fern-api 0.60.22 → 0.60.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1701,7 +1701,7 @@ ${c.indent}`:""}${MGf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1701
1701
  `}),r.replaceAll(/\n$/g,"")}function bFS(e){return e?eh.green(q7.radioOn):q7.radioOff}var cmo=li(kSe(),1);function Fop(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var Bca=class extends F2{_run(t){this.done=t;let r=bV(this.rl),i=r.line.pipe((0,cmo.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,cmo.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(Fop(t,this.opt.mask)):eh.italic.dim("[hidden]"):this.opt.mask?Fop(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 csp=li(Ixs(),1),lsp=li(kSe(),1);var Wca=class extends F2{_run(t){this.done=t,this.editorResult=new lsp.Subject;let r=bV(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,csp.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 Gsp=li(Usp(),1);var Hsp=li(require("readline"),1),$sp=li(Wsp(),1),uzi=class{constructor(t){this.rl||=Hsp.default.createInterface(x3S(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 x3S(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 $sp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Gca=class extends uzi{constructor(t={}){super(t),this.log=(0,Gsp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return Sca(this.rl,this.bottomBar.split(`
1703
1703
  `).length),this}updateBottomBar(t){return Sca(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&&amo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var rcp=li(Ksp(),1),icp=li(WCs(),1),ncp=li(ecp(),1),eq=li(kSe(),1),acp=li(xsa(),1);var Bmo=li(kSe(),1),tcp=li(xsa(),1),xmo=function(e,t,r){return typeof e[t]!="function"?(0,Bmo.of)(e):(0,Bmo.from)((0,tcp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Qca={isPlainObject:rcp.default,set:ncp.default,get:icp.default},Kmn=class extends uzi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Qca.isPlainObject(r)?{...r}:{},Qca.isPlainObject(t)&&(t=Object.values(t).every(n=>Qca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,eq.from)(t):t;return this.process=i.pipe((0,eq.concatMap)(this.processQuestion.bind(this)),(0,eq.publish)()),this.process.connect(),this.process.pipe((0,eq.reduce)((n,a)=>(Qca.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,eq.defer)(()=>(0,eq.of)(t).pipe((0,eq.concatMap)(this.setDefaultType.bind(this)),(0,eq.concatMap)(this.filterIfRunnable.bind(this)),(0,eq.concatMap)(()=>xmo(t,"message",this.answers)),(0,eq.concatMap)(()=>xmo(t,"default",this.answers)),(0,eq.concatMap)(()=>xmo(t,"choices",this.answers)),(0,eq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,eq.defer)(()=>(0,eq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,eq.defer)(()=>(0,eq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Qca.get(this.answers,t.name)!==void 0)return(0,eq.empty)();if(t.when===!1)return(0,eq.empty)();if(typeof t.when!="function")return(0,eq.of)(t);let{answers:r}=this;return(0,eq.defer)(()=>(0,eq.from)((0,acp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,eq.filter)(i=>i!=null)))}};function ocp(e){let t=function(r,i){let n;try{n=new Kmn(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",Eca),this.registerPrompt("input",ZIi),this.registerPrompt("number",Mca),this.registerPrompt("confirm",Aca),this.registerPrompt("rawlist",qca),this.registerPrompt("expand",Tca),this.registerPrompt("checkbox",Cca),this.registerPrompt("password",Bca),this.registerPrompt("editor",Wca)},t.restoreDefaultPrompts(),t}var Gxs=ocp();function Z3S(e,t){Gxs.registerPrompt(e,t)}function k3S(){Gxs.restoreDefaultPrompts()}var e7S={prompt:Gxs,ui:{BottomBar:Gca,Prompt:Kmn},createPromptModule:ocp,registerPrompt:Z3S,restoreDefaultPrompts:k3S,Separator:zie},Imo=e7S;var ylp=li(ucp()),E2S="4.2.1",j5t;(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"})(j5t||(j5t={}));function M2S(e,t){if(!e)throw new Error(t)}function A2S(e){return e?.replace(/\/+$/,"")}async function q2S(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 T2S(){return new Date().getTime()}function slp(){return new Date().toISOString()}function vlp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var nla=String.fromCharCode,clp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ymo={};function C2S(e,t){if(!Ymo[e]){Ymo[e]={};for(let r=0;r<e.length;r++)Ymo[e][e.charAt(r)]=r}return Ymo[e][t]}var ala={compressToBase64:function(e){if(e==null)return"";let t=ala._compress(e,6,function(r){return clp.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:ala._decompress(e.length,32,function(t){return C2S(clp,e.charAt(t))})},compress:function(e){return ala._compress(e,16,function(t){return nla(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,f="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(f=e.charAt(P),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=b++,n[f]=!0),s=o+f,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(f)}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:ala._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,f=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,f),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},qIs=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 Xmo="0123456789abcdef",Zmo=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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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}},TIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??B2S()}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 Zmo.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,Zmo.ofInner(t)}},B2S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),llp,flp=()=>x2S().toString(),x2S=()=>(llp||(llp=new TIs)).generate(),kmo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},ola=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function dlp(e){return typeof e=="object"&&(e instanceof kmo||e instanceof ola)}var CIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new qIs,this._isInitialized=!1,M2S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=A2S(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:dlp},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(j5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j5t.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=flp();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(f=>f.json()).catch(f=>{this._events.emit("error",f)})}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 f=l[t];return f===void 0&&(f=!1),f}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 f=l[t];return f===void 0?null:f}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),f=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:f,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:slp(),uuid:i?.uuid?i.uuid:flp()};(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(j5t.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(j5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=vlp(()=>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(j5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(j5t.Queue)||[];this.setPersistedProperty(j5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:slp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${T2S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,f=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ala.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,f)}catch(s){throw s instanceof ola||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 f=new AbortController;return setTimeout(()=>f.abort(),l),f.signal}),await q2S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new ola(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new kmo(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(j5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!dlp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},BIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},xIs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!xIs){let e=ulp();xIs=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 blp=xIs,I2S=1152921504606847e3,z2S=["is_not"],ePo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},L2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},IIs=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||blp,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 f of this.featureFlags)if(t===f.key){l=f;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(f){f instanceof L2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}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 f=>{try{let s=this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let o=await this.computeFeatureFlagPayloadLocally(f.key,s);o&&(u[f.key]=o)}catch(s){s instanceof L2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new L2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let f=this.groupTypeMapping[String(l)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new L2("Flag has unknown group type index");if(!(f 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[f];return this.matchFeatureFlagProperties(t,i[f],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,f=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of f)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 L2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new L2("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 f=l.type,s=!1;if(f==="cohort"?s=Olp(l,n,this.cohorts,this.debugMode):s=glp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&plp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=plp(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 ePo("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 ePo&&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=vlp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function plp(e,t,r=""){let i=(0,ylp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/I2S}function glp(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 L2("Operator is_not_set is not supported")}else throw new L2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!z2S.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 f(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 _lp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return _lp(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"?f(u,String(n),a):f(u,s,a):f(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=R2S(String(n));if(s==null&&(s=hlp(n)),s==null)throw new L2(`Invalid date: ${n}`);let o=hlp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new L2(`Unknown operator: ${a}`)}}function Olp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new L2("can't match cohort without a given cohort property value");let a=r[n];return mlp(a,t,r,i)}function mlp(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 f=mlp(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let f;l.type==="cohort"?f=Olp(l,t,r,i):f=glp(l,t);let s=l.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("can't match cohort without a given cohort property value");return n==="AND"}}function _lp(e){try{return new RegExp(e),!0}catch{return!1}}function hlp(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 L2(`${e} is in an invalid date format`)}else throw new L2(`The date provided ${e} must be a string, number, or date object`)}function R2S(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 N2S=30*1e3,F2S=50*1e3,rPn=class extends CIs{constructor(t,r={}){super(t,r),this._memoryStorage=new BIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new IIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:N2S,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||F2S}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):blp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return E2S}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:f}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:f})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:f,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,f,s);f=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,f,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:f,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),f==null&&(f=!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||{},f=this.addLocalPersonAndGroupProperties(t,i,u,l);u=f.allPersonProperties,l=f.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}}},zIs=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})}};zIs.POSTHOG_ID_TAG="posthog_distinct_id";var tPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new rPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.60.22",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ula=class{async sendEvent(){}async identify(){}async flush(){}};var iPn=require("fs/promises"),Slp=require("os"),Dlp=require("path");var Plp=li(require("crypto")),iPo=new Uint8Array(256),rPo=iPo.length;function RIs(){return rPo>iPo.length-16&&(Plp.default.randomFillSync(iPo),rPo=0),iPo.slice(rPo,rPo+=16)}var mV=[];for(let e=0;e<256;++e)mV.push((e+256).toString(16).slice(1));function jlp(e,t=0){return mV[e[t+0]]+mV[e[t+1]]+mV[e[t+2]]+mV[e[t+3]]+"-"+mV[e[t+4]]+mV[e[t+5]]+"-"+mV[e[t+6]]+mV[e[t+7]]+"-"+mV[e[t+8]]+mV[e[t+9]]+"-"+mV[e[t+10]]+mV[e[t+11]]+mV[e[t+12]]+mV[e[t+13]]+mV[e[t+14]]+mV[e[t+15]]}var wlp=li(require("crypto")),NIs={randomUUID:wlp.default.randomUUID};function L2S(e,t,r){if(NIs.randomUUID&&!t&&!e)return NIs.randomUUID();e=e||{};let i=e.random||(e.rng||RIs)();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 jlp(i)}var Uie=L2S;var U2S="id",V2S=".fern",sla=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new rPn(r),this.userId=t==null?void 0:GEs(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.60.22",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Lu(Hl.of((0,Slp.homedir)()),Xa.of(V2S),Xa.of(U2S));await Cf(t)||(await(0,iPn.mkdir)((0,Dlp.dirname)(t),{recursive:!0}),await(0,iPn.writeFile)(t,Uie())),this.persistedDistinctId=(await(0,iPn.readFile)(t)).toString()}return this.persistedDistinctId}};var FIs;async function nPn(){return FIs==null&&(FIs=await W2S()),FIs}async function W2S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ula;let r=await ayo();return r!=null?new sla({token:r,posthogApiKey:e}):await $gn()!=null?new tPo({posthogApiKey:e}):new sla({token:void 0,posthogApiKey:e})}catch{return new ula}}function cla(e,t){return function(){return e.apply(t,arguments)}}var{toString:H2S}=Object.prototype,{getPrototypeOf:UIs}=Object,aPo=(e=>t=>{let r=H2S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),w5t=e=>(e=e.toLowerCase(),t=>aPo(t)===e),oPo=e=>t=>typeof t===e,{isArray:aPn}=Array,lla=oPo("undefined");function $2S(e){return e!==null&&!lla(e)&&e.constructor!==null&&!lla(e.constructor)&&tDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mlp=w5t("ArrayBuffer");function G2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mlp(e.buffer),t}var Q2S=oPo("string"),tDe=oPo("function"),Alp=oPo("number"),uPo=e=>e!==null&&typeof e=="object",J2S=e=>e===!0||e===!1,nPo=e=>{if(aPo(e)!=="object")return!1;let t=UIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},K2S=w5t("Date"),Y2S=w5t("File"),X2S=w5t("Blob"),Z2S=w5t("FileList"),k2S=e=>uPo(e)&&tDe(e.pipe),e4S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||tDe(e.append)&&((t=aPo(e))==="formdata"||t==="object"&&tDe(e.toString)&&e.toString()==="[object FormData]"))},t4S=w5t("URLSearchParams"),[r4S,i4S,n4S,a4S]=["ReadableStream","Request","Response","Headers"].map(w5t),o4S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fla(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),aPn(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 qlp(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 dzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tlp=e=>!lla(e)&&e!==dzi;function LIs(){let{caseless:e}=Tlp(this)&&this||{},t={},r=(i,n)=>{let a=e&&qlp(t,n)||n;nPo(t[a])&&nPo(i)?t[a]=LIs(t[a],i):nPo(i)?t[a]=LIs({},i):aPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&fla(arguments[i],r);return t}var u4S=(e,t,r,{allOwnKeys:i}={})=>(fla(t,(n,a)=>{r&&tDe(n)?e[a]=cla(n,r):e[a]=n},{allOwnKeys:i}),e),s4S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),c4S=(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)},l4S=(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&&UIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},f4S=(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},d4S=e=>{if(!e)return null;if(aPn(e))return e;let t=e.length;if(!Alp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},p4S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&UIs(Uint8Array)),_4S=(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])}},h4S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},y4S=w5t("HTMLFormElement"),v4S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Elp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),b4S=w5t("RegExp"),Clp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};fla(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},g4S=e=>{Clp(e,(t,r)=>{if(tDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(tDe(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+"'")})}})},O4S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return aPn(e)?i(e):i(String(e).split(t)),r},m4S=()=>{},P4S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function j4S(e){return!!(e&&tDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var w4S=e=>{let t=new Array(10),r=(i,n)=>{if(uPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=aPn(i)?[]:{};return fla(i,(u,l)=>{let f=r(u,n+1);!lla(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},S4S=w5t("AsyncFunction"),D4S=e=>e&&(uPo(e)||tDe(e))&&tDe(e.then)&&tDe(e.catch),Blp=((e,t)=>e?setImmediate:t?((r,i)=>(dzi.addEventListener("message",({source:n,data:a})=>{n===dzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),dzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",tDe(dzi.postMessage)),E4S=typeof queueMicrotask<"u"?queueMicrotask.bind(dzi):typeof process<"u"&&process.nextTick||Blp,ds={isArray:aPn,isArrayBuffer:Mlp,isBuffer:$2S,isFormData:e4S,isArrayBufferView:G2S,isString:Q2S,isNumber:Alp,isBoolean:J2S,isObject:uPo,isPlainObject:nPo,isReadableStream:r4S,isRequest:i4S,isResponse:n4S,isHeaders:a4S,isUndefined:lla,isDate:K2S,isFile:Y2S,isBlob:X2S,isRegExp:b4S,isFunction:tDe,isStream:k2S,isURLSearchParams:t4S,isTypedArray:p4S,isFileList:Z2S,forEach:fla,merge:LIs,extend:u4S,trim:o4S,stripBOM:s4S,inherits:c4S,toFlatObject:l4S,kindOf:aPo,kindOfTest:w5t,endsWith:f4S,toArray:d4S,forEachEntry:_4S,matchAll:h4S,isHTMLForm:y4S,hasOwnProperty:Elp,hasOwnProp:Elp,reduceDescriptors:Clp,freezeMethods:g4S,toObjectSet:O4S,toCamelCase:v4S,noop:m4S,toFiniteNumber:P4S,findKey:qlp,global:dzi,isContextDefined:Tlp,isSpecCompliantForm:j4S,toJSONObject:w4S,isAsyncFn:S4S,isThenable:D4S,setImmediate:Blp,asap:E4S};function oPn(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(oPn,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 xlp=oPn.prototype,Ilp={};["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=>{Ilp[e]={value:e}});Object.defineProperties(oPn,Ilp);Object.defineProperty(xlp,"isAxiosError",{value:!0});oPn.from=(e,t,r,i,n,a)=>{let u=Object.create(xlp);return ds.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),oPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ep=oPn;var zlp=li(Cia(),1),sPo=zlp.default;function VIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function Nlp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function Rlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Nlp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function M4S(e){return ds.isArray(e)&&!e.some(VIs)}var A4S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function q4S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(sPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!ds.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(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(!f&&ds.isBlob(O))throw new Ep("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&M4S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=Nlp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?Rlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return VIs(O)?!0:(t.append(Rlp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(A4S,{defaultVisitor:o,convertValue:s,isVisitable:VIs});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 mfi=q4S;function Flp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Llp(e,t){this._pairs=[],e&&mfi(e,this,t)}var Ulp=Llp.prototype;Ulp.append=function(t,r){this._pairs.push([t,r])};Ulp.toString=function(t){let r=t?function(i){return t.call(this,i,Flp)}:Flp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vlp=Llp;function T4S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function pzi(e,t,r){if(!t)return e;let i=r&&r.encode||T4S;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 WIs=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)})}},HIs=WIs;var uPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Glp=li(require("crypto"),1);var Wlp=li(require("url"),1),Hlp=Wlp.default.URLSearchParams;var $Is="abcdefghijklmnopqrstuvwxyz",$lp="0123456789",Qlp={DIGIT:$lp,ALPHA:$Is,ALPHA_DIGIT:$Is+$Is.toUpperCase()+$lp},C4S=(e=16,t=Qlp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Glp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Jlp={isNode:!0,classes:{URLSearchParams:Hlp,FormData:sPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Qlp,generateString:C4S,protocols:["http","https","file","data"]};var JIs={};jo(JIs,{hasBrowserEnv:()=>QIs,hasStandardBrowserEnv:()=>B4S,hasStandardBrowserWebWorkerEnv:()=>x4S,navigator:()=>GIs,origin:()=>I4S});var QIs=typeof window<"u"&&typeof document<"u",GIs=typeof navigator=="object"&&navigator||void 0,B4S=QIs&&(!GIs||["ReactNative","NativeScript","NS"].indexOf(GIs.product)<0),x4S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",I4S=QIs&&window.location.href||"http://localhost";var AM={...JIs,...Jlp};function KIs(e,t){return mfi(e,new AM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return AM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function z4S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function R4S(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 N4S(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),f=a>=r.length;return u=!u&&ds.isArray(n)?n.length:u,f?(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]=R4S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t(z4S(i),n,r,0)}),r}return null}var cPo=N4S;function F4S(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 YIs={transitional:uPn,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(cPo(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 KIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return mfi(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),F4S(t)):t}],transformResponse:[function(t){let r=this.transitional||YIs.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"?Ep.from(l,Ep.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:AM.classes.FormData,Blob:AM.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=>{YIs.headers[e]={}});var sPn=YIs;var L4S=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"]),Klp=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&&amo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var rcp=li(Ksp(),1),icp=li(WCs(),1),ncp=li(ecp(),1),eq=li(kSe(),1),acp=li(xsa(),1);var Bmo=li(kSe(),1),tcp=li(xsa(),1),xmo=function(e,t,r){return typeof e[t]!="function"?(0,Bmo.of)(e):(0,Bmo.from)((0,tcp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Qca={isPlainObject:rcp.default,set:ncp.default,get:icp.default},Kmn=class extends uzi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Qca.isPlainObject(r)?{...r}:{},Qca.isPlainObject(t)&&(t=Object.values(t).every(n=>Qca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,eq.from)(t):t;return this.process=i.pipe((0,eq.concatMap)(this.processQuestion.bind(this)),(0,eq.publish)()),this.process.connect(),this.process.pipe((0,eq.reduce)((n,a)=>(Qca.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,eq.defer)(()=>(0,eq.of)(t).pipe((0,eq.concatMap)(this.setDefaultType.bind(this)),(0,eq.concatMap)(this.filterIfRunnable.bind(this)),(0,eq.concatMap)(()=>xmo(t,"message",this.answers)),(0,eq.concatMap)(()=>xmo(t,"default",this.answers)),(0,eq.concatMap)(()=>xmo(t,"choices",this.answers)),(0,eq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,eq.defer)(()=>(0,eq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,eq.defer)(()=>(0,eq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Qca.get(this.answers,t.name)!==void 0)return(0,eq.empty)();if(t.when===!1)return(0,eq.empty)();if(typeof t.when!="function")return(0,eq.of)(t);let{answers:r}=this;return(0,eq.defer)(()=>(0,eq.from)((0,acp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,eq.filter)(i=>i!=null)))}};function ocp(e){let t=function(r,i){let n;try{n=new Kmn(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",Eca),this.registerPrompt("input",ZIi),this.registerPrompt("number",Mca),this.registerPrompt("confirm",Aca),this.registerPrompt("rawlist",qca),this.registerPrompt("expand",Tca),this.registerPrompt("checkbox",Cca),this.registerPrompt("password",Bca),this.registerPrompt("editor",Wca)},t.restoreDefaultPrompts(),t}var Gxs=ocp();function Z3S(e,t){Gxs.registerPrompt(e,t)}function k3S(){Gxs.restoreDefaultPrompts()}var e7S={prompt:Gxs,ui:{BottomBar:Gca,Prompt:Kmn},createPromptModule:ocp,registerPrompt:Z3S,restoreDefaultPrompts:k3S,Separator:zie},Imo=e7S;var ylp=li(ucp()),E2S="4.2.1",j5t;(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"})(j5t||(j5t={}));function M2S(e,t){if(!e)throw new Error(t)}function A2S(e){return e?.replace(/\/+$/,"")}async function q2S(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 T2S(){return new Date().getTime()}function slp(){return new Date().toISOString()}function vlp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var nla=String.fromCharCode,clp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ymo={};function C2S(e,t){if(!Ymo[e]){Ymo[e]={};for(let r=0;r<e.length;r++)Ymo[e][e.charAt(r)]=r}return Ymo[e][t]}var ala={compressToBase64:function(e){if(e==null)return"";let t=ala._compress(e,6,function(r){return clp.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:ala._decompress(e.length,32,function(t){return C2S(clp,e.charAt(t))})},compress:function(e){return ala._compress(e,16,function(t){return nla(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,f="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(f=e.charAt(P),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=b++,n[f]=!0),s=o+f,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(f)}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:ala._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,f=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,f),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},qIs=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 Xmo="0123456789abcdef",Zmo=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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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}},TIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??B2S()}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 Zmo.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,Zmo.ofInner(t)}},B2S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),llp,flp=()=>x2S().toString(),x2S=()=>(llp||(llp=new TIs)).generate(),kmo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},ola=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function dlp(e){return typeof e=="object"&&(e instanceof kmo||e instanceof ola)}var CIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new qIs,this._isInitialized=!1,M2S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=A2S(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:dlp},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(j5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j5t.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=flp();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(f=>f.json()).catch(f=>{this._events.emit("error",f)})}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 f=l[t];return f===void 0&&(f=!1),f}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 f=l[t];return f===void 0?null:f}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),f=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:f,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:slp(),uuid:i?.uuid?i.uuid:flp()};(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(j5t.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(j5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=vlp(()=>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(j5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(j5t.Queue)||[];this.setPersistedProperty(j5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:slp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${T2S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,f=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ala.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,f)}catch(s){throw s instanceof ola||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 f=new AbortController;return setTimeout(()=>f.abort(),l),f.signal}),await q2S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new ola(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new kmo(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(j5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!dlp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},BIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},xIs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!xIs){let e=ulp();xIs=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 blp=xIs,I2S=1152921504606847e3,z2S=["is_not"],ePo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},L2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},IIs=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||blp,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 f of this.featureFlags)if(t===f.key){l=f;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(f){f instanceof L2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}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 f=>{try{let s=this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let o=await this.computeFeatureFlagPayloadLocally(f.key,s);o&&(u[f.key]=o)}catch(s){s instanceof L2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new L2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let f=this.groupTypeMapping[String(l)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new L2("Flag has unknown group type index");if(!(f 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[f];return this.matchFeatureFlagProperties(t,i[f],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,f=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of f)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 L2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new L2("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 f=l.type,s=!1;if(f==="cohort"?s=Olp(l,n,this.cohorts,this.debugMode):s=glp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&plp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=plp(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 ePo("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 ePo&&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=vlp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function plp(e,t,r=""){let i=(0,ylp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/I2S}function glp(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 L2("Operator is_not_set is not supported")}else throw new L2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!z2S.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 f(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 _lp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return _lp(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"?f(u,String(n),a):f(u,s,a):f(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=R2S(String(n));if(s==null&&(s=hlp(n)),s==null)throw new L2(`Invalid date: ${n}`);let o=hlp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new L2(`Unknown operator: ${a}`)}}function Olp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new L2("can't match cohort without a given cohort property value");let a=r[n];return mlp(a,t,r,i)}function mlp(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 f=mlp(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let f;l.type==="cohort"?f=Olp(l,t,r,i):f=glp(l,t);let s=l.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("can't match cohort without a given cohort property value");return n==="AND"}}function _lp(e){try{return new RegExp(e),!0}catch{return!1}}function hlp(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 L2(`${e} is in an invalid date format`)}else throw new L2(`The date provided ${e} must be a string, number, or date object`)}function R2S(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 N2S=30*1e3,F2S=50*1e3,rPn=class extends CIs{constructor(t,r={}){super(t,r),this._memoryStorage=new BIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new IIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:N2S,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||F2S}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):blp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return E2S}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:f}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:f})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:f,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,f,s);f=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,f,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:f,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),f==null&&(f=!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||{},f=this.addLocalPersonAndGroupProperties(t,i,u,l);u=f.allPersonProperties,l=f.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}}},zIs=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})}};zIs.POSTHOG_ID_TAG="posthog_distinct_id";var tPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new rPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.60.23",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ula=class{async sendEvent(){}async identify(){}async flush(){}};var iPn=require("fs/promises"),Slp=require("os"),Dlp=require("path");var Plp=li(require("crypto")),iPo=new Uint8Array(256),rPo=iPo.length;function RIs(){return rPo>iPo.length-16&&(Plp.default.randomFillSync(iPo),rPo=0),iPo.slice(rPo,rPo+=16)}var mV=[];for(let e=0;e<256;++e)mV.push((e+256).toString(16).slice(1));function jlp(e,t=0){return mV[e[t+0]]+mV[e[t+1]]+mV[e[t+2]]+mV[e[t+3]]+"-"+mV[e[t+4]]+mV[e[t+5]]+"-"+mV[e[t+6]]+mV[e[t+7]]+"-"+mV[e[t+8]]+mV[e[t+9]]+"-"+mV[e[t+10]]+mV[e[t+11]]+mV[e[t+12]]+mV[e[t+13]]+mV[e[t+14]]+mV[e[t+15]]}var wlp=li(require("crypto")),NIs={randomUUID:wlp.default.randomUUID};function L2S(e,t,r){if(NIs.randomUUID&&!t&&!e)return NIs.randomUUID();e=e||{};let i=e.random||(e.rng||RIs)();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 jlp(i)}var Uie=L2S;var U2S="id",V2S=".fern",sla=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new rPn(r),this.userId=t==null?void 0:GEs(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.60.23",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Lu(Hl.of((0,Slp.homedir)()),Xa.of(V2S),Xa.of(U2S));await Cf(t)||(await(0,iPn.mkdir)((0,Dlp.dirname)(t),{recursive:!0}),await(0,iPn.writeFile)(t,Uie())),this.persistedDistinctId=(await(0,iPn.readFile)(t)).toString()}return this.persistedDistinctId}};var FIs;async function nPn(){return FIs==null&&(FIs=await W2S()),FIs}async function W2S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ula;let r=await ayo();return r!=null?new sla({token:r,posthogApiKey:e}):await $gn()!=null?new tPo({posthogApiKey:e}):new sla({token:void 0,posthogApiKey:e})}catch{return new ula}}function cla(e,t){return function(){return e.apply(t,arguments)}}var{toString:H2S}=Object.prototype,{getPrototypeOf:UIs}=Object,aPo=(e=>t=>{let r=H2S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),w5t=e=>(e=e.toLowerCase(),t=>aPo(t)===e),oPo=e=>t=>typeof t===e,{isArray:aPn}=Array,lla=oPo("undefined");function $2S(e){return e!==null&&!lla(e)&&e.constructor!==null&&!lla(e.constructor)&&tDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mlp=w5t("ArrayBuffer");function G2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mlp(e.buffer),t}var Q2S=oPo("string"),tDe=oPo("function"),Alp=oPo("number"),uPo=e=>e!==null&&typeof e=="object",J2S=e=>e===!0||e===!1,nPo=e=>{if(aPo(e)!=="object")return!1;let t=UIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},K2S=w5t("Date"),Y2S=w5t("File"),X2S=w5t("Blob"),Z2S=w5t("FileList"),k2S=e=>uPo(e)&&tDe(e.pipe),e4S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||tDe(e.append)&&((t=aPo(e))==="formdata"||t==="object"&&tDe(e.toString)&&e.toString()==="[object FormData]"))},t4S=w5t("URLSearchParams"),[r4S,i4S,n4S,a4S]=["ReadableStream","Request","Response","Headers"].map(w5t),o4S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fla(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),aPn(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 qlp(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 dzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tlp=e=>!lla(e)&&e!==dzi;function LIs(){let{caseless:e}=Tlp(this)&&this||{},t={},r=(i,n)=>{let a=e&&qlp(t,n)||n;nPo(t[a])&&nPo(i)?t[a]=LIs(t[a],i):nPo(i)?t[a]=LIs({},i):aPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&fla(arguments[i],r);return t}var u4S=(e,t,r,{allOwnKeys:i}={})=>(fla(t,(n,a)=>{r&&tDe(n)?e[a]=cla(n,r):e[a]=n},{allOwnKeys:i}),e),s4S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),c4S=(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)},l4S=(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&&UIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},f4S=(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},d4S=e=>{if(!e)return null;if(aPn(e))return e;let t=e.length;if(!Alp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},p4S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&UIs(Uint8Array)),_4S=(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])}},h4S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},y4S=w5t("HTMLFormElement"),v4S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Elp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),b4S=w5t("RegExp"),Clp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};fla(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},g4S=e=>{Clp(e,(t,r)=>{if(tDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(tDe(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+"'")})}})},O4S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return aPn(e)?i(e):i(String(e).split(t)),r},m4S=()=>{},P4S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function j4S(e){return!!(e&&tDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var w4S=e=>{let t=new Array(10),r=(i,n)=>{if(uPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=aPn(i)?[]:{};return fla(i,(u,l)=>{let f=r(u,n+1);!lla(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},S4S=w5t("AsyncFunction"),D4S=e=>e&&(uPo(e)||tDe(e))&&tDe(e.then)&&tDe(e.catch),Blp=((e,t)=>e?setImmediate:t?((r,i)=>(dzi.addEventListener("message",({source:n,data:a})=>{n===dzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),dzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",tDe(dzi.postMessage)),E4S=typeof queueMicrotask<"u"?queueMicrotask.bind(dzi):typeof process<"u"&&process.nextTick||Blp,ds={isArray:aPn,isArrayBuffer:Mlp,isBuffer:$2S,isFormData:e4S,isArrayBufferView:G2S,isString:Q2S,isNumber:Alp,isBoolean:J2S,isObject:uPo,isPlainObject:nPo,isReadableStream:r4S,isRequest:i4S,isResponse:n4S,isHeaders:a4S,isUndefined:lla,isDate:K2S,isFile:Y2S,isBlob:X2S,isRegExp:b4S,isFunction:tDe,isStream:k2S,isURLSearchParams:t4S,isTypedArray:p4S,isFileList:Z2S,forEach:fla,merge:LIs,extend:u4S,trim:o4S,stripBOM:s4S,inherits:c4S,toFlatObject:l4S,kindOf:aPo,kindOfTest:w5t,endsWith:f4S,toArray:d4S,forEachEntry:_4S,matchAll:h4S,isHTMLForm:y4S,hasOwnProperty:Elp,hasOwnProp:Elp,reduceDescriptors:Clp,freezeMethods:g4S,toObjectSet:O4S,toCamelCase:v4S,noop:m4S,toFiniteNumber:P4S,findKey:qlp,global:dzi,isContextDefined:Tlp,isSpecCompliantForm:j4S,toJSONObject:w4S,isAsyncFn:S4S,isThenable:D4S,setImmediate:Blp,asap:E4S};function oPn(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(oPn,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 xlp=oPn.prototype,Ilp={};["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=>{Ilp[e]={value:e}});Object.defineProperties(oPn,Ilp);Object.defineProperty(xlp,"isAxiosError",{value:!0});oPn.from=(e,t,r,i,n,a)=>{let u=Object.create(xlp);return ds.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),oPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ep=oPn;var zlp=li(Cia(),1),sPo=zlp.default;function VIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function Nlp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function Rlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Nlp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function M4S(e){return ds.isArray(e)&&!e.some(VIs)}var A4S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function q4S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(sPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!ds.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(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(!f&&ds.isBlob(O))throw new Ep("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&M4S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=Nlp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?Rlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return VIs(O)?!0:(t.append(Rlp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(A4S,{defaultVisitor:o,convertValue:s,isVisitable:VIs});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 mfi=q4S;function Flp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Llp(e,t){this._pairs=[],e&&mfi(e,this,t)}var Ulp=Llp.prototype;Ulp.append=function(t,r){this._pairs.push([t,r])};Ulp.toString=function(t){let r=t?function(i){return t.call(this,i,Flp)}:Flp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vlp=Llp;function T4S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function pzi(e,t,r){if(!t)return e;let i=r&&r.encode||T4S;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 WIs=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)})}},HIs=WIs;var uPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Glp=li(require("crypto"),1);var Wlp=li(require("url"),1),Hlp=Wlp.default.URLSearchParams;var $Is="abcdefghijklmnopqrstuvwxyz",$lp="0123456789",Qlp={DIGIT:$lp,ALPHA:$Is,ALPHA_DIGIT:$Is+$Is.toUpperCase()+$lp},C4S=(e=16,t=Qlp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Glp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Jlp={isNode:!0,classes:{URLSearchParams:Hlp,FormData:sPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Qlp,generateString:C4S,protocols:["http","https","file","data"]};var JIs={};jo(JIs,{hasBrowserEnv:()=>QIs,hasStandardBrowserEnv:()=>B4S,hasStandardBrowserWebWorkerEnv:()=>x4S,navigator:()=>GIs,origin:()=>I4S});var QIs=typeof window<"u"&&typeof document<"u",GIs=typeof navigator=="object"&&navigator||void 0,B4S=QIs&&(!GIs||["ReactNative","NativeScript","NS"].indexOf(GIs.product)<0),x4S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",I4S=QIs&&window.location.href||"http://localhost";var AM={...JIs,...Jlp};function KIs(e,t){return mfi(e,new AM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return AM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function z4S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function R4S(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 N4S(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),f=a>=r.length;return u=!u&&ds.isArray(n)?n.length:u,f?(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]=R4S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t(z4S(i),n,r,0)}),r}return null}var cPo=N4S;function F4S(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 YIs={transitional:uPn,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(cPo(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 KIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return mfi(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),F4S(t)):t}],transformResponse:[function(t){let r=this.transitional||YIs.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"?Ep.from(l,Ep.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:AM.classes.FormData,Blob:AM.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=>{YIs.headers[e]={}});var sPn=YIs;var L4S=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"]),Klp=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]&&L4S[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Ylp=Symbol("internals");function dla(e){return e&&String(e).trim().toLowerCase()}function lPo(e){return e===!1||e==null?e:ds.isArray(e)?e.map(lPo):String(e)}function U4S(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 V4S=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function XIs(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 W4S(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function H4S(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 cPn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,f,s){let o=dla(f);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||f]=lPo(l))}let u=(l,f)=>ds.forEach(l,(s,o)=>a(s,o,f));if(ds.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(ds.isString(t)&&(t=t.trim())&&!V4S(t))u(Klp(t),r);else if(ds.isHeaders(t))for(let[l,f]of t.entries())a(f,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=dla(t),t){let i=ds.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return U4S(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=dla(t),t){let i=ds.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||XIs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=dla(u),u){let l=ds.findKey(i,u);l&&(!r||XIs(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||XIs(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]=lPo(n),delete r[a];return}let l=t?W4S(a):String(a).trim();l!==a&&delete r[a],r[l]=lPo(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[Ylp]=this[Ylp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=dla(u);i[l]||(H4S(n,u),i[l]=!0)}return ds.isArray(t)?t.forEach(a):a(t),this}};cPn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ds.reduceDescriptors(cPn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ds.freezeMethods(cPn);var bz=cPn;function pla(e,t){let r=this||sPn,i=t||r,n=bz.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 _la(e){return!!(e&&e.__CANCEL__)}function Xlp(e,t,r){Ep.call(this,e??"canceled",Ep.ERR_CANCELED,t,r),this.name="CanceledError"}ds.inherits(Xlp,Ep,{__CANCEL__:!0});var rDe=Xlp;function eXt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Ep("Request failed with status code "+r.status,[Ep.ERR_BAD_REQUEST,Ep.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function ZIs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function kIs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function _zi(e,t,r){let i=!ZIs(t);return e&&i||r==!1?kIs(e,t):t}var pfp=li(Kca(),1),_fp=li(require("http"),1),hfp=li(require("https"),1),yfp=li(require("util"),1),vfp=li(oIs(),1),$Jr=li(require("zlib"),1);var hzi="1.8.2";function hla(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var $4S=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function ezs(e,t,r){let i=r&&r.Blob||AM.classes.Blob,n=hla(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=$4S.exec(e);if(!a)throw new Ep("Invalid URL",Ep.ERR_INVALID_URL);let u=a[1],l=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),l?"base64":"utf8");if(t){if(!i)throw new Ep("Blob is not supported",Ep.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Ep("Unsupported protocol "+n,Ep.ERR_NOT_SUPPORT)}var yzi=li(require("stream"),1);var Zlp=li(require("stream"),1);var tzs=Symbol("internals"),rzs=class extends Zlp.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[tzs]={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[tzs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[tzs],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,f=1e3/l,s=a/f,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,E=u,q,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&&(P=g.subarray(E),g=g.subarray(0,E)),c(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},izs=rzs;var bfp=require("events");var efp=li(require("util"),1),tfp=require("stream");var{asyncIterator:klp}=Symbol,G4S=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[klp]?yield*e[klp]():yield e},fPo=G4S;var Q4S=AM.ALPHABET.ALPHA_DIGIT+"-_",yla=typeof TextEncoder=="function"?new TextEncoder:new efp.default.TextEncoder,Pfi=`\r
1707
1707
  `,J4S=yla.encode(Pfi),K4S=2,nzs=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)}"`:""}${Pfi}`;n?r=yla.encode(String(r).replace(/\r?\n|\r\n?/g,Pfi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Pfi}`,this.headers=yla.encode(a+Pfi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+K4S,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ds.isTypedArray(t)?yield t:yield*fPo(t),yield J4S}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},Y4S=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+AM.generateString(n,Q4S)}=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=yla.encode("--"+a+Pfi),l=yla.encode("--"+a+"--"+Pfi+Pfi),f=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new nzs(c,b);return f+=g.size,g});f+=u.byteLength*s.length,f=ds.toFiniteNumber(f);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(o["Content-Length"]=f),t&&t(o),tfp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},rfp=Y4S;var ifp=li(require("stream"),1),azs=class extends ifp.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)}},nfp=azs;var X4S=(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,afp=X4S;function Z4S(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(f){let s=Date.now(),o=i[a];u||(u=s),r[n]=f,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 ofp=Z4S;function k4S(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 ufp=k4S;var HJr=(e,t,r=3)=>{let i=0,n=ofp(50,250);return ufp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,f=u-i,s=n(f),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:f,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)},lPn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},fPn=e=>(...t)=>ds.asap(()=>e(...t));var sfp={flush:$Jr.default.constants.Z_SYNC_FLUSH,finishFlush:$Jr.default.constants.Z_SYNC_FLUSH},e8S={flush:$Jr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:$Jr.default.constants.BROTLI_OPERATION_FLUSH},cfp=ds.isFunction($Jr.default.createBrotliDecompress),{http:t8S,https:r8S}=vfp.default,i8S=/https:?/,lfp=AM.protocols.map(e=>e+":"),ffp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function n8S(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function gfp(e,t,r){let i=t;if(!i&&i!==!1){let n=pfp.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){gfp(a,t,a.href)}}var a8S=typeof process<"u"&&ds.kindOf(process)==="process",o8S=e=>new Promise((t,r)=>{let i,n,a=(f,s)=>{n||(n=!0,i&&i(f,s))},u=f=>{a(f),t(f)},l=f=>{a(f,!0),r(f)};e(u,l,f=>i=f).catch(l)}),u8S=({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)}},dfp=(e,t)=>u8S(ds.isObject(e)?e:{address:e,family:t}),Ofp=a8S&&function(t){return o8S(async function(i,n,a){let{data:u,lookup:l,family:f}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let Se=afp(l,Qe=>ds.isArray(Qe)?Qe:[Qe]);l=(Qe,St,Ee)=>{Se(Qe,St,(Te,It,je)=>{if(Te)return Ee(Te);let Ot=ds.isArray(It)?It.map(at=>dfp(at)):[dfp(It,je)];St.all?Ee(Te,Ot):Ee(Te,Ot[0].address,Ot[0].family)})}}let m=new bfp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Se,Qe)=>{b=!0,Qe&&(g=!0,P())});function E(Se){m.emit("abort",!Se||Se.type?new rDe(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=_zi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(q,AM.hasBrowserEnv?AM.origin:void 0),D=A.protocol||lfp[0];if(D==="data:"){let Se;if(c!=="GET")return eXt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=ezs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Ep.from(Qe,Ep.ERR_BAD_REQUEST,t)}return s==="text"?(Se=Se.toString(o),(!o||o==="utf8")&&(Se=ds.stripBOM(Se))):s==="stream"&&(Se=yzi.default.Readable.from(Se)),eXt(i,n,{data:Se,status:200,statusText:"OK",headers:new bz,config:t})}if(lfp.indexOf(D)===-1)return n(new Ep("Unsupported protocol "+D,Ep.ERR_BAD_REQUEST,t));let C=bz.from(t.headers).normalize();C.set("User-Agent","axios/"+hzi,!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=rfp(u,Qe=>{C.set(Qe)},{tag:`axios-${hzi}-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 yfp.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=yzi.default.Readable.from(fPo(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 Ep("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Ep.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Ep("Request body larger than maxBodyLength limit",Ep.ERR_BAD_REQUEST,t))}let Y=ds.toFiniteNumber(C.getContentLength());ds.isArray(x)?(L=x[0],V=x[1]):L=V=x,u&&(z||L)&&(ds.isStream(u)||(u=yzi.default.Readable.from(u,{objectMode:!1})),u=yzi.default.pipeline([u,new izs({maxRate:ds.toFiniteNumber(L)})],ds.noop),z&&u.on("progress",ffp(u,lPn(Y,HJr(fPn(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=pzi(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"+(cfp?", br":""),!1);let fe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:f,beforeRedirect:n8S,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,gfp(fe,t.proxy,D+"//"+A.hostname+(A.port?":"+A.port:"")+fe.path));let me,_e=i8S.test(fe.protocol);if(fe.agent=_e?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=_e?hfp.default:_fp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),me=_e?r8S:t8S),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 izs({maxRate:ds.toFiniteNumber(V)});$&&at.on("progress",ffp(at,lPn(Ee,HJr(fPn($),!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($Jr.default.createUnzip(sfp)),delete Qe.headers["content-encoding"];break;case"deflate":St.push(new nfp),St.push($Jr.default.createUnzip(sfp)),delete Qe.headers["content-encoding"];break;case"br":cfp&&(St.push($Jr.default.createBrotliDecompress(e8S)),delete Qe.headers["content-encoding"])}Te=St.length>1?yzi.default.pipeline(St,ds.noop):St[0];let je=yzi.default.finished(Te,()=>{je(),P()}),Ot={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new bz(Qe.headers),config:t,request:It};if(s==="stream")Ot.data=Te,eXt(i,n,Ot);else{let at=[],he=0;Te.on("data",function(bt){at.push(bt),he+=bt.length,t.maxContentLength>-1&&he>t.maxContentLength&&(g=!0,Te.destroy(),n(new Ep("maxContentLength size of "+t.maxContentLength+" exceeded",Ep.ERR_BAD_RESPONSE,t,It)))}),Te.on("aborted",function(){if(g)return;let bt=new Ep("stream has been aborted",Ep.ERR_BAD_RESPONSE,t,It);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Ep.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(Ep.from(bt,null,t,Ot.request,Ot))}eXt(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(Ep.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 Ep("error trying to parse `config.timeout` to int",Ep.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||uPn;t.timeoutErrorMessage&&(St=t.timeoutErrorMessage),n(new Ep(St,Ee.clarifyTimeoutError?Ep.ETIMEDOUT:Ep.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 rDe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var mfp=AM.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,AM.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(AM.origin),AM.navigator&&/(msie|trident)/i.test(AM.navigator.userAgent)):()=>!0;var Pfp=AM.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 jfp=e=>e instanceof bz?{...e}:e;function S5t(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 f={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(jfp(s),jfp(o),c,!0)};return ds.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=f[o]||n,b=c(e[o],t[o],o);ds.isUndefined(b)&&c!==l||(r[o]=b)}),r}var dPo=e=>{let t=S5t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=bz.from(u),t.url=pzi(_zi(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let f;if(ds.isFormData(r)){if(AM.hasStandardBrowserEnv||AM.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((f=u.getContentType())!==!1){let[s,...o]=f?f.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(AM.hasStandardBrowserEnv&&(i&&ds.isFunction(i)&&(i=i(t)),i||i!==!1&&mfp(t.url))){let s=n&&a&&Pfp.read(a);s&&u.set(n,s)}return t};var s8S=typeof XMLHttpRequest<"u",wfp=s8S&&function(e){return new Promise(function(r,i){let n=dPo(e),a=n.data,u=bz.from(n.headers).normalize(),{responseType:l,onUploadProgress:f,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function E(){if(!P)return;let A=bz.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:A,config:e,request:P};eXt(function($){r($),m()},function($){i($),m()},C),P=null}"onloadend"in P?P.onloadend=E:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(E)},P.onabort=function(){P&&(i(new Ep("Request aborted",Ep.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new Ep("Network Error",Ep.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||uPn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Ep(D,C.clarifyTimeoutError?Ep.ETIMEDOUT:Ep.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&ds.forEach(u.toJSON(),function(D,C){P.setRequestHeader(C,D)}),ds.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),l&&l!=="json"&&(P.responseType=n.responseType),s&&([b,O]=HJr(s,!0),P.addEventListener("progress",b)),f&&P.upload&&([c,g]=HJr(f),P.upload.addEventListener("progress",c),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=A=>{P&&(i(!A||A.type?new rDe(null,e,P):A),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=hla(n.url);if(q&&AM.protocols.indexOf(q)===-1){i(new Ep("Unsupported protocol "+q+":",Ep.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var c8S=(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 Ep?o:new rDe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Ep(`timeout ${t} of ms exceeded`,Ep.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:f}=i;return f.unsubscribe=()=>ds.asap(l),f}},Sfp=c8S;var l8S=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},f8S=async function*(e,t){for await(let r of d8S(e))yield*l8S(r,t)},d8S=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()}},ozs=(e,t,r,i)=>{let n=f8S(e,t),a=0,u,l=f=>{u||(u=!0,i&&i(f))};return new ReadableStream({async pull(f){try{let{done:s,value:o}=await n.next();if(s){l(),f.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}f.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(f){return l(f),n.return()}},{highWaterMark:2})};var _Po=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Efp=_Po&&typeof ReadableStream=="function",p8S=_Po&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Mfp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},_8S=Efp&&Mfp(()=>{let e=!1,t=new Request(AM.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Dfp=64*1024,uzs=Efp&&Mfp(()=>ds.isReadableStream(new Response("").body)),pPo={stream:uzs&&(e=>e.body)};_Po&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!pPo[t]&&(pPo[t]=ds.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Ep(`Response type '${t}' is not supported`,Ep.ERR_NOT_SUPPORT,i)})})})(new Response);var h8S=async e=>{if(e==null)return 0;if(ds.isBlob(e))return e.size;if(ds.isSpecCompliantForm(e))return(await new Request(AM.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 p8S(e)).byteLength},y8S=async(e,t)=>{let r=ds.toFiniteNumber(e.getContentLength());return r??h8S(t)},Afp=_Po&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:f,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=dPo(e);s=s?(s+"").toLowerCase():"text";let g=Sfp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(f&&_8S&&r!=="get"&&r!=="head"&&(P=await y8S(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]=lPn(P,HJr(fPn(f)));i=ozs(C.body,Dfp,$,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=uzs&&(s==="stream"||s==="response");if(uzs&&(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&&lPn(z,HJr(fPn(l),!0))||[];q=new Response(ozs(q.body,Dfp,$,()=>{x&&x(),m&&m()}),C)}s=s||"text";let D=await pPo[ds.findKey(pPo,s)||"text"](q,e);return!A&&m&&m(),await new Promise((C,z)=>{eXt(C,z,{data:D,headers:bz.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 Ep("Network Error",Ep.ERR_NETWORK,e,O),{cause:E.cause||E}):Ep.from(E,E&&E.code,e,O)}});var szs={http:Ofp,xhr:wfp,fetch:Afp};ds.forEach(szs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var qfp=e=>`- ${e}`,v8S=e=>ds.isFunction(e)||e===null||e===!1,hPo={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,!v8S(r)&&(i=szs[(u=String(r)).toLowerCase()],i===void 0))throw new Ep(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,f])=>`adapter ${l} `+(f===!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}${STp.default.cursorHide}`});var Q_a=li(ici(),1);function X5s(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.`),pPn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function s9s({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!KTp(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,f)=>l.generatorName.localeCompare(f.generatorName)||l.currentVersion.localeCompare(f.currentVersion));for(let l of u)n+=`
1942
1942
  ${await o_D(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?pPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function o_D(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 u_D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await XTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=rci(o.name,c),g=await lJt({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 XTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,f,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][f]==null&&(u.versions[l][f]={});let c=rci(s.name,o),b=await lJt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][f][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function XTp({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 Q8t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let f of l.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,u)}})}))}function ZTp(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 f=Zie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function yAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await u_D({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[f,s]of Object.entries(l.versions))u.push(...ZTp(s,f,t.logger));else u.push(...ZTp(l.versions,void 0,t.logger))}return u}var tha=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 G1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Q1n=e=>e!==null&&typeof e=="object";var rha=(...e)=>{for(let t of e)if((!Q1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return f9s({},...e)},c9s=(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 vAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:f9s(e[r]??[],t[r]??[])}var l9s=(e={},t={})=>({beforeRequest:vAo(e,t,"beforeRequest"),beforeRetry:vAo(e,t,"beforeRetry"),afterResponse:vAo(e,t,"afterResponse"),beforeError:vAo(e,t,"beforeError")}),f9s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Q1n(n)){for(let[a,u]of Object.entries(n))Q1n(u)&&a in t&&(u=f9s(t[a],u)),t={...t,[a]:u};Q1n(n.hooks)&&(i=l9s(i,n.hooks),t.hooks=i),Q1n(n.headers)&&(r=c9s(r,n.headers),t.headers=r)}return t};var kTp=(()=>{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})(),eCp=typeof globalThis.AbortController=="function",tCp=typeof globalThis.ReadableStream=="function",rCp=typeof globalThis.FormData=="function",bAo=["get","post","put","patch","head","delete"],s_D=()=>{};s_D();var iCp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},gAo=2147483647,OAo=Symbol("stop"),nCp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},aCp={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 uCp=e=>bAo.includes(e)?e.toUpperCase():e,c_D=["get","put","head","delete","options","trace"],l_D=[408,413,429,500,502,503,504],f_D=[413,429,503],oCp={limit:2,methods:c_D,statusCodes:l_D,afterStatusCodes:f_D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},sCp=(e={})=>{if(typeof e=="number")return{...oCp,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{...oCp,...e}};async function d9s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new G1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function p9s(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 cCp=(e,t)=>{let r={};for(let i in t)!(i in aCp)&&!(i in nCp)&&!(i in e)&&(r[i]=t[i]);return r};var iha=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>gAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${gAo}`);await Promise.resolve();let l=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let f=new tha(l,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!tCp)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,f]of Object.entries(iCp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);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:c9s(this._input.headers,r.headers),hooks:l9s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:uCp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:sCp(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(eCp){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(kTp&&(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);(rCp&&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 G1n)throw t;if(t instanceof tha){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),gAo);if(this._retryCount<1)throw r;await p9s(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})===OAo)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=cCp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):d9s(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:f,value:s}=await u.read();if(f){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 _9s=e=>{let t=(r,i)=>iha.create(r,rha(e,i));for(let r of bAo)t[r]=(i,n)=>iha.create(i,rha(e,n,{method:r}));return t.create=r=>_9s(rha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),_9s(rha(e,r))),t.stop=OAo,t},d_D=_9s(),lCp=d_D;var BCp=li(CCp(),1);function g9s(e){let t=(0,BCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var EBp=li(DBp(),1),MBp=li(ici(),1),B9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},x9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function I9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??g9s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,EBp.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,l&&(f.authorization=`${l.type} ${l.token}`);let s;try{s=await lCp(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new B9s(e):c}if(t.allVersions)return s;let o=new x9s(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=MBp.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 cha(e,t){let{version:r}=await I9s(e.toLowerCase(),t);return r}async function Gdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cha(e.packageName,{version:t?"prerelease":"latest"})}var ABp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],CAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;isLocal;constructor(t,{isLocal:r}){this.ttyAwareLogger=new hAo(t),this.isLocal=r??!1;let i=this.getPackageName(),n=this.getPackageVersion(),a=this.getCliName();(i==null||n==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:n,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.60.22"}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 yre}failWithoutThrowing(t,r){this.didSucceed=!1,fAo({message:t,error:r,logger:this.logger})}async exit(){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await nPn()).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 YTp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1943
+ `,i?pPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function o_D(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 u_D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await XTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=rci(o.name,c),g=await lJt({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 XTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,f,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][f]==null&&(u.versions[l][f]={});let c=rci(s.name,o),b=await lJt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][f][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function XTp({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 Q8t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let f of l.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,u)}})}))}function ZTp(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 f=Zie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function yAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await u_D({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[f,s]of Object.entries(l.versions))u.push(...ZTp(s,f,t.logger));else u.push(...ZTp(l.versions,void 0,t.logger))}return u}var tha=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 G1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Q1n=e=>e!==null&&typeof e=="object";var rha=(...e)=>{for(let t of e)if((!Q1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return f9s({},...e)},c9s=(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 vAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:f9s(e[r]??[],t[r]??[])}var l9s=(e={},t={})=>({beforeRequest:vAo(e,t,"beforeRequest"),beforeRetry:vAo(e,t,"beforeRetry"),afterResponse:vAo(e,t,"afterResponse"),beforeError:vAo(e,t,"beforeError")}),f9s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Q1n(n)){for(let[a,u]of Object.entries(n))Q1n(u)&&a in t&&(u=f9s(t[a],u)),t={...t,[a]:u};Q1n(n.hooks)&&(i=l9s(i,n.hooks),t.hooks=i),Q1n(n.headers)&&(r=c9s(r,n.headers),t.headers=r)}return t};var kTp=(()=>{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})(),eCp=typeof globalThis.AbortController=="function",tCp=typeof globalThis.ReadableStream=="function",rCp=typeof globalThis.FormData=="function",bAo=["get","post","put","patch","head","delete"],s_D=()=>{};s_D();var iCp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},gAo=2147483647,OAo=Symbol("stop"),nCp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},aCp={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 uCp=e=>bAo.includes(e)?e.toUpperCase():e,c_D=["get","put","head","delete","options","trace"],l_D=[408,413,429,500,502,503,504],f_D=[413,429,503],oCp={limit:2,methods:c_D,statusCodes:l_D,afterStatusCodes:f_D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},sCp=(e={})=>{if(typeof e=="number")return{...oCp,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{...oCp,...e}};async function d9s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new G1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function p9s(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 cCp=(e,t)=>{let r={};for(let i in t)!(i in aCp)&&!(i in nCp)&&!(i in e)&&(r[i]=t[i]);return r};var iha=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>gAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${gAo}`);await Promise.resolve();let l=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let f=new tha(l,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!tCp)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,f]of Object.entries(iCp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);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:c9s(this._input.headers,r.headers),hooks:l9s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:uCp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:sCp(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(eCp){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(kTp&&(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);(rCp&&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 G1n)throw t;if(t instanceof tha){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),gAo);if(this._retryCount<1)throw r;await p9s(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})===OAo)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=cCp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):d9s(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:f,value:s}=await u.read();if(f){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 _9s=e=>{let t=(r,i)=>iha.create(r,rha(e,i));for(let r of bAo)t[r]=(i,n)=>iha.create(i,rha(e,n,{method:r}));return t.create=r=>_9s(rha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),_9s(rha(e,r))),t.stop=OAo,t},d_D=_9s(),lCp=d_D;var BCp=li(CCp(),1);function g9s(e){let t=(0,BCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var EBp=li(DBp(),1),MBp=li(ici(),1),B9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},x9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function I9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??g9s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,EBp.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,l&&(f.authorization=`${l.type} ${l.token}`);let s;try{s=await lCp(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new B9s(e):c}if(t.allVersions)return s;let o=new x9s(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=MBp.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 cha(e,t){let{version:r}=await I9s(e.toLowerCase(),t);return r}async function Gdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cha(e.packageName,{version:t?"prerelease":"latest"})}var ABp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],CAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;isLocal;constructor(t,{isLocal:r}){this.ttyAwareLogger=new hAo(t),this.isLocal=r??!1;let i=this.getPackageName(),n=this.getPackageVersion(),a=this.getCliName();(i==null||n==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:n,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.60.23"}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 yre}failWithoutThrowing(t,r){this.didSucceed=!1,fAo({message:t,error:r,logger:this.logger})}async exit(){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await nPn()).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 YTp({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=l_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 J_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 yre}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await nPn()).sendEvent(t)}logger=EQr(this.log.bind(this));constructTaskInitForWorkspace(t){let r=qBp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?qBp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=ABp[this.numTasks++%ABp.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=>gsi.indexOf(i.level)>=gsi.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 Gdi({cliEnvironment:this.environment,includePreReleases:t}),i=Zie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await yAo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await $5s({message:t,default:r})}async getInput(t){return await G5s({message:t.message,default:t.default})}};function qBp(e){return`[${e}]:`}var fQp=require("fs/promises");function kie({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 oUp=require("fs/promises");var r9t=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 mDe=class extends r9t{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 lha=class{context;constructor(t){this.context=t}};var BAo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let f=n!=null?Xh.of(`${n}${l8t}${u}`):Xh.of(u);t[f]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${l8t}${u}`:u,f=i.directories[u];r(f,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(l8t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Xh.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 gNi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new BAo,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 XQr(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"]))TBp(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(TBp(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??$y((cxe(r)+"/"+sBi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Xh.of(XN))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Dto(cxe(yvn.of(`/${t}`)),yvn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Dto(cxe(yvn.of(`/${t}`)),yvn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===Xh.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=>hSe(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=NR(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:NR(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:NR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===nS?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 TBp(e){return e?.header!=null}var ene={openapi:e=>({...e,type:"openapi",_visit:function(t){return ene._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return ene._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 eSn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return eSn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var W5={basic:e=>({...e,type:"basic",_visit:function(t){return W5._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return W5._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return W5._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return W5._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return W5._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 Yg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Yg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Yg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Yg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Yg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Yg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Yg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Yg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Yg._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 tSn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return tSn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return tSn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Qdi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return Qdi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return Qdi._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 CV={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case CV.GenerallyAvailable:return t.generallyAvailable();case CV.Beta:return t.beta();case CV.Deprecated:return t.deprecated();default:return t._other()}}};var $ze={cursor:e=>({...e,type:"cursor",_visit:function(t){return $ze._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return $ze._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return $ze._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 xKr={language:e=>({...e,type:"language",_visit:function(t){return xKr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return xKr._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 BV={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 BV.Curl:return t.curl();case BV.Python:return t.python();case BV.Javascript:return t.javascript();case BV.Typescript:return t.typescript();case BV.Go:return t.go();case BV.Ruby:return t.ruby();case BV.Csharp:return t.csharp();case BV.Java:return t.java();case BV.Js:return t.js();case BV.Node:return t.node();case BV.Ts:return t.ts();case BV.Nodets:return t.nodets();case BV.Golang:return t.golang();case BV.Dotnet:return t.dotnet();case BV.Jvm:return t.jvm();default:return t._other()}}};var i9t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return i9t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return i9t._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 n9t={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return n9t._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return n9t._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 zG={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case zG.Get:return t.get();case zG.Post:return t.post();case zG.Put:return t.put();case zG.Patch:return t.patch();case zG.Delete:return t.delete();case zG.Head:return t.head();case zG.Options:return t.options();case zG.Trace:return t.trace();default:return t._other()}}};var Jdi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Jdi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Jdi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Jdi._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 IKr={file:e=>({...e,type:"file",_visit:function(t){return IKr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return IKr._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 RG={file:e=>({...e,type:"file",_visit:function(t){return RG._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return RG._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return RG._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return RG._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return RG._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return RG._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return RG._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 wj={int:e=>({...e,type:"int",_visit:function(t){return wj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return wj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return wj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return wj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return wj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return wj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return wj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return wj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return wj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return wj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return wj._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 Dx={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Dx._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Dx._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 zKr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return zKr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return zKr._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 PDe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return PDe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return PDe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return PDe._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 DT={file:e=>({...e,type:"file",_visit:function(t){return DT._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return DT._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return DT._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return DT._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return DT._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return DT._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return DT._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 gX={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return gX._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return gX._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 lv={};jo(lv,{AllOfPropertyConflict:()=>wSn,ArraySchema:()=>Kqo,ArraySchemaWithExample:()=>jTo,Availability:()=>WAo,Base64WithExample:()=>bTo,BasicSecurityScheme:()=>GAo,BearerSecurityScheme:()=>QAo,BooleanSchema:()=>Wqo,BooleanWithExample:()=>gTo,BytesResponse:()=>hSn,CasingOverrides:()=>YAo,CommonProperty:()=>iTo,CommonPropertyWithExample:()=>CTo,CursorPagination:()=>Dqo,CustomCodeSample:()=>wqo,CustomCodeSampleLanguage:()=>mqo,CustomCodeSampleSdk:()=>jqo,CustomPagination:()=>Mqo,DateWithExample:()=>vTo,DatetimeWithExample:()=>yTo,DiscriminatedOneOfSchema:()=>tTo,DiscriminatedOneOfSchemaWithExample:()=>qTo,DoubleSchema:()=>Uqo,DoubleWithExample:()=>_To,Encoding:()=>VAo,Endpoint:()=>Aqo,EndpointExample:()=>gSn,EndpointResponseExample:()=>Oqo,EndpointSdkName:()=>UXt,EndpointWithExample:()=>uxp,EnumSchema:()=>aSn,EnumSchemaWithExample:()=>mTo,EnumValue:()=>Xdi,ErrorExample:()=>hqo,FernExample:()=>vqo,FileResponse:()=>pSn,FileSchema:()=>sqo,FloatWithExample:()=>pTo,FullEndpointExample:()=>Sqo,FullExample:()=>iq,FullObjectExample:()=>iqo,FullOneOfExample:()=>aqo,GlobalHeader:()=>$qo,Header:()=>kdi,HeaderExample:()=>bSn,HeaderSecurityScheme:()=>JAo,HeaderWithExample:()=>rpi,HttpEndpointServer:()=>ySn,HttpError:()=>yqo,HttpErrorWithExample:()=>sTo,HttpMethod:()=>sSn,IdempotencyHeader:()=>Gqo,Int64WithExample:()=>lTo,IntSchema:()=>Fqo,IntWithExample:()=>cTo,JsonRequest:()=>dqo,JsonRequestWithExample:()=>aTo,JsonResponse:()=>_Sn,JsonResponseWithExample:()=>ESn,KeyValuePair:()=>nqo,LiteralExample:()=>rqo,LiteralSchema:()=>jSn,LiteralSchemaValue:()=>Qqo,LongSchema:()=>Lqo,MapSchema:()=>Yqo,MapSchemaWithExample:()=>wTo,MultipartRequest:()=>dSn,MultipartRequestProperty:()=>fqo,MultipartRequestPropertyEncoding:()=>lqo,MultipartSchema:()=>cqo,NamedFullExample:()=>WXt,Namespace:()=>XAo,NamespaceId:()=>tqo,NullableSchema:()=>Zqo,NullableSchemaWithExample:()=>DTo,OauthSecurityScheme:()=>kAo,ObjectProperty:()=>eTo,ObjectPropertyConflictInfo:()=>SSn,ObjectPropertyWithExample:()=>ATo,ObjectSchema:()=>Jqo,ObjectSchemaWithExample:()=>ETo,OctetStreamRequest:()=>fSn,OffsetPagination:()=>Eqo,OneOfSchema:()=>kqo,OneOfSchemaWithExample:()=>MTo,OpenApiIntermediateRepresentation:()=>axp,OpenApiSource:()=>NAo,OptionalSchema:()=>Xqo,OptionalSchemaWithExample:()=>STo,Pagination:()=>OSn,PathParameter:()=>cSn,PathParameterExample:()=>bqo,PathParameterWithExample:()=>nTo,PrimitiveExample:()=>uSn,PrimitiveSchema:()=>tpi,PrimitiveSchemaValue:()=>Hqo,PrimitiveSchemaValueWithExample:()=>OTo,PrimitiveSchemaWithExample:()=>MSn,PropertyKey:()=>oSn,ProtobufEncoding:()=>UAo,ProtobufSource:()=>FAo,QueryParameter:()=>lSn,QueryParameterExample:()=>vSn,QueryParameterWithExample:()=>DSn,QuerySecurityScheme:()=>KAo,ReferencedSchema:()=>VXt,Request:()=>pqo,RequestWithExample:()=>oTo,Response:()=>_qo,ResponseWithExample:()=>uTo,Schema:()=>ZO,SchemaId:()=>OX,SchemaWithExample:()=>xM,Schemas:()=>Nqo,SdkGroup:()=>ZAo,SdkGroupInfo:()=>oqo,SdkGroupName:()=>Zdi,SecurityScheme:()=>eqo,SecuritySchemeId:()=>$Ao,Server:()=>_ha,Source:()=>LAo,StatusCode:()=>LXt,StreamingResponseExample:()=>gqo,StringSchema:()=>Vqo,StringSchemaWithExample:()=>hTo,SupportedSdkLanguage:()=>Pqo,Tag:()=>HAo,TagId:()=>mX,Tags:()=>uqo,TextResponse:()=>epi,Uint64WithExample:()=>dTo,UintWithExample:()=>fTo,UnDiscriminatedOneOfSchema:()=>rTo,UnDiscriminatedOneOfSchemaWithExample:()=>TTo,UnknownSchemaWithExample:()=>PTo,Webhook:()=>qqo,WebhookExampleCall:()=>PSn,WebhookHttpMethod:()=>mSn,WebhookWithExample:()=>sxp,WebsocketChannel:()=>Rqo,WebsocketHandshake:()=>Tqo,WebsocketHandshakeWithExample:()=>oxp,WebsocketMessageExample:()=>Iqo,WebsocketMessageOrigin:()=>Cqo,WebsocketMessageSchema:()=>Bqo,WebsocketServer:()=>xqo,WebsocketSessionExample:()=>zqo,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>tne,WithInline:()=>hE,WithName:()=>c0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Gze,WithTitle:()=>zO,commons:()=>L9s,example:()=>U9s,finalIr:()=>V9s,parseIr:()=>W9s});var L9s={};jo(L9s,{BasicSecurityScheme:()=>GAo,BearerSecurityScheme:()=>QAo,Encoding:()=>VAo,HeaderSecurityScheme:()=>JAo,Namespace:()=>XAo,NamespaceId:()=>tqo,OauthSecurityScheme:()=>kAo,OpenApiSource:()=>NAo,ProtobufEncoding:()=>UAo,ProtobufSource:()=>FAo,QuerySecurityScheme:()=>KAo,SchemaId:()=>OX,SdkGroup:()=>ZAo,SdkGroupName:()=>Zdi,SecurityScheme:()=>eqo,SecuritySchemeId:()=>$Ao,Server:()=>_ha,Source:()=>LAo,StatusCode:()=>LXt,Tag:()=>HAo,TagId:()=>mX,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>tne,WithInline:()=>hE,WithName:()=>c0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Gze,WithTitle:()=>zO});var At={};jo(At,{JsonError:()=>rSn,ParseError:()=>iSn,any:()=>GBp,bigint:()=>BBp,boolean:()=>QBp,booleanLiteral:()=>$Bp,date:()=>xBp,discriminant:()=>rxp,enum_:()=>IAo,getObjectLikeUtils:()=>a9t,getObjectUtils:()=>ONi,getSchemaUtils:()=>rq,isProperty:()=>Ydi,lazy:()=>IBp,lazyObject:()=>VBp,list:()=>RAo,number:()=>JBp,object:()=>zAo,objectWithoutOptionalProperties:()=>UBp,optional:()=>z9s,property:()=>RBp,record:()=>ZBp,set:()=>kBp,string:()=>KBp,stringLiteral:()=>HBp,transform:()=>R9s,undiscriminatedUnion:()=>txp,union:()=>nxp,unknown:()=>YBp,withParsedProperties:()=>F9s});var tj={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 BM(e,t){return`Expected ${t}. Received ${vhD(e)}.`}function vhD(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 H5(e){return{...e,json:CBp(e.json),parse:CBp(e.parse)}}function CBp(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(`
@@ -2009,7 +2009,7 @@ ${a}]`:`[${e.join(u)}]`},B3o=(e,t,r)=>`let ${e} = ${JZs(t,r)}`,JZs=(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=E3i({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:A,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f+1});if(D.length>0)return D}let g=typeof b=="string"?b:b.type;if(typeof g!="string")return as_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&cS(O.declaration)){let A=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return E3i({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:A,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f+1})}let m=typeof b!="string"&&typeof b.key=="string"?b.key:void 0;if(m==null)return[];let{[m]:P,...E}=c,q=[];return P==null?q.push({message:`Missing property "${m}"`}):q.push(...a9({rawTypeReference:g,example:P,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:f+1})),q.push(...as_(E)),q}function as_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function P7o({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:f}){return dF(t,{alias:s=>Zu_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:f}),enum:s=>ku_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>E3i({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f}),discriminatedUnion:s=>os_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f}),undiscriminatedUnion:s=>es_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f})})}var hs_=/^([+-]?\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)?)?)?)?$/,oiE=/^[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}$/,uiE=/^\d{4}-\d{2}-\d{2}$/,siE=128;function a9({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>siE)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(fJt)){let f=r.resolveType({type:e,file:n});if(f==null)return[];let s=i.parseExampleReference(t);if(s==null)return[];let o=r.resolveNamedType({referenceToNamedType:s.rawTypeReference,file:n});return o==null?[]:LMn({expected:f,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return Cxi({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>ciE({primitiveType:f,example:t}),named:f=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:f,file:n});return s==null?[]:P7o({typeName:s.typeName,typeDeclaration:s.declaration,file:s.file,example:t,typeResolver:r,exampleResolver:i,workspace:a,breadcrumbs:u,depth:l+1})},map:({keyType:f,valueType:s})=>mj(t)?Object.entries(t).flatMap(([o,c])=>[...a9({rawTypeReference:f,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...a9({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):_Re(t,"a map"),list:f=>Array.isArray(t)?t.flatMap((s,o)=>a9({rawTypeReference:f,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):_Re(t,"a list"),set:f=>{if(!Array.isArray(t))return _Re(t,"a list");let s=Gps(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)=>a9({rawTypeReference:f,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:f=>t==null?[]:a9({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:f=>t==null?[]:a9({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return RDe(s=>s===f.boolean,f.boolean.toString())(t);case"string":return RDe(s=>s===f.string,`"${f.string}"`)(t);default:Mo(f)}}}})}function ciE({primitiveType:e,example:t}){return e.v2!=null?wp._visit(e.v2,{integer:r=>liE({example:t,rules:r.validation}),long:()=>ls_(t),uint:()=>us_(t),uint64:()=>ss_(t),double:r=>fiE({example:t,rules:r.validation}),float:()=>cs_(t),boolean:()=>fs_(t),string:r=>diE({example:t,rules:r.validation}),uuid:()=>ds_(t),date:()=>_s_(t),dateTime:()=>ps_(t),base64:()=>FMn(t),bigInteger:()=>FMn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):Zb._visit(e.v1,{integer:()=>ys_(t),long:()=>ls_(t),uint:()=>us_(t),uint64:()=>ss_(t),double:()=>vs_(t),float:()=>cs_(t),boolean:()=>fs_(t),string:()=>FMn(t),uuid:()=>ds_(t),dateTime:()=>ps_(t),date:()=>_s_(t),base64:()=>FMn(t),bigInteger:()=>FMn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function liE({example:e,rules:t}){let r=ys_(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 fiE({example:e,rules:t}){let r=vs_(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 diE({example:e,rules:t}){let r=FMn(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 FMn=RDe(e=>typeof e=="string","a string"),ys_=RDe(e=>Number.isInteger(e),"an integer"),us_=RDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),ss_=RDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),cs_=RDe(e=>typeof e=="number","a float"),vs_=RDe(e=>typeof e=="number","a double"),ls_=RDe(e=>Number.isInteger(e),"an integer"),fs_=RDe(e=>typeof e=="boolean","a boolean"),ds_=RDe(e=>typeof e=="string"&&oiE.test(e),"a UUID"),ps_=RDe(e=>typeof e=="string"&&hs_.test(e),"an ISO 8601 timestamp"),_s_=RDe(e=>typeof e=="string"&&uiE.test(e)&&hs_.test(e),"a date");function RDe(e,t){return r=>e(r)?[]:_Re(r,t)}function LMn({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&&LMn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return LMn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return LMn({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&&LMn({expected:e.container.keyType,actual:t.container.keyType})&&LMn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:piE({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 piE({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 j7o({_enum:e,file:t}){let r=e.enum.map(n=>({...eQ(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:UMn(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 bs_(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 UMn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function Ktc({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return dF(t,{alias:f=>uw.alias({value:gE({example:r,rawTypeBeingExemplified:typeof f=="string"?f:f.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:f=>gs_({typeName:e,rawObject:f,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:f=>{let s=M3i(f);if(!mj(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=f.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 uw.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:V_i(f).name,wireValue:s}),singleUnionType:hiE({rawValueType:b,rawSingleUnionType:c,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,example:r,discriminant:s,discriminantValueForExample:o,workspace:l})})},enum:f=>{if(typeof r!="string"){let s=f.enum.map(o=>typeof o=="string"?o:o.value).join(", ");throw new Error(`Expected one of ${s}. Received ${r}`)}return uw.enum({value:u.casingsGenerator.generateNameAndWireValue({name:bs_(r,f).name,wireValue:r})})},undiscriminatedUnion:f=>{for(let[c,b]of f.union.entries())if(a9({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return uw.undiscriminatedUnion({index:c,singleUnionType:gE({example:r,rawTypeBeingExemplified:typeof b=="string"?b:b.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})});let o=f.union.map(c=>typeof c=="string"?c:c.type).join(", ");throw new Error(`Expected one of ${o}. Received ${r}`)}})}function gE({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}){let{resolvedExample:l,file:f}=a.resolveExampleOrThrow({example:e,file:t}),s=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:Cxi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>_iE({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!mj(l))throw new Error("Example is not an object");return Ph.container(YO.map({map:Object.entries(l).map(([g,O])=>({key:gE({example:g,fileContainingExample:f,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:gE({example:O,fileContainingExample:f,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=>gE({example:b,fileContainingExample:f,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=>gE({example:b,fileContainingExample:f,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>Ph.container(YO.optional({optional:l!=null?gE({example:l,fileContainingExample:f,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?gE({example:l,fileContainingExample:f,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:Ktc({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:f,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Ph.unknown(s)}}),jsonExample:s}}function _iE({example:e,typeBeingExemplified:t}){return Zb._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 gs_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!mj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return uw.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((f,[s,o])=>{let c=Os_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return f;let b=gE({example:o,fileContainingExample:n,rawTypeBeingExemplified:typeof c.rawPropertyType=="string"?c.rawPropertyType:c.rawPropertyType.type,fileContainingRawTypeReference:c.file,typeResolver:a,exampleResolver:u,workspace:l});return f.push({name:n.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),f},[]):[]})}function Os_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:F0a({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function F0a({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"||!cS(u.declaration))throw new Error("Extension is not of a named object");let l=Os_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function hiE({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:i,typeResolver:n,exampleResolver:a,example:u,discriminant:l,discriminantValueForExample:f,workspace:s}){let o=i.casingsGenerator.generateNameAndWireValue({name:NMn({unionKey:f,rawSingleUnionType:t}).name,wireValue:f});if(e==null)return{wireDiscriminantValue:o,shape:lF.noProperties()};let c=Jtc({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!mj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:lF.singleProperty(gE({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!mj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;Fci(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!cS(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:em.generateTypeId(m),object:gs_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:Mo(c)}}function w7o({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=FYr({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...eQ(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 FYr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function ms_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:f}){let s=viE({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:f});return{id:r.name??Yva(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:PiE({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...biE({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:f}),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:FYr({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:gE({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:f}),shape:yiE({queryParameter:b})}}):[],request:giE({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:f}),response:OiE({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:f})}}function yiE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?B2.exploded():B2.single()}function viE({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,variableResolver:a,file:u,workspace:l}){let f=[],s=[],o=[],c=({name:b,pathParameterDeclaration:g,examplePathParameter:O})=>{let m=L0a({parameter:g,variableResolver:a,file:u});return{name:b,value:gE({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=B9t(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],P=e["path-parameters"]?.[g],E=b[g];if(m!=null)f.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(E!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:E,examplePathParameter:O}));else if(P!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:f,endpointPathParameters:o,servicePathParameters:s}}function biE({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:u}){let l=[],f=[];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)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:LZt({headerKey:s,header:c}).name,wireValue:s}),value:gE({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:LZt({headerKey:s,header:b}).name,wireValue:s}),value:gE({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:f,serviceHeaders:l}}function giE({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"&&rua(u)!=null)return;if(!oC(u))return uG.reference(gE({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(!mj(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let l=[];for(let[f,s]of Object.entries(t.request)){let o=u.properties?.[f],c=typeof o=="string"?o:o?.type;if(!(c!=null&&Yxe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:f,property:o}).name,wireValue:f}),value:gE({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=F0a({extends_:u.extends,wirePropertyKey:f,typeResolver:r,file:n});if(b==null)throw new Error("Could not find original type declaration for property: "+f);l.push({name:n.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:f,property:b.rawPropertyType}).name,wireValue:f}),value:gE({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 uG.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function OiE({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?Qq.ok(uC.body(void 0)):xxi(e,t.response,{body:l=>{if(l.error!=null){let f=i.getDeclarationOrThrow(l.error,a);return Qq.error({error:L_i({errorName:l.error,file:a}),body:f.declaration.type!=null?gE({example:l.body,rawTypeBeingExemplified:f.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:f.file,fileContainingExample:a,workspace:u}):void 0})}return Qq.ok(uC.body(miE({endpoint:e,example:l,typeResolver:r,exampleResolver:n,file:a,workspace:u})))},stream:l=>{let f=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return Qq.ok(uC.stream(l.stream.map(s=>{if(f!=null)return gE({example:s,rawTypeBeingExemplified:f,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(g0)))},events:l=>{let f=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return Qq.ok(uC.sse(l.stream.map(({event:s,data:o})=>{if(f==null)return;let c=gE({example:o,rawTypeBeingExemplified:f,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(g0)))}})}function miE({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 gE({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function PiE({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=Wv(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 Ps_({endpoint:e,file:t,typeResolver:r}){return{body:jiE({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function jiE({endpoint:e,file:t,typeResolver:r}){let i=wiE({endpoint:e,file:t,typeResolver:r}),n=SiE({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=iV.fileDownload({...i});break}case"json":{a=iV.json({...i.value});break}case"text":{a=iV.text({...i});break}case"bytes":{a=iV.bytes({...i});break}default:Mo(i)}return SM.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return SM.streaming(n)}}function wiE({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 Yxe(a)!=null?SM.fileDownload({docs:n,v2Examples:void 0}):iua(a)!=null?SM.text({docs:n,v2Examples:void 0}):wJt(a)!=null?SM.bytes({docs:n,v2Examples:void 0}):DiE(i,n,t,r)}}function SiE({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 Kbn(a)?kre.text({docs:n,v2Examples:void 0}):typeof i!="string"&&u==="sse"?kre.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0}):kre.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0})}}function DiE(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?SM.json(GY.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:I0a({typeResolver:i,file:r,resolvedType:u,property:l}),v2Examples:void 0})):SM.json(GY.response({docs:t,responseBodyType:a,v2Examples:void 0}))}function js_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return oG.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 ws_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return oG.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function Ss_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return oG.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 Ds_(e){if(MiE(e))return{type:"offset",offset:C9t(e.offset),results:FZt(e.results),step:e.step!=null?C9t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?FZt(e["has-next-page"]):void 0};if(EiE(e))return{type:"cursor",cursor:C9t(e.cursor),next_cursor:FZt(e.next_cursor),results:FZt(e.results)};if(AiE(e))return{type:"custom",results:FZt(e.results)};throw new Error("Invalid pagination schema")}function EiE(e){return e.cursor!=null}function MiE(e){return e.offset!=null&&e.results!=null}function AiE(e){return"type"in e&&e.type==="custom"}function Es_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=Ds_(n);switch(a.type){case"cursor":return js_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return Ss_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return ws_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:Mo(a)}}function Ms_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=L_i({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function S7o({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function As_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:S7o({source:e}),name:U_i.generateName(r)}}function qs_({file:e,serviceDeclaration:t,sourceResolver:r}){return _Jt(t.source)?Cs_(e,t.source,r,t.transport?.grpc?.["service-name"]):Wxe.http()}function Ts_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=_Jt(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 Wxe.http();if(n&&u){let f=r.source,s=r.transport?.grpc?.["service-name"];return s?Cs_(e,f,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
2012
- ${JSON.stringify(r)}"`)}}function Cs_(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=As_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Wxe.grpc({service:a})}function Bs_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:f,sourceResolver:s,globalErrors:o,workspace:c}){let b=VMn({pathParameters:r["path-parameters"],location:Hxe.Service,file:i,variableResolver:f}),g=qs_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:mne(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:k7(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([P,E])=>hRe({headerKey:P,header:E,file:i})):[],pathParameters:b,encoding:BiE(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([P,E])=>{let q=VMn({pathParameters:B9t(E),location:Hxe.Endpoint,file:i,variableResolver:f}),A={...eQ(E),id:"",name:i.casingsGenerator.generateName(P),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?CiE(E.method):S7.Post,basePath:E["base-path"]!=null?k7(E["base-path"]):void 0,path:k7(E.path),fullPath:k7(E["base-path"]!=null?Wv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Wv(i.rootApiFile["base-path"],r["base-path"],E.path):Wv(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])=>w7o({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>hRe({headerKey:D,header:C,file:i})):[],requestBody:$u_({request:E.request,file:i}),sdkRequest:Yu_({service:r,request:E.request,endpoint:E,endpointKey:P,file:i,typeResolver:a,propertyResolver:u}),response:Ps_({endpoint:E,file:i,typeResolver:a}),errors:[...Ms_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:ms_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:f,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>Xu_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Es_({propertyResolver:u,file:i,endpointName:P,endpointSchema:E}),transport:Ts_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0};return A.id=em.generateEndpointId(O,A),A})}}function VMn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>qiE({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function qiE({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...eQ(t),name:i.casingsGenerator.generateName(e),valueType:TiE({parameter:t,variableResolver:n,file:i}),location:r,variable:$0n(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function TiE({parameter:e,variableResolver:t,file:r}){let i=L0a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function L0a({parameter:e,variableResolver:t,file:r}){let i=D7o({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function D7o({parameter:e,variableResolver:t,file:r}){if($0n(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 CiE(e){switch(e){case"GET":return S7.Get;case"POST":return S7.Post;case"PUT":return S7.Put;case"PATCH":return S7.Patch;case"DELETE":return S7.Delete;default:Mo(e)}}function hRe({headerKey:e,header:t,file:r}){let{name:i}=LZt({headerKey:e,header:t});return{...eQ(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 LZt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function BiE(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Mo(e)}}var xs_="1.0.0";var E7o=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=BDe({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:xs_,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=Wv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Wv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Wv(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??Uie(),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 Is_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new E7o({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var tQ={};jo(tQ,{validateObjectExample:()=>E3i,validateTypeExample:()=>P7o,validateTypeReferenceExample:()=>a9});var M7o=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:em.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(!zs_(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(!zs_(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},f=a.find(s=>s.name.originalName===n.originalName);if(f==null){let s=em.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),f=o}return this.getPackageForFernFilepath(t,u,f)}};function zs_(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 Rs_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var A7o=e=>{let t=CDe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function q7o({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function Ns_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:A7o(n),serviceId:em.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:em.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 Fs_({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:A7o(n),serviceId:em.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:em.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:xiE({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 xiE=({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 Ls_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=Fs_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?Ns_({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 U0a={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}},Ytc={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 Us_(e){return{endpoint:e["get-token"].endpoint,requestProperties:IiE({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ziE({responseProperties:e["get-token"]?.["response-properties"]})}}function Vs_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:RiE({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:NiE({responseProperties:e["refresh-token"]?.["response-properties"]})}}function IiE({requestProperties:e}){if(e==null)return U0a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?C9t(t):U0a.requestProperties.client_id,client_secret:r!=null?C9t(r):U0a.requestProperties.client_secret,scopes:i!=null?C9t(i):U0a.requestProperties.scopes}}function ziE({responseProperties:e}){return Ws_({responseProperties:e,defaultValue:U0a.responseProperties})}function RiE({requestProperties:e}){if(e==null)return Ytc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?C9t(t):Ytc.requestProperties.refresh_token}}function NiE({responseProperties:e}){return Ws_({responseProperties:e,defaultValue:Ytc.responseProperties})}function Ws_({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?FZt(r):t.access_token,expires_in:i!=null?FZt(i):t.expires_in,refresh_token:n!=null?FZt(n):t.refresh_token}}function Js_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Uxe.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return Ixi(e.auth,{single:a=>{let u=Hs_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Uxe.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Uxe.Any,schemes:a.map(u=>Hs_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function Hs_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,f)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return nua(s,{header:o=>NC.header({docs:f,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=>Gs_({file:r,docs:f,rawScheme:o}),bearer:o=>$s_({file:r,docs:f,rawScheme:o}),oauth:o=>Qs_({file:r,docs:f,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return $s_({file:r,docs:void 0,rawScheme:void 0});case"basic":return Gs_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return Qs_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function $s_({file:e,docs:t,rawScheme:r}){return NC.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Gs_({file:e,docs:t,rawScheme:r}){return NC.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 Qs_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return NC.oauth({docs:t,configuration:Mci.clientCredentials(Ls_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Us_(r),refreshTokenEndpoint:Vs_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Ks_({file:e,rawApiFileSchema:t}){if(t.version!=null)return qci.header({header:FiE({file:e,header:t.version.header}),value:LiE({file:e,versionDeclaration:t.version})})}function FiE({file:e,header:t}){return typeof t=="string"?hRe({file:e,headerKey:t,header:{type:"string"}}):hRe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function LiE({file:e,versionDeclaration:t}){return j7o({_enum:{default:t.default,enum:t.values},file:e})}function Ys_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,f]of Object.entries(e.messages??{}))u.push({type:l,availability:mne(f.availability),docs:f.docs,origin:f.origin,body:WiE({body:f.body,file:n}),displayName:f["display-name"]});return{availability:mne(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,f])=>hRe({headerKey:l,header:f,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?VMn({pathParameters:e["path-parameters"],location:Hxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,f])=>{let{name:s}=FYr({queryParameterKey:l,queryParameter:f}),o=n.parseTypeReference(f);return{...eQ(f),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof f!="string"&&f["allow-multiple"]!=null?f["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let f=$iE({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:QiE({channel:e,example:l,pathParams:f}),...f,...GiE({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:FYr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:gE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:UiE({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:ViE({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function UiE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?B2.exploded():B2.single()}function ViE({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!JiE(e.body))return WSe.reference(gE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!mj(t))throw new Error("Example must be an object");let u=[];for(let[l,f]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:l,property:s}).name,wireValue:l}),value:gE({example:f,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=F0a({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:n9({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:gE({example:f,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 WSe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function WiE({body:e,file:t}){return typeof e=="string"?P5.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):HiE(e)?P5.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):P5.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:T9t(e.extends??[]).map(r=>i9({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function HiE(e){return e.type!=null}function $iE({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],f=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=L0a({parameter:o,variableResolver:n,file:a});return{name:s,value:gE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=B9t(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(f({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function GiE({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,f]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:LZt({headerKey:l,header:s}).name,wireValue:l}),value:gE({example:f,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 QiE({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 JiE(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function Xs_({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:gE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:L_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,v2Examples:void 0,displayName:void 0}}var Zs_="content";function ks_(e,t){if(e==null||e.strategy==="status-code")return L8t.statusCode();switch(e.strategy){case"property":return L8t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Zs_,wireValue:Zs_})});default:Mo(e)}}function ec_({readme:e,services:t}){let r=new Xtc(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 Xtc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=YiE({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:KiE(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function KiE(e){let t="";e.fullPath.head.length>0&&(t=Wv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Wv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Wv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function YiE({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 tc_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:em.generateWebhookId(t.fernFilepath,u),availability:mne(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(([f,s])=>hRe({headerKey:f,header:s,file:t})):[],payload:XiE({payload:l.payload,file:t}),examples:l.examples!=null?kiE({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function XiE({payload:e,file:t}){return typeof e=="string"?aV.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):REn(e)?aV.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):aV.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:T9t(e.extends).map(r=>i9({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>ZiE({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?mne(i.availability):void 0,file:t})):[]})}function ZiE({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n9({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function kiE({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:REn(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:gE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!mj(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:gE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function rc_({name:e,source:t}){return jj.userDefined({file:S7o({source:t}),name:U_i.generateName(e)})}function ic_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=enE({type:e.proto.type});if(t!=null)return t}}function enE({type:e}){switch(e){case"google.protobuf.Any":return jj.wellKnown(Zf.any());case"google.protobuf.Api":return jj.wellKnown(Zf.api());case"google.protobuf.BoolValue":return jj.wellKnown(Zf.boolValue());case"google.protobuf.BytesValue":return jj.wellKnown(Zf.bytesValue());case"google.protobuf.DoubleValue":return jj.wellKnown(Zf.doubleValue());case"google.protobuf.Duration":return jj.wellKnown(Zf.duration());case"google.protobuf.Empty":return jj.wellKnown(Zf.empty());case"google.protobuf.Enum":return jj.wellKnown(Zf.enum());case"google.protobuf.EnumValue":return jj.wellKnown(Zf.enumValue());case"google.protobuf.Field":return jj.wellKnown(Zf.field());case"google.protobuf.FieldCardinality":return jj.wellKnown(Zf.fieldCardinality());case"google.protobuf.FieldKind":return jj.wellKnown(Zf.fieldKind());case"google.protobuf.FieldMask":return jj.wellKnown(Zf.fieldMask());case"google.protobuf.FloatVlaue":return jj.wellKnown(Zf.floatValue());case"google.protobuf.Int32Value":return jj.wellKnown(Zf.int32Value());case"google.protobuf.Int64Value":return jj.wellKnown(Zf.int64Value());case"google.protobuf.ListValue":return jj.wellKnown(Zf.listValue());case"google.protobuf.Method":return jj.wellKnown(Zf.method());case"google.protobuf.Mixin":return jj.wellKnown(Zf.mixin());case"google.protobuf.NullValue":return jj.wellKnown(Zf.nullValue());case"google.protobuf.Option":return jj.wellKnown(Zf.option());case"google.protobuf.SourceContext":return jj.wellKnown(Zf.sourceContext());case"google.protobuf.StringValue":return jj.wellKnown(Zf.stringValue());case"google.protobuf.Struct":return jj.wellKnown(Zf.struct());case"google.protobuf.Syntax":return jj.wellKnown(Zf.syntax());case"google.protobuf.Timestamp":return jj.wellKnown(Zf.timestamp());case"google.protobuf.Type":return jj.wellKnown(Zf.type());case"google.protobuf.Uint32Value":return jj.wellKnown(Zf.uint32Value());case"google.protobuf.Uint64Value":return jj.wellKnown(Zf.uint64Value());case"google.protobuf.Value":return jj.wellKnown(Zf.value())}}function nc_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=pz(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&cS(a.declaration)){let u=pz(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([f,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[f,o]});return KO.object({extends:T9t(a.declaration.extends).map(f=>i9({typeName:f,file:t})),properties:x0a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function ac_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return Lxe(i)?nc_({generic:i,file:t,typeResolver:r}):KO.alias({aliasOf:t.parseTypeReference(e),resolvedType:tnE({aliasOf:i,file:t,typeResolver:r})})}function tnE({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return nV.primitive(i.originalTypeReference.primitive);case"container":return nV.container(i.originalTypeReference.container);case"unknown":return nV.unknown();case"named":{let n=cS(i.declaration)?U8t.Object:Lci(i.declaration)?U8t.Union:$8t(i.declaration)?U8t.Enum:G0n(i.declaration)?U8t.UndiscriminatedUnion:Mo(i.declaration);return nV.named({name:i.name,shape:n})}}}function oc_({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 uc_(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 ktc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new Ztc}){let n=dF(e,{alias:u=>{let l=typeof u=="string"?u:u.type,f=pz(l);if(f!=null){let s=new Set(f.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=pz(o.typeName)?.arguments;if(cS(o.declaration)){let b=uc_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>uc_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(f=>typeof f=="string"?f:f.type)),l.push(...Object.values(u.union).reduce((f,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&f.push(o),f},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,f)=>{let s=typeof f=="string"?f:f.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=x2({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:f,valueType:s})=>[...f,...s],list:f=>f,optional:f=>f,nullable:f=>f,set:f=>f,named:f=>[f],literal:()=>[],unknown:()=>[]}});for(let f of l){let s=i9({typeName:f,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t});if(Lxe(o.typeName))continue;a.push(...ktc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var Ztc=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 sc_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=eQ(t),f=i9({typeName:e,file:r}),s=ktc({typeDeclaration:t,file:r,typeResolver:i}),o={};cS(t)&&(o=DFi(t.properties??{}));let c=inE({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:unE(t),name:f,shape:rnE({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:nnE({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:Ktc({typeName:f,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 rnE({typeDeclaration:e,file:t,typeResolver:r}){return dF(e,{alias:i=>ac_({alias:i,file:t,typeResolver:r}),object:i=>Wu_({object:i,file:t}),discriminatedUnion:i=>ns_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>oc_({union:i,file:t}),enum:i=>KO.enum(j7o({_enum:i,file:t}))})}function inE({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=ic_({encoding:t.encoding});if(a!=null)return KQr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return KQr.proto(rc_({source:n,name:r}))}function nnE({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?anE(e.encoding):onE(t)}function anE(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function onE(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function unE(e){if(typeof e!="string"&&"inline"in e)return e.inline}function cc_(e,t){let r=t[e];if(r==null)throw new DQr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function lc_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,cnE({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>snE({endpoint:i,ir:e}))}]))}}function snE({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>fc_(r,t))}}}function cnE({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>fc_(r,t))}}}return e}function fc_(e,t){let r=erc(e.typeId,t);return dc_({objectTypeDeclaration:r,ir:t})}function erc(e,t){let r=cc_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return erc(r.shape.resolvedType.name.typeId,t)}throw new DQr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function dc_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=erc(i.typeId,t);return dc_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function _c_({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:Az({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=Az({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 Az({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=>Az({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Ph.container(YO.set({...i,set:i.set.map(n=>Az({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?Az({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?Az({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=Az({filteredIr:e,exampleTypeReference:n.key}),u=Az({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=Az({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Ph.named({...r,shape:uw.enum(i)})}),object:i=>({...t,shape:Ph.named({...r,shape:uw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:Az({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=_c_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=Az({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function trc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function lnE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function pc_({filteredIr:e,headers:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function fnE({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=Az({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=Az({filteredIr:e,exampleTypeReference:r});return i!==void 0?uG.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function dnE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Qq.ok(uC.body(i!=null?Az({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Qq.ok(uC.stream(i.map(n=>Az({filteredIr:e,exampleTypeReference:n})).filter(g0))),sse:i=>Qq.ok(uC.sse(i.map(({event:n,data:a})=>{let u=Az({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(g0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Qq.error({error:r,body:i!=null?Az({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function rrc({filteredIr:e,example:t}){return{...t,rootPathParameters:trc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:trc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:trc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:pc_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:pc_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:lnE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?fnE({filteredIr:e,requestBody:t.request}):void 0,response:dnE({filteredIr:e,response:t.response})}}function hc_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:uw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:uw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:Az({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=_c_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:uw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=Az({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:uw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function yc_({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:F_i({referencedIn:t,importPath:l})}}var A3i=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=r0({relativeFilepath:n,definitionFile:a,casingsGenerator:U_i,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[f,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:f,endpoint:s,file:l})}),eFi(this.workspace,(n,a)=>{let u=r0({relativeFilepath:n,definitionFile:a,casingsGenerator:U_i,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,f]of Object.entries(a.service?.endpoints??{}))f.method===t&&f.path===r&&(i={endpointId:l,endpoint:f,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new zxi().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=yc_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var q3i=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=zDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:r0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var NDe=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(mj(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(`\\${fJt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(fJt))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(fJt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(fJt.length),exampleName:n}}};var T7o=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:eie.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:eie.query(w7o({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:eie.body(u)}}if(oC(i.body)){let u=$tc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:eie.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:eie.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Htc({typeResolver:this.typeResolver,file:z0a(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 h1=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=zDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=pz(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let f=n.types?.[l];return f!=null?{typeName:l,declaration:f,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return x2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Bf.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Bf.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Bf.container(Tv.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Bf.container(Tv.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Bf.container(Tv.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Bf.container(Tv.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Bf.container(Tv.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Bf.container(Tv.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(Fci(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=N0a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||cne(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 I9t=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:NYr({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 C7o(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function FF({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:f,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=BDe({generationLanguage:t,keywords:r,smartCasing:i}),O=new EFi(a),m=NYr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),P=(e.definition.rootApiFile.contents.errors??[]).map(at=>({error:L_i({errorName:at,file:m}),docs:void 0})),E=new h1(e),q=new A3i(e),A=new T7o(E,q),D=new q3i(e),C=new NDe(E),z=new I9t,$={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:Ks_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:B0a(e.definition.rootApiFile.contents.docs),auth:Js_({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,he])=>hRe({headerKey:at,header:he,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([at,he])=>hRe({headerKey:at,header:he,file:m})):[],types:{},errors:{},services:{},constants:Rs_(g),environments:zEn({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:ks_(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:VMn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:Hxe.Root,variableResolver:z}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([at,he])=>({docs:typeof he!="string"?he.docs:void 0,id:at,name:m.casingsGenerator.generateName(at),type:m.parseTypeReference(he)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},x=new M7o,L=at=>{x.addSubpackage(at.fernFilepath),aw(at.definitionFile,{imports:Go,docs:he=>{he!=null&&x.addDocs(at.fernFilepath,he)},types:he=>{if(he!=null)for(let[Pe,bt]of Object.entries(he)){if(Lxe(Pe))continue;let Dt=sc_({typeName:Pe,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=em.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,Vu_(bt))}},errors:he=>{if(he==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[bt,Dt]of Object.entries(he)){let sr=Xs_({errorName:bt,errorDeclaration:Dt,file:at,typeResolver:E,exampleResolver:C,workspace:e}),ur=em.generateErrorId(sr.name);$.errors[ur]=sr,x.addError(ur,sr),O.addError(sr)}},service:he=>{if(he==null)return;let Pe=Bs_({rootDefaultUrl:at.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:he,file:at,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:P,variableResolver:z,workspace:e}),bt=em.generateServiceId(Pe.name);$.services[bt]=Pe,x.addService(bt,Pe);let Dt={};Pe.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=he.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),Dt[sr.name.originalName]=sr}),he.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,he.audiences),Object.entries(he.endpoints).map(([sr,ur])=>{let ni=Dt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ni],ur.audiences)})},webhooks:he=>{if(he==null)return;let Pe=em.generateWebhookGroupId(at.fernFilepath),bt=tc_({webhooks:he,file:at,typeResolver:E,exampleResolver:C,workspace:e}),Dt={};for(let sr of bt)Dt[sr.name.originalName]=sr;Object.entries(he).forEach(([sr,ur])=>{let ni=Dt[sr];ni!=null&&(O.addWebhook(at.fernFilepath,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(at.fernFilepath,ni,ur.audiences))}),$.webhookGroups[Pe]=bt,x.addWebhookGroup(Pe,at.fernFilepath)},channel:he=>{if(he==null)return;let Pe=em.generateWebSocketChannelId(at.fernFilepath),bt=Ys_({channel:he,file:at,variableResolver:z,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(at.fernFilepath,Pe,bt,he),he.audiences!=null&&O.markChannelForAudiences(at.fernFilepath,Pe,he.audiences),$.websocketChannels!=null&&($.websocketChannels[Pe]=bt,x.addWebSocketChannel(Pe,at.fernFilepath))}})};AF(e,(at,he,Pe)=>{L(r0({relativeFilepath:at,definitionFile:he,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),eFi(e,(at,he)=>{if(he.navigation!=null)if(typeof he.navigation=="string")x.addPackageRedirection({from:One({relativeFilepath:at,casingsGenerator:g}),to:One({relativeFilepath:NR(cxe(at),Xh.of(he.navigation)),casingsGenerator:g})});else{let Pe=he.navigation.map(bt=>em.generateSubpackageId(One({relativeFilepath:NR(cxe(at),Xh.of(bt)),casingsGenerator:g})));at===nS?x.sortRootPackage(Pe):x.sortSubpackage(em.generateSubpackageId(One({relativeFilepath:at,casingsGenerator:g})),Pe)}}),$.serviceTypeReferenceInfo=_nE(O);let V=n.disabled?$:bYr({ir:$,exampleGeneration:n}),Y=e.definition.rootApiFile.contents,K=zEn({casingsGenerator:g,rawApiFileSchema:Y}),Z=K?.environments._visit({singleBaseUrl:at=>at.environments.filter(he=>C7o(he.id,Y.environments)!=null).length===0,multipleBaseUrls:at=>at.environments.filter(he=>C7o(he.id,Y.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(at=>{O.markEnvironmentForAudiences(at,C7o(at.id,Y.environments)??[],Z)});let fe=O.hasNoAudiences()?void 0:O.build(),me=hnE(V,fe),_e=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(at=>at.endpoints.every(he=>he.auth)),Se=Object.values(me.services).some(at=>at.endpoints.some(he=>he.response?.body?.type==="streaming")),Qe=Object.values(me.services).some(at=>at.endpoints.some(he=>he.pagination!=null)),St=Object.values(me.services).some(at=>at.endpoints.some(he=>he.response?.body?.type==="fileDownload")),Ee={isAuthMandatory:_e,hasStreamingEndpoints:Se,hasPaginatedEndpoints:Qe,hasFileDownloadEndpoints:St,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:f!=null&&l!=null?{header:"User-Agent",value:`${l}/${f}`}:void 0}},Te=u!=null?ec_({readme:u,services:$.services}):void 0,{types:It,services:je}=lc_(me),Ot=pnE({...me,...x.build(fe),types:It,services:je,sdkConfig:Ee,readmeConfig:Te});return{...Ot,dynamic:Is_({ir:Ot,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function pnE(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]=B0a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function _nE(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 hnE(e,t){if(t==null)return e;let r=ACi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let f=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>hc_({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)&&f.push(s);return[u,{...l,shape:KO.object({...l.shape,properties:f})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let f=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,f]})),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:ACi(e.errors,u=>t.hasError(u)),services:nd(ACi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(f=>({...f,example:rrc({filteredIr:t,example:f.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(f=>({...f,example:f.example!=null?rrc({filteredIr:t,example:f.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(f=>t.hasQueryParameter(l.id,f.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(f=>t.hasRequestProperty(l.id,f.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:ynE(e.serviceTypeReferenceInfo,t)}}function ynE(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 vc_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var gc_=li(yna(),1);var bc_=["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 z9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,gc_.default)(e,{special:bc_}).replace(/V\s(\d)/g,"V$1")}function V0a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&vc_(e),r._other(e))}}}function UZt(e){return typeof e.subpackageId=="string"}function aB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function yRe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var irc="__package__",W_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 UZt(t)?t.subpackageId:irc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=t4.SubpackageId(t);return r===irc?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=t4.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 f=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{f.push(`${o} ${aB(u.path.parts)}`),f.push(`${o} ${yRe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${Wv(c.baseUrl,aB(u.path.parts))}`),f.push(`${o} ${Wv(c.baseUrl,yRe(u.path.parts))}`);let b=B7o(c);b!=null&&(f.push(`${o} ${Wv(b,aB(u.path.parts))}`),f.push(`${o} ${Wv(b,yRe(u.path.parts))}`))})}),f.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 f=[];["GET","WSS"].forEach(o=>{f.push(`${o} ${aB(u.path.parts)}`),f.push(`${o} ${yRe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${Wv(c.baseUrl,aB(u.path.parts))}`),f.push(`${o} ${Wv(c.baseUrl,yRe(u.path.parts))}`);let b=B7o(c);b!=null&&(f.push(`${o} ${Wv(b,aB(u.path.parts))}`),f.push(`${o} ${Wv(b,yRe(u.path.parts))}`))})}),f.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=UZt(t)?[...r,t.name]:r,n=i.length===0?[irc]: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 B7o(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 WMn=li(qFo(),1),mc_=li(TFo(),1);function Oc_(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{}}WMn.default.extend(mc_.default);var vnE="Changelog",bnE=["summary","index","overview"],LYr=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??vnE,i=[],n;for(let b of this.changelogFiles??[]){let g=a_s(b.split("/"));if(g==null)continue;let O=Oc_(g);if(O==null){let P=g.split(".")[0]?.toLowerCase();P!=null&&bnE.includes(P)&&(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??Gq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=WMn.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}}),f=nrc(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,f,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=WMn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return nrc(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),f=this.idgen.get(`${t}/year/${a}`);return{id:f,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(f,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=WMn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return nrc(Array.from(n.entries()).map(([a,u])=>{let l=(0,WMn.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 KA(this.docsWorkspace.absoluteFilePath,t)}};function nrc(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 x7o(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 W0a({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=>W0a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),f=i(l,u);return{...e,children:f,pointsTo:void 0}}return e}function HMn({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 f=t(l.endpointId);if(f==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${f.method} ${r(f)}`,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 I7o({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return HMn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function VZt(e,t){if(t!=null)return KA(e.absoluteFilePath,t)}function z7o({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=xo.V1.PageId(VZt(e,t.absolutePath)),f=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Gq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:f.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 R7o=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,f,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=W_i.create(r,a),this.#u=f,this.#c=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(VZt(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??Gq(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 LYr(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?W_i.getSubpackageId(r):void 0;return t.map(a=>V0a(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(g0)}#f(t,r){return z7o({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(VZt(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=W_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 f=t.slug??(UZt(a)?a.urlSlug:this.apiSection.slug??Gq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),o=this.#s(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(UZt(a)?a.displayName??z9t(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??Gq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),f=this.#s(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Gq(t.package)}`),type:"apiPackage",children:f,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(VZt(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?W_i.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(g0);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 f=t.slug??Gq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),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=W_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=UZt(n)?n.urlSlug:"",f=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:UZt(n)?n.displayName??z9t(n.name):this.apiSection.title,slug:f.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(t4.SubpackageId(r))?.endpoints.get(t4.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 f=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??aB(n.path.parts),slug:f.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(t4.SubpackageId(r))?.webSockets.get(t4.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??aB(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(t4.SubpackageId(r))?.webhooks.get(t4.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??Wv("/",...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 I7o({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>aB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return W0a({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??aB(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??aB(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??z9t(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=UZt(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:UZt(a)?a.displayName??z9t(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 x7o(t)}mergeEndpointPairs(t){return HMn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>aB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var N7o=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[$y(r).toLowerCase()]=i,this.#e[`subpackage_${$y(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Wv(a.baseUrl,aB(i.path))}`]=i,this.#r[`${n} ${Wv(a.baseUrl,yRe(i.path))}`]=i;let u=B7o(a);u!=null&&(this.#r[`${n} ${Wv(u,aB(i.path))}`]=i,this.#r[`${n} ${Wv(u,yRe(i.path))}`]=i)}),this.#r[`${i.method} ${aB(i.path)}`]=i,this.#r[`${i.method} ${yRe(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 ${aB(i.path)}`]=i,this.#n[`STREAM ${yRe(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 H0a({item:e,parentSlug:t}){return t.apply({urlSlug:Gq(e.id.split(".").pop()??"")}).get()}var $0a=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,f,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=f,this.hideChildren=o,this.#e=r,this.#t=new N7o(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(VZt(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??Gq(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 LYr(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=>V0a(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(g0)}#_(t,r){return z7o({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(VZt(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??Gq(a.name),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,f),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??z9t(a.name),slug:f.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??Gq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),f=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${Gq(t.package)}`),type:"apiPackage",children:f,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(VZt(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(g0);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??Gq(t.title),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,f),o={id:a,type:"apiPackage",children:s,title:t.title,slug:f.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=Gq(n.name),f=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??z9t(n.name),slug:f.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():H0a({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??aB(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??aB(a.path),slug:t.slug!=null?i.append(t.slug).get():H0a({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??Wv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():H0a({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 I7o({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>aB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return W0a({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(bA.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(bA.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(bA.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:Gq(r.name)}),a=this.#w(t,n),u={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??z9t(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=H0a({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:bA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??aB(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:bA.WebSocketId(t),title:r.displayName??aB(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:bA.WebhookId(t),method:r.method,title:r.displayName??z9t(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(".")===bA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===bA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===bA.api.v1.SubpackageId(t)));return{id:bA.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 x7o(t)}mergeEndpointPairs(t){return HMn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>aB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Pc_=li(require("crypto"),1);function gnE(e){return Pc_.default.createHash("sha256").update(e).digest("hex")}var F7o=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),gnE(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 L7o(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 U7o=li(LSe(),1);var arc=li(LSe(),1);function jc_(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,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:arc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:arc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Mo(i)}}var nj=li(LSe(),1);var H_i=li(LSe(),1);function Sc_(e){return e._visit({alias:t=>({type:"alias",value:JD(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:n6(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>H_i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:H_i.FernRegistry.PropertyKey(r.name.wireValue),valueType:JD(r.valueType),availability:n6(r.availability)})),extraProperties:PnE(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:H_i.FernRegistry.PropertyKey(i.name.wireValue),valueType:JD(i.valueType),availability:n6(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?n6(i.availability):void 0,additionalProperties:Ks.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[H_i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:H_i.FernRegistry.PropertyKey(n.name.wireValue),valueType:JD(n.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:JD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function JD(e){return e._visit({container:t=>Ks.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:JD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:JD(r),valueType:JD(i)}),optional:r=>({type:"optional",itemType:JD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:JD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:JD(r)}),literal:r=>Ks.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:H_i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Ks.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>mnE(t.v2),float:()=>wc_(t.v2),double:()=>wc_(t.v2),string:()=>OnE(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 OnE(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 mnE(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 wc_(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 PnE(e){return typeof e=="boolean"?e?Bf.unknown():void 0:typeof e=="string"?{type:"id",value:H_i.FernRegistry.TypeId(e),default:void 0}:JD(e)}function urc(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?wnE(r,t):[],webhooks:i!=null?jnE(i):[],websockets:n!=null?[SnE(n,t)]:[],types:e.types.map(a=>nj.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>nj.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?nj.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function jnE(e){return e.map(t=>({description:t.docs??void 0,id:nj.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??TCi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:JD(r.valueType),availability:n6(r.availability)})),payload:BnE(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function wnE(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 f=Object.values(i.v2Examples.userSpecifiedExamples)[0];l=Dc_({example:f,irEndpoint:i})}else if(Object.keys(i.v2Examples.autogeneratedExamples).length>0){let f=Object.values(i.v2Examples.autogeneratedExamples)[0];l=Dc_({example:f,irEndpoint:i})}l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>orc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(g0));else if(n!=null){let l=orc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Xva({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let f=orc({autogeneratedExample:l,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:n6(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:AnE(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?nj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?DnE({environmentsConfig:t.environments,endpoint:i}):void 0,id:nj.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??TCi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:nj.FernRegistry.PropertyKey(l.name.originalName),type:JD(l.valueType),availability:void 0})),parts:[...$Mn(i.basePath),...$Mn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:nj.FernRegistry.PropertyKey(l.name.originalName),type:JD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?$Mn(t.basePath):[],...$Mn(e.basePath),...$Mn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:JD(l.valueType),availability:n6(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:JD(l.valueType),availability:n6(l.availability)})),request:i.requestBody!=null?qnE(i.requestBody):void 0,response:i.response!=null?TnE(i.response):void 0,errors:void 0,errorsV2:CnE(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 SnE(e,t){return{auth:e.auth,availability:n6(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?nj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?EnE({environmentsConfig:t.environments,channel:e}):[],id:nj.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??TCi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:nj.FernRegistry.PropertyKey(r.name.originalName),type:JD(r.valueType),availability:void 0})),parts:$Mn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:JD(r.valueType),description:r.docs,availability:n6(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:JD(r.valueType),availability:n6(r.availability)})),messages:e.messages.map(r=>({type:nj.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:xnE(r.body),description:r.docs,availability:n6(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[nj.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:nj.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function n6(e){if(e!=null)switch(e.status){case"DEPRECATED":return nj.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return nj.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return nj.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return nj.FernRegistry.Availability.Beta;default:Mo(e.status)}}function DnE({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:nj.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:nj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function EnE({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:nj.FernRegistry.EnvironmentId(n.id),baseUrl:MnE(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:nj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function MnE(e,t){return e.replace(/^[^:]+/,t)}function AnE(e){return Ks.http.HttpMethod._visit(e,{get:()=>nj.FernRegistry.HttpMethod.Get,post:()=>nj.FernRegistry.HttpMethod.Post,put:()=>nj.FernRegistry.HttpMethod.Put,patch:()=>nj.FernRegistry.HttpMethod.Patch,delete:()=>nj.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function $Mn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:nj.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function qnE(e){let t=Ks.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??lx.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>nj.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:nj.FernRegistry.PropertyKey(i.name.wireValue),valueType:JD(i.valueType),availability:n6(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??lx.APPLICATION_JSON,shape:{type:"reference",value:JD(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:nj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:nj.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:nj.FernRegistry.PropertyKey(n.name.wireValue),valueType:JD(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:n6(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(g0)},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 TnE(e){if(e.body==null)return;let t,r=Ks.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:JD(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:JD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:JD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});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 CnE(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:JD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:nj.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:nj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:JD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Dc_({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(mj(e.request.requestBody)){let a=e.request.requestBody;for(let u of i.properties)u._visit({file:l=>{let f=a[l.key.wireValue];if(l.type==="file")n[l.key.wireValue]={type:"filename",value:typeof f=="string"?f:"<file1>"};else if(l.type==="fileArray"){let s=(Array.isArray(f)?f:[f]).filter(o=>typeof o=="string");n[l.key.wireValue]={type:"filenames",value:s}}},bodyProperty:l=>{if(l.style==="exploded"){let f=a[l.name.wireValue];n[l.name.wireValue]={type:"exploded",value:Array.isArray(f)?f:[f]}}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(g0)}}function orc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let f=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(f!=null)return{name:l.name,value:{jsonExample:f,shape:Ks.ExampleTypeReferenceShape.primitive(Ks.ExamplePrimitive.string({original:f}))}}}).filter(g0),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,f)=>(l[nj.FernRegistry.PropertyKey(f.name.originalName)]=f.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,f)=>(l[f.name.wireValue]=f.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,f)=>(l[f.name.wireValue]=f.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 f={};if(mj(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")f[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");f[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];f[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else f[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:kBe})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Ks.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:f=>f!=null?200:204,stream:f=>f.length>0?200:204,sse:f=>f.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let f=i.errors[l.errorId];if(f==null)throw new Error("Cannot find error "+l.errorId);return f.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:f=>f?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:f=>f!=null?{type:"json",value:f.jsonExample}:void 0,stream:f=>({type:"stream",value:f.map(s=>s.jsonExample)}),sse:f=>({type:"sse",value:f.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=>VSe._visit(l,{language:f=>({language:f.language,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:f.install}),sdk:f=>({language:f.sdk,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:void 0}),_other:()=>{}})).filter(g0)}}function BnE(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>nj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:nj.FernRegistry.PropertyKey(t.name.wireValue),valueType:JD(t.valueType),availability:n6(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:JD(e.payloadType)},description:e.docs};default:Mo(e)}}function xnE(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>nj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:nj.FernRegistry.PropertyKey(t.name.wireValue),valueType:JD(t.valueType),availability:n6(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:JD(e.bodyType)};default:Mo(e)}}function WX({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:urc(e.rootPackage,e),auth:jc_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:n6(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:JD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[U7o.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Sc_(a.shape),availability:n6(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[U7o.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:U7o.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...urc(a,e)}}return i}var src=li(LSe(),1);async function crc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=FF({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 IF(r,t)}),f=oIi({token:i.value}),s=WX({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await f.api.v1.register.registerApiDefinition({orgId:src.FernRegistry.OrgId(e),apiId:src.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 InE=new O3i({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function G0a(e,t,r){return h0a(d0a(WX({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),t4.ApiDefinitionId(t),InE))}var W_={};jo(W_,{AlgoliaSearchIndex:()=>Ec_,ApiDefinitionId:()=>Jc_,ApiId:()=>Zc_,Availability:()=>pl_,DocsConfigId:()=>kc_,EndpointId:()=>tl_,EndpointPathLiteral:()=>fl_,EnvironmentId:()=>el_,FileId:()=>ol_,HttpMethod:()=>dl_,IndexSegmentId:()=>Mc_,JqString:()=>sl_,OrgId:()=>Yc_,PageId:()=>al_,PayloadLocation:()=>Ll_,PropertyKey:()=>cl_,PullRequestState:()=>Il_,RoleId:()=>ll_,TokenId:()=>Xc_,TypeId:()=>nl_,Url:()=>ul_,VersionId:()=>Kc_,WebSocketId:()=>rl_,WebhookId:()=>il_,algolia:()=>lrc,api:()=>Orc,commons:()=>mrc,diff:()=>_l_,docs:()=>qrc,generators:()=>Crc,git:()=>Brc,navigation:()=>zrc,sdks:()=>Nrc,snippets:()=>Nl_,snippetsFactory:()=>Fl_,templates:()=>Frc,tokens:()=>Ul_});var lrc={};jo(lrc,{AlgoliaSearchIndex:()=>Ec_,IndexSegmentId:()=>Mc_});function Ec_(e){return e}function Mc_(e){return e}var Orc={};jo(Orc,{latest:()=>prc,v1:()=>grc});var prc={};jo(prc,{AuthSchemeId:()=>Ac_,WebhookHttpMethod:()=>Bc_,auth:()=>frc,commons:()=>qc_,endpoint:()=>Tc_,type_:()=>Cc_,webhook:()=>drc,websocket:()=>xc_});var frc={};jo(frc,{AuthSchemeId:()=>Ac_});function Ac_(e){return e}var qc_={};var Tc_={};var Cc_={};var drc={};jo(drc,{WebhookHttpMethod:()=>Bc_});var Bc_={Get:"GET",Post:"POST"};var xc_={};var grc={};jo(grc,{SubpackageId:()=>Hc_,WebSocketMessageId:()=>$c_,WebSocketMessageOrigin:()=>Gc_,WebhookHttpMethod:()=>Qc_,commons:()=>brc,db:()=>_rc,read:()=>yrc,register:()=>vrc});var _rc={};jo(_rc,{endpoint:()=>Ic_});var Ic_={};var yrc={};jo(yrc,{SupportedLanguage:()=>zc_,endpoint:()=>hrc,type_:()=>Rc_,webhook:()=>Nc_,websocket:()=>Fc_});var hrc={};jo(hrc,{SupportedLanguage:()=>zc_});var zc_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Rc_={};var Nc_={};var Fc_={};var vrc={};jo(vrc,{SourceId:()=>znE,endpoint:()=>Lc_,type_:()=>Uc_,webhook:()=>Vc_,websocket:()=>Wc_});var Lc_={};var Uc_={};var Vc_={};var Wc_={};function znE(e){return e}var brc={};jo(brc,{SubpackageId:()=>Hc_,WebSocketMessageId:()=>$c_,WebSocketMessageOrigin:()=>Gc_,WebhookHttpMethod:()=>Qc_});function Hc_(e){return e}function $c_(e){return e}var Gc_={Client:"client",Server:"server"};var Qc_={Get:"GET",Post:"POST"};var mrc={};jo(mrc,{ApiDefinitionId:()=>Jc_,ApiId:()=>Zc_,Availability:()=>pl_,DocsConfigId:()=>kc_,EndpointId:()=>tl_,EndpointPathLiteral:()=>fl_,EnvironmentId:()=>el_,FileId:()=>ol_,HttpMethod:()=>dl_,JqString:()=>sl_,OrgId:()=>Yc_,PageId:()=>al_,PropertyKey:()=>cl_,RoleId:()=>ll_,TokenId:()=>Xc_,TypeId:()=>nl_,Url:()=>ul_,VersionId:()=>Kc_,WebSocketId:()=>rl_,WebhookId:()=>il_});function Jc_(e){return e}function Kc_(e){return e}function Yc_(e){return e}function Xc_(e){return e}function Zc_(e){return e}function kc_(e){return e}function el_(e){return e}function tl_(e){return e}function rl_(e){return e}function il_(e){return e}function nl_(e){return e}function al_(e){return e}function ol_(e){return e}function ul_(e){return e}function sl_(e){return e}function cl_(e){return e}function ll_(e){return e}function fl_(e){return e}var dl_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var pl_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var _l_={};var qrc={};jo(qrc,{latest:()=>wrc,v1:()=>Mrc,v2:()=>Arc});var wrc={};jo(wrc,{Layout:()=>yl_,MdxEngine:()=>RnE,TwitterCardSetting:()=>vl_,commons:()=>hl_,frontmatter:()=>Prc,seo:()=>jrc});var RnE={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var hl_={};var Prc={};jo(Prc,{Layout:()=>yl_});var yl_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var jrc={};jo(jrc,{TwitterCardSetting:()=>vl_});var vl_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Mrc={};jo(Mrc,{commons:()=>Erc,db:()=>bl_,read:()=>gl_,write:()=>Src});var bl_={};var gl_={};var Src={};jo(Src,{DocsRegistrationId:()=>FnE,FilePath:()=>NnE});function NnE(e){return e}function FnE(e){return e}var Erc={};jo(Erc,{ContentAlignment:()=>jl_,FontDisplay:()=>Ml_,FontStyle:()=>El_,HeaderPosition:()=>wl_,JsScriptStrategy:()=>Dl_,ProgrammingLanguage:()=>Ol_,SearchbarPlacement:()=>ml_,TabsPlacement:()=>Pl_,TwitterCardSetting:()=>Sl_,commons:()=>Drc});var Drc={};jo(Drc,{ContentAlignment:()=>jl_,FontDisplay:()=>Ml_,FontStyle:()=>El_,HeaderPosition:()=>wl_,JsScriptStrategy:()=>Dl_,ProgrammingLanguage:()=>Ol_,SearchbarPlacement:()=>ml_,TabsPlacement:()=>Pl_,TwitterCardSetting:()=>Sl_});var Ol_={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 ml_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Pl_={Header:"HEADER",Sidebar:"SIDEBAR"};var jl_={Center:"CENTER",Left:"LEFT"};var wl_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Sl_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Dl_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var El_={Normal:"normal",Italic:"italic"};var Ml_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Arc={};jo(Arc,{read:()=>Al_,write:()=>ql_});var Al_={};var ql_={};var Crc={};jo(Crc,{ChangelogEntryType:()=>Cl_,GeneratorId:()=>LnE,GeneratorLanguage:()=>UnE,ReleaseType:()=>Bl_,cli:()=>Tl_,commons:()=>Trc,versions:()=>xl_});var Tl_={};var Trc={};jo(Trc,{ChangelogEntryType:()=>Cl_,ReleaseType:()=>Bl_});var Cl_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Bl_={Ga:"GA",Rc:"RC"};var xl_={};function LnE(e){return e}var UnE={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Brc={};jo(Brc,{PullRequestState:()=>Il_});var Il_={Open:"open",Closed:"closed",Merged:"merged"};var zrc={};jo(zrc,{latest:()=>xrc,v1:()=>Irc});var xrc={};jo(xrc,{NodeId:()=>HnE,ProductId:()=>$nE,Slug:()=>VnE,TabId:()=>WnE});function VnE(e){return e}function WnE(e){return e}function HnE(e){return e}function $nE(e){return e}var Irc={};jo(Irc,{NavigationV1Availability:()=>YnE,NodeId:()=>JnE,ProductId:()=>KnE,Slug:()=>GnE,TabId:()=>QnE});function GnE(e){return e}function QnE(e){return e}function JnE(e){return e}function KnE(e){return e}var YnE={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Nrc={};jo(Nrc,{Language:()=>zl_,VersionBump:()=>Rl_,versions:()=>Rrc});var Rrc={};jo(Rrc,{Language:()=>zl_,VersionBump:()=>Rl_});var zl_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Rl_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var Nl_={};var Fl_={};var Frc={};jo(Frc,{PayloadLocation:()=>Ll_});var Ll_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var Ul_={};var GMn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Nd(e){return e!=null}var Wl_=li(yna(),1);var Vl_=["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 WZt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Wl_.default)(e,{special:Vl_}).replace(/V\s(\d)/g,"V$1")}function V7o({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:WZt(a)},n.push(a)})}),r}var W7o=class{errors=new GMn},QMn=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 Hl_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var H7o=class extends W7o{},Wp=class extends QMn{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 ${Hl_(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})}}},LF=class extends Wp{},Pne=class extends LF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var $l_="x-fern-base-path",Gl_="x-fern-availability",$7o="x-fern-sdk-group-name",Ql_="x-fern-global-headers",Jl_="x-fern-sdk-method-name";var Kl_="x-fern-webhook",Yl_="x-fern-access-token-locator",Xl_="x-fern-basic",Zl_="x-fern-username-variable-name",kl_="x-fern-password-variable-name",ef_="x-fern-bearer",tf_="x-fern-token-variable-name",rf_="x-fern-header",if_="x-fern-header-variable-name",nf_="x-fern-server-name",af_="x-fern-examples";var G7o=class extends Wp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[nf_]}convert(){if(this.serverName!=null)return this.serverName}};var Q7o=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 G7o({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 HZt(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,f)=>new Q7o({input:l,context:r,accessPath:i,pathId:["servers",`${f}`]}));return[...n,...u]}function pS(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function QV(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:(pS(n)&&(n=QV(n,t,r)),n)}function J7o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return pS(r)?QV(r,t,void 0):r}var mf_=li(Ax());var K7o=class extends Wp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Xl_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Y7o=class extends Wp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[kl_]}convert(){return this.passwordVariableName}};var X7o=class extends Wp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[Zl_]}convert(){return this.usernameVariableName}};var Z7o=class extends Wp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ef_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var k7o=class extends Wp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[tf_]}convert(){return this.tokenVariableName}};function of_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var uf_="x-bearer-format",sf_="x-code-samples",cf_="x-codeSamples";var e6o=class extends Wp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[uf_]}convert(){return this.bearerFormat}};var t6o=class extends Wp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[rf_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var r6o=class extends Wp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[if_]}convert(){return this.headerVariableName}};function lf_(e){return e.type==="apiKey"}var JMn=class extends Wp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){lf_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new t6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new r6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new e6o({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 ff_(e){return e}function df_(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var XnE=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function pf_(e){return Array.from(e.match(XnE)??[])}function _f_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function hf_(e){return Object.is(e,-0)?"-0":e.toString()}function yf_(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 Lrc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?_f_(t)?Lrc(e,yf_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=hf_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return ZnE(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function ZnE(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 vf_(e){return function(t){return Lrc(t,e)}}function Urc(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 i6o(e,t){switch(t=t??ff_,typeof t){case"string":case"symbol":case"number":case"object":return Urc(e,vf_(t));case"function":return Urc(e,t)}}function bf_(e){let t=pf_(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>df_(n)).join("")}`}function Vrc(e){if(e==null)return"";if(Array.isArray(e))return e.map(Vrc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function gf_(e){return typeof e!="string"&&(e=Vrc(e)),e.replace(/['\u2019]/g,"")}function R9t(e){return bf_(gf_(e))}function LM(e){if(e!=null)return Array.isArray(e)?e:[e]}function n6o({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`${knE(u)}${eaE(e)}.${taE(i,n,a,l)}`}function knE(e){return e?"webhook_":"endpoint_"}function eaE(e){return e!=null?LM(e)?.map(t=>R9t(t)).join("/"):""}function taE(e,t,r,i){return e||t||R9t(r??"")||R9t(i??"")}function Of_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var a6o=class extends Wp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[Yl_],this.accessTokenLocator!=null&&(Of_(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 o6o=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 JMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new a6o({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=n6o({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 KMn=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 X7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Y7o({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 Z7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new k7o({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":{of_(this.input)?(this.authScheme="header",this.headerAuthNode=new JMn({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 o6o({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 mf_.UnreachableCaseError(this.authScheme);return}}};var YMn=class extends Wp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=J7o(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 KMn({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 u6o=class extends Wp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[$l_],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 Pf_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function jf_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function XMn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>LM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!Pf_(n))&&(u=jf_(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 s6o(e,t){return pS(e)?QV(e,t,void 0):e}function $_i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function wf_(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 Sf_(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 Df_=li(Ax());var Wrc=["decimal","decimal128","double-int","double","float","sf-decimal"],Hrc=["int16","int32","int64","int8","sf-integer","uint8"],$rc=["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"],Grc=["beta","pre-release","in-development","generally-available","deprecated"];function UF(e,t){return pS(e)?QV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var vRe=class extends Wp{availability;constructor(t){super(t),this.safeParse()}parse(){if(UF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[Gl_];r!=null&&(Grc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Grc.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 Df_.UnreachableCaseError(this.availability);return}}};var l6o=li(Ax());function Ef_(e){return typeof e=="object"&&e!=null&&"language"in e}function Mf_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Af_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function qf_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function c6o(e){return typeof e=="object"&&e!=null&&"event"in e}function Qrc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(c6o)}function G_i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Tf_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var f6o=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[af_]}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 G_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=>G_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 l6o.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=Tf_(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 l6o.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Af_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{Qrc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!Qrc(r.response)&&qf_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new l6o.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Ef_(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})):Mf_(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 f=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(f).length>0?f: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 Q0a=class extends Wp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[$7o]}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(R9t(r)))}};var d6o=class extends Wp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[Jl_]}convert(){return this.sdkMethodName}};var p6o=class extends Wp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[Kl_]}convert(){return this.isWebhook}};var _6o=class extends Wp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[sf_]??[],...this.input[cf_]??[]],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 T3i=li(Ax());function Jrc(e,t){return pS(e)?QV(e,t,void 0):e}function Cf_(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 o9="",$Zt=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&&(G_i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>G_i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new T3i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Jrc(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=Jrc(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 T3i.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(c6o)){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 T3i.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 G_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=>G_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 T3i.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 T3i.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 T3i.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:Cf_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?WZt(this.name):this.summary!=null?WZt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Bf_(e,t){return pS(e)?QV(e,t,void 0):e}var Gf_=li(Ax());var xf_="#/components/schemas/";function ZMn(e){if(e.$ref.startsWith(xf_))return e.$ref.replace(xf_,"")}function UYr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function Q_i(e){return typeof e.type=="string"&&e.type==="array"}function If_(e){return e.type==="boolean"}function zf_(e){return e.type==="integer"}function J_i(e){return!Array.isArray(e.type)&&!Q_i(e)}function Rf_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||J_i(t)||Q_i(t))}function Nf_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ff_(e){return e.type==="null"}function Lf_(e){return e.type==="number"}function Krc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Uf_(e){return e.type==="string"}var h6o=class extends Pne{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new lq({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 LM(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 y6o=class extends LF{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 vRe({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 v6o=class extends Pne{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 lq({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=>LM(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(UYr).filter(Nd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function b6o(e){return e!=null&&e.length>0?e:[void 0]}var kMn=class extends Pne{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 lq({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 lq({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(pS(t))return ZMn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new lq({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 XMn(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}}}]:LM(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=>b6o(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=UF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new lq({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 g6o=class extends Pne{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=>UF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>UF(t,this.context.document)?.type!=="null"?new lq({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=UF({$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 lq({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(UYr).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])=>LM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??WZt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Nd)).filter(Nd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>LM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?WZt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?WZt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Nd)).filter(Nd)}:void 0,i=this.isNullable?UYr(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 O6o=class extends LF{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 K_i=class extends LF{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(pS(r)){let n=UF(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 Vf_=li(Ax());function raE(e){return Hrc.includes(e)}var m6o=class extends LF{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&&(raE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Hrc.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 Vf_.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 P6o=class extends LF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UYr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Wf_=li(Ax());function iaE(e){return Wrc.includes(e)}var j6o=class extends LF{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&&(iaE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Wrc.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 Wf_.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 Hf_=li(Ax());function naE(e){return $rc.includes(e)}var w6o=class extends LF{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 Hf_.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&&(naE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${$rc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new K_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 $f_=li(Ax());var S6o=class extends LF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,$f_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var C3i=class extends Pne{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=ZMn(this.input);let t=UF(this.input,this.context.document);t?.enum!=null&&J_i(t)&&(this.maybeEnumConverterNode=new K_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=UF(this.input,this.context.document);if(r!=null)return new lq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var lq=class e extends Pne{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 vRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),J_i(this.input)&&Nf_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),pS(this.input)){let t=ZMn(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 C3i({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 y6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Rf_(this.input))this.typeShapeNode=new v6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(J_i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new g6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Krc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new kMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(J_i(this.input)&&this.input.enum!=null)this.typeShapeNode=new K_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":Krc(this.input)&&(this.typeShapeNode=new kMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":Q_i(this.input)&&(this.typeShapeNode=new h6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":If_(this.input)&&(this.typeShapeNode=new O6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":zf_(this.input)&&(this.typeShapeNode=new m6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Lf_(this.input)&&(this.typeShapeNode=new j6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Uf_(this.input)&&(this.typeShapeNode=new w6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Ff_(this.input)&&(this.typeShapeNode=new P6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new Gf_.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 kMn({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 S6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!pS(this.input)&&(!Q_i(this.input)&&this.input==null||Q_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=LM(t)?.map(i=>this.nullable?UYr(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 Y_i(e){if(e!=null)return XMn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Nd))}var GZt=class extends LF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;pS(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 vRe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new lq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Bf_(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 Qf_(e,t){return pS(e)?QV(e,t,void 0):e}var Yrc=li(Ax());function D6o(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 Jf_=li(Kps(),1),eAn=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=Jf_.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 aaE(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var tAn=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 lq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),aaE(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(pS(r)?n=J7o(r.$ref,this.context.document):n=r,n!=null)return[t,new KMn({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=LM(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 E6o=class extends lq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=UF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${pS(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=UF(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 M6o=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=UF(this.input.schema,this.context.document);this.availability=new vRe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=pS(this.input.schema)?new C3i({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=eAn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new lq({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 E6o({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?{[o9]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[o9]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:LM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=R9t([this.method,this.path,this.contentType,"request"].join("_"));return D6o({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 Yrc.UnreachableCaseError(n);return}}).filter(Nd)}convert(){if(this.schema instanceof C3i)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=LM(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 Yrc.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 A6o=class extends Wp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Qf_(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 M6o({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])=>LM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Nd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>LM(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 Kf_={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 Yf_(e,t){if(pS(e)){let r=QV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var q6o=li(Ax());var Xf_="application/json";var Zf_="application/octet-stream";function kf_(e,t){return e===t||t===o9||e===o9}var J0a=class extends Wp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,f){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,f]of Object.entries(r))for(let s of f)kf_(l,a)&&(i.add(l),this.examples?.push(new $Zt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,$_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[f,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new $Zt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,$_i(s,u),{requestBody:f,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,f,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new $Zt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,$_i(f,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,f]of r.slice(t.length))this.examples?.push(...f.map(s=>new $Zt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,$_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[o9];if(a!=null)for(let u of a)this.examples?.push(new $Zt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,$_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=eAn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=Xf_,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 lq({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=Zf_,this.contentSubtype=UF(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 lq({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=i6o(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[o9]??=[],r[o9]=[{value:this.input.example}]);let i=UF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=i6o(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[o9]??=[],r[o9]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[o9]??=[],r[o9]?.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(([f])=>!n.has(f)&&f!==o9).map(([f,s])=>[l,f,s]));let u=Object.entries(r).filter(([l,f])=>!n.has(l)&&Nd(f)&&l!==o9);Object.keys(r).every(l=>l===o9)||this.matchExamplesByIndex(a,u),!n.has(o9)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return LM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new q6o.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return LM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=R9t([this.method,this.path,this.statusCode,"response"].join("_"));return D6o({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 q6o.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 q6o.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var K0a=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=Yf_(this.input,this.context.document);if(r==null){this.context.errors.error({message:pS(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 GZt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new J0a({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 J0a({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 T6o=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 K0a({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 K0a({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 b6o(Y_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=LM(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??Kf_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let f=l.convert();if(f!=null&&f.responseBody?.type==="json")return{name:f.name,description:f.description,responseBody:f.responseBody}}).filter(Nd)})).filter(Nd)})).filter(Nd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var X_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 $Zt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,$_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 vRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=HZt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new p6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(pS(i)){let a=s6o(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 GZt({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 GZt({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 GZt({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 _6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new A6o({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 T6o({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 YMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new Q0a({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 Q0a({input:{[$7o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new d6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>n6o({namespace:LM(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 f6o({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=Sf_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:wf_(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:Y_i(this.queryParameters)?.flat(),headers:Y_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,f=this.auth?.convert();f!=null&&(l=Object.keys(f));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:Y_i(this.pathParameters)?.flat(),queryParameters:Y_i(this.queryParameters)?.flat(),requestHeaders:Y_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 rAn=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=HZt(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 X_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 X_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 X_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 X_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 X_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 C6o(e){return"payloads"in e}var B6o=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 rAn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:HZt(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=>{C6o(a)?r[W_.WebhookId(a.id)]=a:t[W_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var x6o=class extends Wp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Ql_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||s6o(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new GZt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return XMn(this.globalHeaders,this.requiredProperties)?.flat()}};function ed_(e,t){if(pS(e)){let r=QV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var I6o=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=ed_(a,this.context.document);if(u!=null)return new rAn({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=>{C6o(i)&&(t[W_.WebhookId(i.id)]=i)}),t),{})}};var z6o=class extends Wp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=HZt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new YMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new u6o({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 B6o({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 I6o({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 tAn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new x6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Uie(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=V7o({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 iAn=class extends QMn{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 bRe(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function N9t(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:(bRe(n)&&(n=N9t(n,t,r)),n)}function td_(e,t){return bRe(e)?N9t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var ad_=li(Ax());function VYr(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]=VYr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VYr(t)):[VYr(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 VYr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VYr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VYr(r));return t}}function Y0a(e,t){return bRe(e)?N9t(e,t,{name:"",schema:{type:"object"}}):e}function rd_(e,t){return bRe(e)?N9t(e,t,void 0):e}function id_(e,t){return bRe(e)?N9t(e,t,void 0):e}function nd_(e,t){return bRe(e)?N9t(e,t,void 0):e}var oaE={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}}}},R6o=class extends iAn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Y0a(this.method.result,this.context.openrpc):void 0,r=t?new lq({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=>Y0a(l,this.context.openrpc)).filter(Nd)?.map(l=>{let f=new lq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!f)return;let s=Array.isArray(f)?f[0]:f;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 f=id_(l,this.context.openrpc);if(f)return{name:f.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:f.params.length>0?{type:"json",value:Object.fromEntries(f.params.map(s=>{let o=rd_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Nd))}:void 0,responseStatusCode:200,responseBody:f.result?{type:"json",value:f.result}:void 0}}).filter(Nd)??[];if(u.length<=0){let l=VYr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Y0a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),f={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:VYr(Y0a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(f)}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:[oaE],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=nd_(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=LM(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 ad_.UnreachableCaseError(u);return}}).filter(Nd)[0];if(n)return{statusCode:200,body:n,description:r}}};var X0a=class extends iAn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=HZt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=td_(t,this.context.openrpc);r!=null&&this.methods.push(new R6o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new tAn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Uie(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Nd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=V7o({endpoints:n});return{id:W_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var Z0a=class extends H7o{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 k0a(e,t){if(e instanceof yZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=new b9t(e.absoluteFilePath),i=await aRe({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 GMn,generatedTypes:{}},f=new z6o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=f_s(a,f.convert())}return a}var od_=require("fs/promises");async function ud_(e,t){let r=await(0,od_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Z0a({openrpc:i,logger:t.logger});return new X0a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function sd_(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 cd_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){saE(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Xrc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Xrc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Xrc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await uGt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Xrc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),uaE(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function uaE(e){return e.api!=null}function saE(e){return e[0]?.tab!=null}function HX(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ld_.default.extend(fd_.default);var caE=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),N6o=0,laE=async({ir:e})=>(N6o++,`${e.apiName.snakeCase.unsafeName}-${N6o}`),faE=async({api:e})=>(N6o++,`${e.id}-${N6o}`),F9t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=caE,f=laE,s=faE){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=f,this.registerApiV2=s}#e=F7o.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 xOs({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 cd_({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=KA(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[Xa.of(s)]=await MXs({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[Xa.of(s)]=await EXs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=sd_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=$ba(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Xa.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[Xa.of(s)]=DXs(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=daE(this.editThisPage,s);u[A9t.PageId(s)]={markdown:o,editThisPageUrl:c?A9t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=Vg(this.docsWorkspace.absoluteFilePath,o);(await(0,F6o.stat)(c)).isDirectory()?(await pxe(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),f=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,F6o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:f}}resolveFilepath(t){if(t!=null)return Vg(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return KA(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Zrc.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,Zrc.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 f=Lu(this.docsWorkspace.absoluteFilePath,Xa.of(l));r[f]=Wv(t,u)}),r}getDocsBasePath(){return new URL(HX(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?A9t.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:A9t.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:A9t.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 tyn(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??Gq(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??Gq(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?paE(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 f=u.length>0?u[u.length-1]:void 0,s;f?.type==="sidebarGroup"?s=f:(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 tyn(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=Vg(this.docsWorkspace.absoluteFilePath,Xa.of(t.openrpc));if(!await Cf(o))throw new Error(`OpenRPC file does not exist at path: ${o}`);let c=await ud_(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:L7o(t.snippetsConfiguration)}),new $0a(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=L7o(t.snippetsConfiguration),b=await k0a(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 $0a(t,b,r,o,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=L7o(t.snippetsConfiguration),a,u;this.parsedDocsConfig.experimental?.openapiParserV3?a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0}):(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0}),a=FF({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 IF(this.taskContext,u)}));let l=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=G0a(a,l,{oauth:t.playground?.oauth});return new R7o(t,f,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new LYr(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??Gq(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`),f=i.apply({urlSlug:r.slug??Gq(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:f.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,f,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 tyn(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 LYr(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??Gq(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):A9t.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(g0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:A9t.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 tyn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:A9t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function daE(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${HX(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function paE(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 JV(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof nN?t:null))).filter(g0)}async function krc(e,t,r){if(e instanceof yZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0});return WX({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var Kic=li(Gds(),1),sy_=li(f2o(),1),YZt=require("fs/promises"),M2o=require("os"),cy_=li(hre(),1),ly_=li(uy_(),1);var nsE="etag",Yic="preview",Xic="app-preview",asE="bundle",osE=".next",Zic=".fern";function usE({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic))}function N3i({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic),Xa.of(e?osE:asE))}function ssE({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic),Xa.of(nsE))}async function A2o({bucketUrl:e,logger:t,preferCached:r,app:i=!1}){t.debug("Setting up docs preview bundle...");let n=await(0,Kic.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let a=n.body,l=await new ly_.default.Parser().parseStringPromise(a),f=l?.ListBucketResult?.Contents?.[0]?.ETag?.[0],s=l?.ListBucketResult?.Contents?.[0]?.Key?.[0],o=ssE({app:i});if(r){let D=await Cf(o),C;if(D&&(t.debug("Reading existing ETag"),C=(await(0,YZt.readFile)(o)).toString()),C!=null&&C===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up docs preview bundle...
2012
+ ${JSON.stringify(r)}"`)}}function Cs_(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=As_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Wxe.grpc({service:a})}function Bs_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:f,sourceResolver:s,globalErrors:o,workspace:c}){let b=VMn({pathParameters:r["path-parameters"],location:Hxe.Service,file:i,variableResolver:f}),g=qs_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:mne(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:k7(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([P,E])=>hRe({headerKey:P,header:E,file:i})):[],pathParameters:b,encoding:BiE(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([P,E])=>{let q=VMn({pathParameters:B9t(E),location:Hxe.Endpoint,file:i,variableResolver:f}),A={...eQ(E),id:"",name:i.casingsGenerator.generateName(P),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?CiE(E.method):S7.Post,basePath:E["base-path"]!=null?k7(E["base-path"]):void 0,path:k7(E.path),fullPath:k7(E["base-path"]!=null?Wv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Wv(i.rootApiFile["base-path"],r["base-path"],E.path):Wv(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])=>w7o({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>hRe({headerKey:D,header:C,file:i})):[],requestBody:$u_({request:E.request,file:i}),sdkRequest:Yu_({service:r,request:E.request,endpoint:E,endpointKey:P,file:i,typeResolver:a,propertyResolver:u}),response:Ps_({endpoint:E,file:i,typeResolver:a}),errors:[...Ms_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:ms_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:f,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>Xu_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Es_({propertyResolver:u,file:i,endpointName:P,endpointSchema:E}),transport:Ts_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0};return A.id=em.generateEndpointId(O,A),A})}}function VMn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>qiE({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function qiE({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...eQ(t),name:i.casingsGenerator.generateName(e),valueType:TiE({parameter:t,variableResolver:n,file:i}),location:r,variable:$0n(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function TiE({parameter:e,variableResolver:t,file:r}){let i=L0a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function L0a({parameter:e,variableResolver:t,file:r}){let i=D7o({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function D7o({parameter:e,variableResolver:t,file:r}){if($0n(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 CiE(e){switch(e){case"GET":return S7.Get;case"POST":return S7.Post;case"PUT":return S7.Put;case"PATCH":return S7.Patch;case"DELETE":return S7.Delete;default:Mo(e)}}function hRe({headerKey:e,header:t,file:r}){let{name:i}=LZt({headerKey:e,header:t});return{...eQ(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 LZt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function BiE(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Mo(e)}}var xs_="1.0.0";var E7o=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=BDe({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:xs_,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=Wv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Wv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Wv(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??Uie(),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 Is_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new E7o({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var tQ={};jo(tQ,{validateObjectExample:()=>E3i,validateTypeExample:()=>P7o,validateTypeReferenceExample:()=>a9});var M7o=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:em.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(!zs_(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(!zs_(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},f=a.find(s=>s.name.originalName===n.originalName);if(f==null){let s=em.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),f=o}return this.getPackageForFernFilepath(t,u,f)}};function zs_(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 Rs_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var A7o=e=>{let t=CDe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function q7o({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function Ns_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a;try{a=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:A7o(n),serviceId:em.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:em.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:a,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function Fs_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{},u;try{u=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:A7o(n),serviceId:em.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:em.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:xiE({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:u,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var xiE=({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 Ls_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=Fs_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?Ns_({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 U0a={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:["expires_in"],refresh_token:void 0}},Ytc={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:["expires_in"]}};function Us_(e){return{endpoint:e["get-token"].endpoint,requestProperties:IiE({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ziE({responseProperties:e["get-token"]?.["response-properties"]})}}function Vs_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:RiE({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:NiE({responseProperties:e["refresh-token"]?.["response-properties"]})}}function IiE({requestProperties:e}){if(e==null)return U0a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?C9t(t):U0a.requestProperties.client_id,client_secret:r!=null?C9t(r):U0a.requestProperties.client_secret,scopes:i!=null?C9t(i):U0a.requestProperties.scopes}}function ziE({responseProperties:e}){return Ws_({responseProperties:e,defaultValue:U0a.responseProperties})}function RiE({requestProperties:e}){if(e==null)return Ytc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?C9t(t):Ytc.requestProperties.refresh_token}}function NiE({responseProperties:e}){return Ws_({responseProperties:e,defaultValue:Ytc.responseProperties})}function Ws_({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?FZt(r):t.access_token,expires_in:i!=null?FZt(i):t.expires_in,refresh_token:n!=null?FZt(n):t.refresh_token}}function Js_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Uxe.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return Ixi(e.auth,{single:a=>{let u=Hs_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Uxe.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Uxe.Any,schemes:a.map(u=>Hs_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function Hs_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,f)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return nua(s,{header:o=>NC.header({docs:f,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=>Gs_({file:r,docs:f,rawScheme:o}),bearer:o=>$s_({file:r,docs:f,rawScheme:o}),oauth:o=>Qs_({file:r,docs:f,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return $s_({file:r,docs:void 0,rawScheme:void 0});case"basic":return Gs_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return Qs_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function $s_({file:e,docs:t,rawScheme:r}){return NC.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Gs_({file:e,docs:t,rawScheme:r}){return NC.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 Qs_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return NC.oauth({docs:t,configuration:Mci.clientCredentials(Ls_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Us_(r),refreshTokenEndpoint:Vs_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Ks_({file:e,rawApiFileSchema:t}){if(t.version!=null)return qci.header({header:FiE({file:e,header:t.version.header}),value:LiE({file:e,versionDeclaration:t.version})})}function FiE({file:e,header:t}){return typeof t=="string"?hRe({file:e,headerKey:t,header:{type:"string"}}):hRe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function LiE({file:e,versionDeclaration:t}){return j7o({_enum:{default:t.default,enum:t.values},file:e})}function Ys_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,f]of Object.entries(e.messages??{}))u.push({type:l,availability:mne(f.availability),docs:f.docs,origin:f.origin,body:WiE({body:f.body,file:n}),displayName:f["display-name"]});return{availability:mne(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,f])=>hRe({headerKey:l,header:f,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?VMn({pathParameters:e["path-parameters"],location:Hxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,f])=>{let{name:s}=FYr({queryParameterKey:l,queryParameter:f}),o=n.parseTypeReference(f);return{...eQ(f),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof f!="string"&&f["allow-multiple"]!=null?f["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let f=$iE({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:QiE({channel:e,example:l,pathParams:f}),...f,...GiE({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:FYr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:gE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:UiE({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:ViE({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function UiE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?B2.exploded():B2.single()}function ViE({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!JiE(e.body))return WSe.reference(gE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!mj(t))throw new Error("Example must be an object");let u=[];for(let[l,f]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:l,property:s}).name,wireValue:l}),value:gE({example:f,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=F0a({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:n9({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:gE({example:f,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 WSe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function WiE({body:e,file:t}){return typeof e=="string"?P5.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):HiE(e)?P5.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):P5.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:T9t(e.extends??[]).map(r=>i9({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:n9({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function HiE(e){return e.type!=null}function $iE({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],f=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=L0a({parameter:o,variableResolver:n,file:a});return{name:s,value:gE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=B9t(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(f({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function GiE({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,f]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:LZt({headerKey:l,header:s}).name,wireValue:l}),value:gE({example:f,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 QiE({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 JiE(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function Xs_({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:gE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:L_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,v2Examples:void 0,displayName:void 0}}var Zs_="content";function ks_(e,t){if(e==null||e.strategy==="status-code")return L8t.statusCode();switch(e.strategy){case"property":return L8t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Zs_,wireValue:Zs_})});default:Mo(e)}}function ec_({readme:e,services:t}){let r=new Xtc(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 Xtc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=YiE({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:KiE(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function KiE(e){let t="";e.fullPath.head.length>0&&(t=Wv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Wv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Wv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function YiE({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 tc_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:em.generateWebhookId(t.fernFilepath,u),availability:mne(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(([f,s])=>hRe({headerKey:f,header:s,file:t})):[],payload:XiE({payload:l.payload,file:t}),examples:l.examples!=null?kiE({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function XiE({payload:e,file:t}){return typeof e=="string"?aV.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):REn(e)?aV.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):aV.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:T9t(e.extends).map(r=>i9({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>ZiE({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?mne(i.availability):void 0,file:t})):[]})}function ZiE({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n9({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function kiE({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:REn(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:gE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!mj(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:gE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function rc_({name:e,source:t}){return jj.userDefined({file:S7o({source:t}),name:U_i.generateName(e)})}function ic_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=enE({type:e.proto.type});if(t!=null)return t}}function enE({type:e}){switch(e){case"google.protobuf.Any":return jj.wellKnown(Zf.any());case"google.protobuf.Api":return jj.wellKnown(Zf.api());case"google.protobuf.BoolValue":return jj.wellKnown(Zf.boolValue());case"google.protobuf.BytesValue":return jj.wellKnown(Zf.bytesValue());case"google.protobuf.DoubleValue":return jj.wellKnown(Zf.doubleValue());case"google.protobuf.Duration":return jj.wellKnown(Zf.duration());case"google.protobuf.Empty":return jj.wellKnown(Zf.empty());case"google.protobuf.Enum":return jj.wellKnown(Zf.enum());case"google.protobuf.EnumValue":return jj.wellKnown(Zf.enumValue());case"google.protobuf.Field":return jj.wellKnown(Zf.field());case"google.protobuf.FieldCardinality":return jj.wellKnown(Zf.fieldCardinality());case"google.protobuf.FieldKind":return jj.wellKnown(Zf.fieldKind());case"google.protobuf.FieldMask":return jj.wellKnown(Zf.fieldMask());case"google.protobuf.FloatVlaue":return jj.wellKnown(Zf.floatValue());case"google.protobuf.Int32Value":return jj.wellKnown(Zf.int32Value());case"google.protobuf.Int64Value":return jj.wellKnown(Zf.int64Value());case"google.protobuf.ListValue":return jj.wellKnown(Zf.listValue());case"google.protobuf.Method":return jj.wellKnown(Zf.method());case"google.protobuf.Mixin":return jj.wellKnown(Zf.mixin());case"google.protobuf.NullValue":return jj.wellKnown(Zf.nullValue());case"google.protobuf.Option":return jj.wellKnown(Zf.option());case"google.protobuf.SourceContext":return jj.wellKnown(Zf.sourceContext());case"google.protobuf.StringValue":return jj.wellKnown(Zf.stringValue());case"google.protobuf.Struct":return jj.wellKnown(Zf.struct());case"google.protobuf.Syntax":return jj.wellKnown(Zf.syntax());case"google.protobuf.Timestamp":return jj.wellKnown(Zf.timestamp());case"google.protobuf.Type":return jj.wellKnown(Zf.type());case"google.protobuf.Uint32Value":return jj.wellKnown(Zf.uint32Value());case"google.protobuf.Uint64Value":return jj.wellKnown(Zf.uint64Value());case"google.protobuf.Value":return jj.wellKnown(Zf.value())}}function nc_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=pz(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&cS(a.declaration)){let u=pz(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([f,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[f,o]});return KO.object({extends:T9t(a.declaration.extends).map(f=>i9({typeName:f,file:t})),properties:x0a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function ac_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return Lxe(i)?nc_({generic:i,file:t,typeResolver:r}):KO.alias({aliasOf:t.parseTypeReference(e),resolvedType:tnE({aliasOf:i,file:t,typeResolver:r})})}function tnE({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return nV.primitive(i.originalTypeReference.primitive);case"container":return nV.container(i.originalTypeReference.container);case"unknown":return nV.unknown();case"named":{let n=cS(i.declaration)?U8t.Object:Lci(i.declaration)?U8t.Union:$8t(i.declaration)?U8t.Enum:G0n(i.declaration)?U8t.UndiscriminatedUnion:Mo(i.declaration);return nV.named({name:i.name,shape:n})}}}function oc_({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 uc_(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 ktc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new Ztc}){let n=dF(e,{alias:u=>{let l=typeof u=="string"?u:u.type,f=pz(l);if(f!=null){let s=new Set(f.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=pz(o.typeName)?.arguments;if(cS(o.declaration)){let b=uc_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>uc_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(f=>typeof f=="string"?f:f.type)),l.push(...Object.values(u.union).reduce((f,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&f.push(o),f},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,f)=>{let s=typeof f=="string"?f:f.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=x2({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:f,valueType:s})=>[...f,...s],list:f=>f,optional:f=>f,nullable:f=>f,set:f=>f,named:f=>[f],literal:()=>[],unknown:()=>[]}});for(let f of l){let s=i9({typeName:f,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t});if(Lxe(o.typeName))continue;a.push(...ktc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var Ztc=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 sc_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=eQ(t),f=i9({typeName:e,file:r}),s=ktc({typeDeclaration:t,file:r,typeResolver:i}),o={};cS(t)&&(o=DFi(t.properties??{}));let c=inE({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:unE(t),name:f,shape:rnE({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:nnE({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:Ktc({typeName:f,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 rnE({typeDeclaration:e,file:t,typeResolver:r}){return dF(e,{alias:i=>ac_({alias:i,file:t,typeResolver:r}),object:i=>Wu_({object:i,file:t}),discriminatedUnion:i=>ns_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>oc_({union:i,file:t}),enum:i=>KO.enum(j7o({_enum:i,file:t}))})}function inE({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=ic_({encoding:t.encoding});if(a!=null)return KQr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return KQr.proto(rc_({source:n,name:r}))}function nnE({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?anE(e.encoding):onE(t)}function anE(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function onE(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function unE(e){if(typeof e!="string"&&"inline"in e)return e.inline}function cc_(e,t){let r=t[e];if(r==null)throw new DQr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function lc_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,cnE({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>snE({endpoint:i,ir:e}))}]))}}function snE({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>fc_(r,t))}}}function cnE({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>fc_(r,t))}}}return e}function fc_(e,t){let r=erc(e.typeId,t);return dc_({objectTypeDeclaration:r,ir:t})}function erc(e,t){let r=cc_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return erc(r.shape.resolvedType.name.typeId,t)}throw new DQr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function dc_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=erc(i.typeId,t);return dc_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function _c_({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:Az({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=Az({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 Az({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=>Az({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Ph.container(YO.set({...i,set:i.set.map(n=>Az({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?Az({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?Az({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=Az({filteredIr:e,exampleTypeReference:n.key}),u=Az({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=Az({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Ph.named({...r,shape:uw.enum(i)})}),object:i=>({...t,shape:Ph.named({...r,shape:uw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:Az({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=_c_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=Az({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Ph.named({...r,shape:uw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function trc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function lnE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function pc_({filteredIr:e,headers:t}){return t.map(r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function fnE({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=Az({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=Az({filteredIr:e,exampleTypeReference:r});return i!==void 0?uG.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function dnE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Qq.ok(uC.body(i!=null?Az({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Qq.ok(uC.stream(i.map(n=>Az({filteredIr:e,exampleTypeReference:n})).filter(g0))),sse:i=>Qq.ok(uC.sse(i.map(({event:n,data:a})=>{let u=Az({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(g0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Qq.error({error:r,body:i!=null?Az({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function rrc({filteredIr:e,example:t}){return{...t,rootPathParameters:trc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:trc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:trc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:pc_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:pc_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:lnE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?fnE({filteredIr:e,requestBody:t.request}):void 0,response:dnE({filteredIr:e,response:t.response})}}function hc_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=Az({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:uw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:uw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:Az({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=_c_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:uw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=Az({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:uw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function yc_({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:F_i({referencedIn:t,importPath:l})}}var A3i=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=r0({relativeFilepath:n,definitionFile:a,casingsGenerator:U_i,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[f,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:f,endpoint:s,file:l})}),eFi(this.workspace,(n,a)=>{let u=r0({relativeFilepath:n,definitionFile:a,casingsGenerator:U_i,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,f]of Object.entries(a.service?.endpoints??{}))f.method===t&&f.path===r&&(i={endpointId:l,endpoint:f,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new zxi().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=yc_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var q3i=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=zDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:r0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var NDe=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(mj(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(`\\${fJt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(fJt))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(fJt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(fJt.length),exampleName:n}}};var T7o=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:eie.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:eie.query(w7o({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:eie.body(u)}}if(oC(i.body)){let u=$tc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:eie.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:eie.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Htc({typeResolver:this.typeResolver,file:z0a(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 h1=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=zDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cne(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=pz(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let f=n.types?.[l];return f!=null?{typeName:l,declaration:f,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:r0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return x2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Bf.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Bf.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Bf.container(Tv.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Bf.container(Tv.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Bf.container(Tv.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Bf.container(Tv.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Bf.container(Tv.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Bf.container(Tv.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(Fci(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=N0a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||cne(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 I9t=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:NYr({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 C7o(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function FF({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:f,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=BDe({generationLanguage:t,keywords:r,smartCasing:i}),O=new EFi(a),m=NYr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),P=(e.definition.rootApiFile.contents.errors??[]).map(at=>({error:L_i({errorName:at,file:m}),docs:void 0})),E=new h1(e),q=new A3i(e),A=new T7o(E,q),D=new q3i(e),C=new NDe(E),z=new I9t,$={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:Ks_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:B0a(e.definition.rootApiFile.contents.docs),auth:Js_({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,he])=>hRe({headerKey:at,header:he,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([at,he])=>hRe({headerKey:at,header:he,file:m})):[],types:{},errors:{},services:{},constants:Rs_(g),environments:zEn({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:ks_(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:VMn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:Hxe.Root,variableResolver:z}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([at,he])=>({docs:typeof he!="string"?he.docs:void 0,id:at,name:m.casingsGenerator.generateName(at),type:m.parseTypeReference(he)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},x=new M7o,L=at=>{x.addSubpackage(at.fernFilepath),aw(at.definitionFile,{imports:Go,docs:he=>{he!=null&&x.addDocs(at.fernFilepath,he)},types:he=>{if(he!=null)for(let[Pe,bt]of Object.entries(he)){if(Lxe(Pe))continue;let Dt=sc_({typeName:Pe,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=em.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,Vu_(bt))}},errors:he=>{if(he==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[bt,Dt]of Object.entries(he)){let sr=Xs_({errorName:bt,errorDeclaration:Dt,file:at,typeResolver:E,exampleResolver:C,workspace:e}),ur=em.generateErrorId(sr.name);$.errors[ur]=sr,x.addError(ur,sr),O.addError(sr)}},service:he=>{if(he==null)return;let Pe=Bs_({rootDefaultUrl:at.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:he,file:at,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:P,variableResolver:z,workspace:e}),bt=em.generateServiceId(Pe.name);$.services[bt]=Pe,x.addService(bt,Pe);let Dt={};Pe.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=he.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),Dt[sr.name.originalName]=sr}),he.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,he.audiences),Object.entries(he.endpoints).map(([sr,ur])=>{let ni=Dt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ni],ur.audiences)})},webhooks:he=>{if(he==null)return;let Pe=em.generateWebhookGroupId(at.fernFilepath),bt=tc_({webhooks:he,file:at,typeResolver:E,exampleResolver:C,workspace:e}),Dt={};for(let sr of bt)Dt[sr.name.originalName]=sr;Object.entries(he).forEach(([sr,ur])=>{let ni=Dt[sr];ni!=null&&(O.addWebhook(at.fernFilepath,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(at.fernFilepath,ni,ur.audiences))}),$.webhookGroups[Pe]=bt,x.addWebhookGroup(Pe,at.fernFilepath)},channel:he=>{if(he==null)return;let Pe=em.generateWebSocketChannelId(at.fernFilepath),bt=Ys_({channel:he,file:at,variableResolver:z,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(at.fernFilepath,Pe,bt,he),he.audiences!=null&&O.markChannelForAudiences(at.fernFilepath,Pe,he.audiences),$.websocketChannels!=null&&($.websocketChannels[Pe]=bt,x.addWebSocketChannel(Pe,at.fernFilepath))}})};AF(e,(at,he,Pe)=>{L(r0({relativeFilepath:at,definitionFile:he,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),eFi(e,(at,he)=>{if(he.navigation!=null)if(typeof he.navigation=="string")x.addPackageRedirection({from:One({relativeFilepath:at,casingsGenerator:g}),to:One({relativeFilepath:NR(cxe(at),Xh.of(he.navigation)),casingsGenerator:g})});else{let Pe=he.navigation.map(bt=>em.generateSubpackageId(One({relativeFilepath:NR(cxe(at),Xh.of(bt)),casingsGenerator:g})));at===nS?x.sortRootPackage(Pe):x.sortSubpackage(em.generateSubpackageId(One({relativeFilepath:at,casingsGenerator:g})),Pe)}}),$.serviceTypeReferenceInfo=_nE(O);let V=n.disabled?$:bYr({ir:$,exampleGeneration:n}),Y=e.definition.rootApiFile.contents,K=zEn({casingsGenerator:g,rawApiFileSchema:Y}),Z=K?.environments._visit({singleBaseUrl:at=>at.environments.filter(he=>C7o(he.id,Y.environments)!=null).length===0,multipleBaseUrls:at=>at.environments.filter(he=>C7o(he.id,Y.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(at=>{O.markEnvironmentForAudiences(at,C7o(at.id,Y.environments)??[],Z)});let fe=O.hasNoAudiences()?void 0:O.build(),me=hnE(V,fe),_e=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(at=>at.endpoints.every(he=>he.auth)),Se=Object.values(me.services).some(at=>at.endpoints.some(he=>he.response?.body?.type==="streaming")),Qe=Object.values(me.services).some(at=>at.endpoints.some(he=>he.pagination!=null)),St=Object.values(me.services).some(at=>at.endpoints.some(he=>he.response?.body?.type==="fileDownload")),Ee={isAuthMandatory:_e,hasStreamingEndpoints:Se,hasPaginatedEndpoints:Qe,hasFileDownloadEndpoints:St,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:f!=null&&l!=null?{header:"User-Agent",value:`${l}/${f}`}:void 0}},Te=u!=null?ec_({readme:u,services:$.services}):void 0,{types:It,services:je}=lc_(me),Ot=pnE({...me,...x.build(fe),types:It,services:je,sdkConfig:Ee,readmeConfig:Te});return{...Ot,dynamic:Is_({ir:Ot,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function pnE(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]=B0a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function _nE(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 hnE(e,t){if(t==null)return e;let r=ACi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let f=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>hc_({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)&&f.push(s);return[u,{...l,shape:KO.object({...l.shape,properties:f})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let f=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,f]})),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:ACi(e.errors,u=>t.hasError(u)),services:nd(ACi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(f=>({...f,example:rrc({filteredIr:t,example:f.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(f=>({...f,example:f.example!=null?rrc({filteredIr:t,example:f.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(f=>t.hasQueryParameter(l.id,f.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(f=>t.hasRequestProperty(l.id,f.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:ynE(e.serviceTypeReferenceInfo,t)}}function ynE(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 vc_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var gc_=li(yna(),1);var bc_=["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 z9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,gc_.default)(e,{special:bc_}).replace(/V\s(\d)/g,"V$1")}function V0a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&vc_(e),r._other(e))}}}function UZt(e){return typeof e.subpackageId=="string"}function aB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function yRe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var irc="__package__",W_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 UZt(t)?t.subpackageId:irc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=t4.SubpackageId(t);return r===irc?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=t4.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 f=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{f.push(`${o} ${aB(u.path.parts)}`),f.push(`${o} ${yRe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${Wv(c.baseUrl,aB(u.path.parts))}`),f.push(`${o} ${Wv(c.baseUrl,yRe(u.path.parts))}`);let b=B7o(c);b!=null&&(f.push(`${o} ${Wv(b,aB(u.path.parts))}`),f.push(`${o} ${Wv(b,yRe(u.path.parts))}`))})}),f.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 f=[];["GET","WSS"].forEach(o=>{f.push(`${o} ${aB(u.path.parts)}`),f.push(`${o} ${yRe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${Wv(c.baseUrl,aB(u.path.parts))}`),f.push(`${o} ${Wv(c.baseUrl,yRe(u.path.parts))}`);let b=B7o(c);b!=null&&(f.push(`${o} ${Wv(b,aB(u.path.parts))}`),f.push(`${o} ${Wv(b,yRe(u.path.parts))}`))})}),f.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=UZt(t)?[...r,t.name]:r,n=i.length===0?[irc]: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 B7o(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 WMn=li(qFo(),1),mc_=li(TFo(),1);function Oc_(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{}}WMn.default.extend(mc_.default);var vnE="Changelog",bnE=["summary","index","overview"],LYr=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??vnE,i=[],n;for(let b of this.changelogFiles??[]){let g=a_s(b.split("/"));if(g==null)continue;let O=Oc_(g);if(O==null){let P=g.split(".")[0]?.toLowerCase();P!=null&&bnE.includes(P)&&(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??Gq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=WMn.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}}),f=nrc(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,f,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=WMn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return nrc(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),f=this.idgen.get(`${t}/year/${a}`);return{id:f,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(f,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=WMn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return nrc(Array.from(n.entries()).map(([a,u])=>{let l=(0,WMn.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 KA(this.docsWorkspace.absoluteFilePath,t)}};function nrc(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 x7o(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 W0a({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=>W0a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),f=i(l,u);return{...e,children:f,pointsTo:void 0}}return e}function HMn({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 f=t(l.endpointId);if(f==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${f.method} ${r(f)}`,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 I7o({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return HMn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function VZt(e,t){if(t!=null)return KA(e.absoluteFilePath,t)}function z7o({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=xo.V1.PageId(VZt(e,t.absolutePath)),f=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Gq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:f.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 R7o=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,f,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=W_i.create(r,a),this.#u=f,this.#c=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(VZt(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??Gq(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 LYr(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?W_i.getSubpackageId(r):void 0;return t.map(a=>V0a(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(g0)}#f(t,r){return z7o({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(VZt(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=W_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 f=t.slug??(UZt(a)?a.urlSlug:this.apiSection.slug??Gq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),o=this.#s(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(UZt(a)?a.displayName??z9t(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??Gq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),f=this.#s(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Gq(t.package)}`),type:"apiPackage",children:f,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(VZt(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?W_i.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(g0);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 f=t.slug??Gq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),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=W_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=UZt(n)?n.urlSlug:"",f=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:UZt(n)?n.displayName??z9t(n.name):this.apiSection.title,slug:f.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(t4.SubpackageId(r))?.endpoints.get(t4.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 f=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??aB(n.path.parts),slug:f.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(t4.SubpackageId(r))?.webSockets.get(t4.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??aB(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(t4.SubpackageId(r))?.webhooks.get(t4.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??Wv("/",...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 I7o({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>aB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return W0a({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??aB(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??aB(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??z9t(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=UZt(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:UZt(a)?a.displayName??z9t(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 x7o(t)}mergeEndpointPairs(t){return HMn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>aB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var N7o=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[$y(r).toLowerCase()]=i,this.#e[`subpackage_${$y(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Wv(a.baseUrl,aB(i.path))}`]=i,this.#r[`${n} ${Wv(a.baseUrl,yRe(i.path))}`]=i;let u=B7o(a);u!=null&&(this.#r[`${n} ${Wv(u,aB(i.path))}`]=i,this.#r[`${n} ${Wv(u,yRe(i.path))}`]=i)}),this.#r[`${i.method} ${aB(i.path)}`]=i,this.#r[`${i.method} ${yRe(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 ${aB(i.path)}`]=i,this.#n[`STREAM ${yRe(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 H0a({item:e,parentSlug:t}){return t.apply({urlSlug:Gq(e.id.split(".").pop()??"")}).get()}var $0a=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,f,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=f,this.hideChildren=o,this.#e=r,this.#t=new N7o(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(VZt(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??Gq(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 LYr(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=>V0a(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(g0)}#_(t,r){return z7o({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(VZt(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??Gq(a.name),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,f),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??z9t(a.name),slug:f.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??Gq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),f=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${Gq(t.package)}`),type:"apiPackage",children:f,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(VZt(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(g0);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??Gq(t.title),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,f),o={id:a,type:"apiPackage",children:s,title:t.title,slug:f.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=Gq(n.name),f=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??z9t(n.name),slug:f.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():H0a({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??aB(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??aB(a.path),slug:t.slug!=null?i.append(t.slug).get():H0a({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??Wv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():H0a({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 I7o({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>aB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return W0a({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(bA.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(bA.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(bA.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:Gq(r.name)}),a=this.#w(t,n),u={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??z9t(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=H0a({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:bA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??aB(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:bA.WebSocketId(t),title:r.displayName??aB(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:bA.WebhookId(t),method:r.method,title:r.displayName??z9t(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(".")===bA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===bA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===bA.api.v1.SubpackageId(t)));return{id:bA.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 x7o(t)}mergeEndpointPairs(t){return HMn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>aB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Pc_=li(require("crypto"),1);function gnE(e){return Pc_.default.createHash("sha256").update(e).digest("hex")}var F7o=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),gnE(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 L7o(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 U7o=li(LSe(),1);var arc=li(LSe(),1);function jc_(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,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:arc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:arc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Mo(i)}}var nj=li(LSe(),1);var H_i=li(LSe(),1);function Sc_(e){return e._visit({alias:t=>({type:"alias",value:JD(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:n6(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>H_i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:H_i.FernRegistry.PropertyKey(r.name.wireValue),valueType:JD(r.valueType),availability:n6(r.availability)})),extraProperties:PnE(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:H_i.FernRegistry.PropertyKey(i.name.wireValue),valueType:JD(i.valueType),availability:n6(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?n6(i.availability):void 0,additionalProperties:Ks.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[H_i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:H_i.FernRegistry.PropertyKey(n.name.wireValue),valueType:JD(n.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:JD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function JD(e){return e._visit({container:t=>Ks.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:JD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:JD(r),valueType:JD(i)}),optional:r=>({type:"optional",itemType:JD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:JD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:JD(r)}),literal:r=>Ks.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:H_i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Ks.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>mnE(t.v2),float:()=>wc_(t.v2),double:()=>wc_(t.v2),string:()=>OnE(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 OnE(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 mnE(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 wc_(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 PnE(e){return typeof e=="boolean"?e?Bf.unknown():void 0:typeof e=="string"?{type:"id",value:H_i.FernRegistry.TypeId(e),default:void 0}:JD(e)}function urc(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?wnE(r,t):[],webhooks:i!=null?jnE(i):[],websockets:n!=null?[SnE(n,t)]:[],types:e.types.map(a=>nj.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>nj.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?nj.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function jnE(e){return e.map(t=>({description:t.docs??void 0,id:nj.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??TCi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:JD(r.valueType),availability:n6(r.availability)})),payload:BnE(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function wnE(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 f=Object.values(i.v2Examples.userSpecifiedExamples)[0];l=Dc_({example:f,irEndpoint:i})}else if(Object.keys(i.v2Examples.autogeneratedExamples).length>0){let f=Object.values(i.v2Examples.autogeneratedExamples)[0];l=Dc_({example:f,irEndpoint:i})}l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>orc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(g0));else if(n!=null){let l=orc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Xva({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let f=orc({autogeneratedExample:l,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:n6(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:AnE(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?nj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?DnE({environmentsConfig:t.environments,endpoint:i}):void 0,id:nj.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??TCi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:nj.FernRegistry.PropertyKey(l.name.originalName),type:JD(l.valueType),availability:void 0})),parts:[...$Mn(i.basePath),...$Mn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:nj.FernRegistry.PropertyKey(l.name.originalName),type:JD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?$Mn(t.basePath):[],...$Mn(e.basePath),...$Mn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:JD(l.valueType),availability:n6(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:JD(l.valueType),availability:n6(l.availability)})),request:i.requestBody!=null?qnE(i.requestBody):void 0,response:i.response!=null?TnE(i.response):void 0,errors:void 0,errorsV2:CnE(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 SnE(e,t){return{auth:e.auth,availability:n6(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?nj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?EnE({environmentsConfig:t.environments,channel:e}):[],id:nj.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??TCi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:nj.FernRegistry.PropertyKey(r.name.originalName),type:JD(r.valueType),availability:void 0})),parts:$Mn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:JD(r.valueType),description:r.docs,availability:n6(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:JD(r.valueType),availability:n6(r.availability)})),messages:e.messages.map(r=>({type:nj.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:xnE(r.body),description:r.docs,availability:n6(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[nj.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:nj.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function n6(e){if(e!=null)switch(e.status){case"DEPRECATED":return nj.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return nj.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return nj.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return nj.FernRegistry.Availability.Beta;default:Mo(e.status)}}function DnE({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:nj.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:nj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function EnE({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:nj.FernRegistry.EnvironmentId(n.id),baseUrl:MnE(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:nj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function MnE(e,t){return e.replace(/^[^:]+/,t)}function AnE(e){return Ks.http.HttpMethod._visit(e,{get:()=>nj.FernRegistry.HttpMethod.Get,post:()=>nj.FernRegistry.HttpMethod.Post,put:()=>nj.FernRegistry.HttpMethod.Put,patch:()=>nj.FernRegistry.HttpMethod.Patch,delete:()=>nj.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function $Mn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:nj.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function qnE(e){let t=Ks.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??lx.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>nj.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:nj.FernRegistry.PropertyKey(i.name.wireValue),valueType:JD(i.valueType),availability:n6(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??lx.APPLICATION_JSON,shape:{type:"reference",value:JD(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:nj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:nj.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:nj.FernRegistry.PropertyKey(n.name.wireValue),valueType:JD(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:n6(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(g0)},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 TnE(e){if(e.body==null)return;let t,r=Ks.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:JD(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:JD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:JD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});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 CnE(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:JD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:nj.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:nj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:JD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Dc_({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(mj(e.request.requestBody)){let a=e.request.requestBody;for(let u of i.properties)u._visit({file:l=>{let f=a[l.key.wireValue];if(l.type==="file")n[l.key.wireValue]={type:"filename",value:typeof f=="string"?f:"<file1>"};else if(l.type==="fileArray"){let s=(Array.isArray(f)?f:[f]).filter(o=>typeof o=="string");n[l.key.wireValue]={type:"filenames",value:s}}},bodyProperty:l=>{if(l.style==="exploded"){let f=a[l.name.wireValue];n[l.name.wireValue]={type:"exploded",value:Array.isArray(f)?f:[f]}}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(g0)}}function orc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let f=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(f!=null)return{name:l.name,value:{jsonExample:f,shape:Ks.ExampleTypeReferenceShape.primitive(Ks.ExamplePrimitive.string({original:f}))}}}).filter(g0),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,f)=>(l[nj.FernRegistry.PropertyKey(f.name.originalName)]=f.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,f)=>(l[f.name.wireValue]=f.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,f)=>(l[f.name.wireValue]=f.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 f={};if(mj(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")f[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");f[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];f[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else f[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:kBe})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Ks.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:f=>f!=null?200:204,stream:f=>f.length>0?200:204,sse:f=>f.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let f=i.errors[l.errorId];if(f==null)throw new Error("Cannot find error "+l.errorId);return f.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:f=>f?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:f=>f!=null?{type:"json",value:f.jsonExample}:void 0,stream:f=>({type:"stream",value:f.map(s=>s.jsonExample)}),sse:f=>({type:"sse",value:f.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=>VSe._visit(l,{language:f=>({language:f.language,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:f.install}),sdk:f=>({language:f.sdk,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:void 0}),_other:()=>{}})).filter(g0)}}function BnE(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>nj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:nj.FernRegistry.PropertyKey(t.name.wireValue),valueType:JD(t.valueType),availability:n6(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:JD(e.payloadType)},description:e.docs};default:Mo(e)}}function xnE(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>nj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:nj.FernRegistry.PropertyKey(t.name.wireValue),valueType:JD(t.valueType),availability:n6(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:JD(e.bodyType)};default:Mo(e)}}function WX({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:urc(e.rootPackage,e),auth:jc_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:n6(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:JD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[U7o.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Sc_(a.shape),availability:n6(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[U7o.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:U7o.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...urc(a,e)}}return i}var src=li(LSe(),1);async function crc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=FF({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 IF(r,t)}),f=oIi({token:i.value}),s=WX({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await f.api.v1.register.registerApiDefinition({orgId:src.FernRegistry.OrgId(e),apiId:src.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 InE=new O3i({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function G0a(e,t,r){return h0a(d0a(WX({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),t4.ApiDefinitionId(t),InE))}var W_={};jo(W_,{AlgoliaSearchIndex:()=>Ec_,ApiDefinitionId:()=>Jc_,ApiId:()=>Zc_,Availability:()=>pl_,DocsConfigId:()=>kc_,EndpointId:()=>tl_,EndpointPathLiteral:()=>fl_,EnvironmentId:()=>el_,FileId:()=>ol_,HttpMethod:()=>dl_,IndexSegmentId:()=>Mc_,JqString:()=>sl_,OrgId:()=>Yc_,PageId:()=>al_,PayloadLocation:()=>Ll_,PropertyKey:()=>cl_,PullRequestState:()=>Il_,RoleId:()=>ll_,TokenId:()=>Xc_,TypeId:()=>nl_,Url:()=>ul_,VersionId:()=>Kc_,WebSocketId:()=>rl_,WebhookId:()=>il_,algolia:()=>lrc,api:()=>Orc,commons:()=>mrc,diff:()=>_l_,docs:()=>qrc,generators:()=>Crc,git:()=>Brc,navigation:()=>zrc,sdks:()=>Nrc,snippets:()=>Nl_,snippetsFactory:()=>Fl_,templates:()=>Frc,tokens:()=>Ul_});var lrc={};jo(lrc,{AlgoliaSearchIndex:()=>Ec_,IndexSegmentId:()=>Mc_});function Ec_(e){return e}function Mc_(e){return e}var Orc={};jo(Orc,{latest:()=>prc,v1:()=>grc});var prc={};jo(prc,{AuthSchemeId:()=>Ac_,WebhookHttpMethod:()=>Bc_,auth:()=>frc,commons:()=>qc_,endpoint:()=>Tc_,type_:()=>Cc_,webhook:()=>drc,websocket:()=>xc_});var frc={};jo(frc,{AuthSchemeId:()=>Ac_});function Ac_(e){return e}var qc_={};var Tc_={};var Cc_={};var drc={};jo(drc,{WebhookHttpMethod:()=>Bc_});var Bc_={Get:"GET",Post:"POST"};var xc_={};var grc={};jo(grc,{SubpackageId:()=>Hc_,WebSocketMessageId:()=>$c_,WebSocketMessageOrigin:()=>Gc_,WebhookHttpMethod:()=>Qc_,commons:()=>brc,db:()=>_rc,read:()=>yrc,register:()=>vrc});var _rc={};jo(_rc,{endpoint:()=>Ic_});var Ic_={};var yrc={};jo(yrc,{SupportedLanguage:()=>zc_,endpoint:()=>hrc,type_:()=>Rc_,webhook:()=>Nc_,websocket:()=>Fc_});var hrc={};jo(hrc,{SupportedLanguage:()=>zc_});var zc_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Rc_={};var Nc_={};var Fc_={};var vrc={};jo(vrc,{SourceId:()=>znE,endpoint:()=>Lc_,type_:()=>Uc_,webhook:()=>Vc_,websocket:()=>Wc_});var Lc_={};var Uc_={};var Vc_={};var Wc_={};function znE(e){return e}var brc={};jo(brc,{SubpackageId:()=>Hc_,WebSocketMessageId:()=>$c_,WebSocketMessageOrigin:()=>Gc_,WebhookHttpMethod:()=>Qc_});function Hc_(e){return e}function $c_(e){return e}var Gc_={Client:"client",Server:"server"};var Qc_={Get:"GET",Post:"POST"};var mrc={};jo(mrc,{ApiDefinitionId:()=>Jc_,ApiId:()=>Zc_,Availability:()=>pl_,DocsConfigId:()=>kc_,EndpointId:()=>tl_,EndpointPathLiteral:()=>fl_,EnvironmentId:()=>el_,FileId:()=>ol_,HttpMethod:()=>dl_,JqString:()=>sl_,OrgId:()=>Yc_,PageId:()=>al_,PropertyKey:()=>cl_,RoleId:()=>ll_,TokenId:()=>Xc_,TypeId:()=>nl_,Url:()=>ul_,VersionId:()=>Kc_,WebSocketId:()=>rl_,WebhookId:()=>il_});function Jc_(e){return e}function Kc_(e){return e}function Yc_(e){return e}function Xc_(e){return e}function Zc_(e){return e}function kc_(e){return e}function el_(e){return e}function tl_(e){return e}function rl_(e){return e}function il_(e){return e}function nl_(e){return e}function al_(e){return e}function ol_(e){return e}function ul_(e){return e}function sl_(e){return e}function cl_(e){return e}function ll_(e){return e}function fl_(e){return e}var dl_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var pl_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var _l_={};var qrc={};jo(qrc,{latest:()=>wrc,v1:()=>Mrc,v2:()=>Arc});var wrc={};jo(wrc,{Layout:()=>yl_,MdxEngine:()=>RnE,TwitterCardSetting:()=>vl_,commons:()=>hl_,frontmatter:()=>Prc,seo:()=>jrc});var RnE={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var hl_={};var Prc={};jo(Prc,{Layout:()=>yl_});var yl_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var jrc={};jo(jrc,{TwitterCardSetting:()=>vl_});var vl_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Mrc={};jo(Mrc,{commons:()=>Erc,db:()=>bl_,read:()=>gl_,write:()=>Src});var bl_={};var gl_={};var Src={};jo(Src,{DocsRegistrationId:()=>FnE,FilePath:()=>NnE});function NnE(e){return e}function FnE(e){return e}var Erc={};jo(Erc,{ContentAlignment:()=>jl_,FontDisplay:()=>Ml_,FontStyle:()=>El_,HeaderPosition:()=>wl_,JsScriptStrategy:()=>Dl_,ProgrammingLanguage:()=>Ol_,SearchbarPlacement:()=>ml_,TabsPlacement:()=>Pl_,TwitterCardSetting:()=>Sl_,commons:()=>Drc});var Drc={};jo(Drc,{ContentAlignment:()=>jl_,FontDisplay:()=>Ml_,FontStyle:()=>El_,HeaderPosition:()=>wl_,JsScriptStrategy:()=>Dl_,ProgrammingLanguage:()=>Ol_,SearchbarPlacement:()=>ml_,TabsPlacement:()=>Pl_,TwitterCardSetting:()=>Sl_});var Ol_={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 ml_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Pl_={Header:"HEADER",Sidebar:"SIDEBAR"};var jl_={Center:"CENTER",Left:"LEFT"};var wl_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Sl_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Dl_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var El_={Normal:"normal",Italic:"italic"};var Ml_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Arc={};jo(Arc,{read:()=>Al_,write:()=>ql_});var Al_={};var ql_={};var Crc={};jo(Crc,{ChangelogEntryType:()=>Cl_,GeneratorId:()=>LnE,GeneratorLanguage:()=>UnE,ReleaseType:()=>Bl_,cli:()=>Tl_,commons:()=>Trc,versions:()=>xl_});var Tl_={};var Trc={};jo(Trc,{ChangelogEntryType:()=>Cl_,ReleaseType:()=>Bl_});var Cl_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Bl_={Ga:"GA",Rc:"RC"};var xl_={};function LnE(e){return e}var UnE={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Brc={};jo(Brc,{PullRequestState:()=>Il_});var Il_={Open:"open",Closed:"closed",Merged:"merged"};var zrc={};jo(zrc,{latest:()=>xrc,v1:()=>Irc});var xrc={};jo(xrc,{NodeId:()=>HnE,ProductId:()=>$nE,Slug:()=>VnE,TabId:()=>WnE});function VnE(e){return e}function WnE(e){return e}function HnE(e){return e}function $nE(e){return e}var Irc={};jo(Irc,{NavigationV1Availability:()=>YnE,NodeId:()=>JnE,ProductId:()=>KnE,Slug:()=>GnE,TabId:()=>QnE});function GnE(e){return e}function QnE(e){return e}function JnE(e){return e}function KnE(e){return e}var YnE={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Nrc={};jo(Nrc,{Language:()=>zl_,VersionBump:()=>Rl_,versions:()=>Rrc});var Rrc={};jo(Rrc,{Language:()=>zl_,VersionBump:()=>Rl_});var zl_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Rl_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var Nl_={};var Fl_={};var Frc={};jo(Frc,{PayloadLocation:()=>Ll_});var Ll_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var Ul_={};var GMn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Nd(e){return e!=null}var Wl_=li(yna(),1);var Vl_=["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 WZt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Wl_.default)(e,{special:Vl_}).replace(/V\s(\d)/g,"V$1")}function V7o({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:WZt(a)},n.push(a)})}),r}var W7o=class{errors=new GMn},QMn=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 Hl_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var H7o=class extends W7o{},Wp=class extends QMn{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 ${Hl_(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})}}},LF=class extends Wp{},Pne=class extends LF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var $l_="x-fern-base-path",Gl_="x-fern-availability",$7o="x-fern-sdk-group-name",Ql_="x-fern-global-headers",Jl_="x-fern-sdk-method-name";var Kl_="x-fern-webhook",Yl_="x-fern-access-token-locator",Xl_="x-fern-basic",Zl_="x-fern-username-variable-name",kl_="x-fern-password-variable-name",ef_="x-fern-bearer",tf_="x-fern-token-variable-name",rf_="x-fern-header",if_="x-fern-header-variable-name",nf_="x-fern-server-name",af_="x-fern-examples";var G7o=class extends Wp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[nf_]}convert(){if(this.serverName!=null)return this.serverName}};var Q7o=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 G7o({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 HZt(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,f)=>new Q7o({input:l,context:r,accessPath:i,pathId:["servers",`${f}`]}));return[...n,...u]}function pS(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function QV(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:(pS(n)&&(n=QV(n,t,r)),n)}function J7o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return pS(r)?QV(r,t,void 0):r}var mf_=li(Ax());var K7o=class extends Wp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Xl_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Y7o=class extends Wp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[kl_]}convert(){return this.passwordVariableName}};var X7o=class extends Wp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[Zl_]}convert(){return this.usernameVariableName}};var Z7o=class extends Wp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ef_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var k7o=class extends Wp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[tf_]}convert(){return this.tokenVariableName}};function of_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var uf_="x-bearer-format",sf_="x-code-samples",cf_="x-codeSamples";var e6o=class extends Wp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[uf_]}convert(){return this.bearerFormat}};var t6o=class extends Wp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[rf_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var r6o=class extends Wp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[if_]}convert(){return this.headerVariableName}};function lf_(e){return e.type==="apiKey"}var JMn=class extends Wp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){lf_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new t6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new r6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new e6o({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 ff_(e){return e}function df_(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var XnE=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function pf_(e){return Array.from(e.match(XnE)??[])}function _f_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function hf_(e){return Object.is(e,-0)?"-0":e.toString()}function yf_(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 Lrc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?_f_(t)?Lrc(e,yf_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=hf_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return ZnE(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function ZnE(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 vf_(e){return function(t){return Lrc(t,e)}}function Urc(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 i6o(e,t){switch(t=t??ff_,typeof t){case"string":case"symbol":case"number":case"object":return Urc(e,vf_(t));case"function":return Urc(e,t)}}function bf_(e){let t=pf_(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>df_(n)).join("")}`}function Vrc(e){if(e==null)return"";if(Array.isArray(e))return e.map(Vrc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function gf_(e){return typeof e!="string"&&(e=Vrc(e)),e.replace(/['\u2019]/g,"")}function R9t(e){return bf_(gf_(e))}function LM(e){if(e!=null)return Array.isArray(e)?e:[e]}function n6o({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`${knE(u)}${eaE(e)}.${taE(i,n,a,l)}`}function knE(e){return e?"webhook_":"endpoint_"}function eaE(e){return e!=null?LM(e)?.map(t=>R9t(t)).join("/"):""}function taE(e,t,r,i){return e||t||R9t(r??"")||R9t(i??"")}function Of_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var a6o=class extends Wp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[Yl_],this.accessTokenLocator!=null&&(Of_(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 o6o=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 JMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new a6o({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=n6o({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 KMn=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 X7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Y7o({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 Z7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new k7o({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":{of_(this.input)?(this.authScheme="header",this.headerAuthNode=new JMn({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 o6o({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 mf_.UnreachableCaseError(this.authScheme);return}}};var YMn=class extends Wp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=J7o(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 KMn({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 u6o=class extends Wp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[$l_],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 Pf_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function jf_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function XMn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>LM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!Pf_(n))&&(u=jf_(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 s6o(e,t){return pS(e)?QV(e,t,void 0):e}function $_i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function wf_(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 Sf_(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 Df_=li(Ax());var Wrc=["decimal","decimal128","double-int","double","float","sf-decimal"],Hrc=["int16","int32","int64","int8","sf-integer","uint8"],$rc=["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"],Grc=["beta","pre-release","in-development","generally-available","deprecated"];function UF(e,t){return pS(e)?QV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var vRe=class extends Wp{availability;constructor(t){super(t),this.safeParse()}parse(){if(UF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[Gl_];r!=null&&(Grc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Grc.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 Df_.UnreachableCaseError(this.availability);return}}};var l6o=li(Ax());function Ef_(e){return typeof e=="object"&&e!=null&&"language"in e}function Mf_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Af_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function qf_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function c6o(e){return typeof e=="object"&&e!=null&&"event"in e}function Qrc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(c6o)}function G_i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Tf_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var f6o=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[af_]}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 G_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=>G_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 l6o.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=Tf_(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 l6o.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Af_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{Qrc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!Qrc(r.response)&&qf_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new l6o.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Ef_(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})):Mf_(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 f=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(f).length>0?f: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 Q0a=class extends Wp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[$7o]}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(R9t(r)))}};var d6o=class extends Wp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[Jl_]}convert(){return this.sdkMethodName}};var p6o=class extends Wp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[Kl_]}convert(){return this.isWebhook}};var _6o=class extends Wp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[sf_]??[],...this.input[cf_]??[]],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 T3i=li(Ax());function Jrc(e,t){return pS(e)?QV(e,t,void 0):e}function Cf_(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 o9="",$Zt=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&&(G_i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>G_i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new T3i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Jrc(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=Jrc(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 T3i.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(c6o)){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 T3i.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 G_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=>G_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 T3i.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 T3i.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 T3i.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:Cf_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?WZt(this.name):this.summary!=null?WZt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Bf_(e,t){return pS(e)?QV(e,t,void 0):e}var Gf_=li(Ax());var xf_="#/components/schemas/";function ZMn(e){if(e.$ref.startsWith(xf_))return e.$ref.replace(xf_,"")}function UYr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function Q_i(e){return typeof e.type=="string"&&e.type==="array"}function If_(e){return e.type==="boolean"}function zf_(e){return e.type==="integer"}function J_i(e){return!Array.isArray(e.type)&&!Q_i(e)}function Rf_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||J_i(t)||Q_i(t))}function Nf_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ff_(e){return e.type==="null"}function Lf_(e){return e.type==="number"}function Krc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Uf_(e){return e.type==="string"}var h6o=class extends Pne{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new lq({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 LM(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 y6o=class extends LF{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 vRe({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 v6o=class extends Pne{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 lq({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=>LM(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(UYr).filter(Nd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function b6o(e){return e!=null&&e.length>0?e:[void 0]}var kMn=class extends Pne{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 lq({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 lq({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(pS(t))return ZMn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new lq({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 XMn(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}}}]:LM(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=>b6o(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=UF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new lq({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 g6o=class extends Pne{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=>UF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>UF(t,this.context.document)?.type!=="null"?new lq({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=UF({$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 lq({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(UYr).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])=>LM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??WZt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Nd)).filter(Nd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>LM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?WZt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?WZt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Nd)).filter(Nd)}:void 0,i=this.isNullable?UYr(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 O6o=class extends LF{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 K_i=class extends LF{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(pS(r)){let n=UF(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 Vf_=li(Ax());function raE(e){return Hrc.includes(e)}var m6o=class extends LF{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&&(raE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Hrc.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 Vf_.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 P6o=class extends LF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UYr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Wf_=li(Ax());function iaE(e){return Wrc.includes(e)}var j6o=class extends LF{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&&(iaE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Wrc.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 Wf_.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 Hf_=li(Ax());function naE(e){return $rc.includes(e)}var w6o=class extends LF{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 Hf_.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&&(naE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${$rc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new K_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 $f_=li(Ax());var S6o=class extends LF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,$f_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var C3i=class extends Pne{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=ZMn(this.input);let t=UF(this.input,this.context.document);t?.enum!=null&&J_i(t)&&(this.maybeEnumConverterNode=new K_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=UF(this.input,this.context.document);if(r!=null)return new lq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var lq=class e extends Pne{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 vRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),J_i(this.input)&&Nf_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),pS(this.input)){let t=ZMn(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 C3i({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 y6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Rf_(this.input))this.typeShapeNode=new v6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(J_i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new g6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Krc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new kMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(J_i(this.input)&&this.input.enum!=null)this.typeShapeNode=new K_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":Krc(this.input)&&(this.typeShapeNode=new kMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":Q_i(this.input)&&(this.typeShapeNode=new h6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":If_(this.input)&&(this.typeShapeNode=new O6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":zf_(this.input)&&(this.typeShapeNode=new m6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Lf_(this.input)&&(this.typeShapeNode=new j6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Uf_(this.input)&&(this.typeShapeNode=new w6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Ff_(this.input)&&(this.typeShapeNode=new P6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new Gf_.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 kMn({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 S6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!pS(this.input)&&(!Q_i(this.input)&&this.input==null||Q_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=LM(t)?.map(i=>this.nullable?UYr(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 Y_i(e){if(e!=null)return XMn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Nd))}var GZt=class extends LF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;pS(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 vRe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new lq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Bf_(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 Qf_(e,t){return pS(e)?QV(e,t,void 0):e}var Yrc=li(Ax());function D6o(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 Jf_=li(Kps(),1),eAn=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=Jf_.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 aaE(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var tAn=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 lq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),aaE(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(pS(r)?n=J7o(r.$ref,this.context.document):n=r,n!=null)return[t,new KMn({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=LM(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 E6o=class extends lq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=UF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${pS(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=UF(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 M6o=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=UF(this.input.schema,this.context.document);this.availability=new vRe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=pS(this.input.schema)?new C3i({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=eAn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new lq({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 E6o({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?{[o9]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[o9]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:LM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=R9t([this.method,this.path,this.contentType,"request"].join("_"));return D6o({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 Yrc.UnreachableCaseError(n);return}}).filter(Nd)}convert(){if(this.schema instanceof C3i)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=LM(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 Yrc.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 A6o=class extends Wp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Qf_(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 M6o({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])=>LM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Nd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>LM(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 Kf_={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 Yf_(e,t){if(pS(e)){let r=QV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var q6o=li(Ax());var Xf_="application/json";var Zf_="application/octet-stream";function kf_(e,t){return e===t||t===o9||e===o9}var J0a=class extends Wp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,f){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,f]of Object.entries(r))for(let s of f)kf_(l,a)&&(i.add(l),this.examples?.push(new $Zt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,$_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[f,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new $Zt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,$_i(s,u),{requestBody:f,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,f,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new $Zt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,$_i(f,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,f]of r.slice(t.length))this.examples?.push(...f.map(s=>new $Zt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,$_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[o9];if(a!=null)for(let u of a)this.examples?.push(new $Zt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,$_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=eAn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=Xf_,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 lq({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=Zf_,this.contentSubtype=UF(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 lq({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=i6o(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[o9]??=[],r[o9]=[{value:this.input.example}]);let i=UF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=i6o(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[o9]??=[],r[o9]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[o9]??=[],r[o9]?.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(([f])=>!n.has(f)&&f!==o9).map(([f,s])=>[l,f,s]));let u=Object.entries(r).filter(([l,f])=>!n.has(l)&&Nd(f)&&l!==o9);Object.keys(r).every(l=>l===o9)||this.matchExamplesByIndex(a,u),!n.has(o9)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return LM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new q6o.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return LM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=R9t([this.method,this.path,this.statusCode,"response"].join("_"));return D6o({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 q6o.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 q6o.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var K0a=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=Yf_(this.input,this.context.document);if(r==null){this.context.errors.error({message:pS(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 GZt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new J0a({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 J0a({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 T6o=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 K0a({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 K0a({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 b6o(Y_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=LM(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??Kf_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let f=l.convert();if(f!=null&&f.responseBody?.type==="json")return{name:f.name,description:f.description,responseBody:f.responseBody}}).filter(Nd)})).filter(Nd)})).filter(Nd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var X_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 $Zt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,$_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 vRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=HZt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new p6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(pS(i)){let a=s6o(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 GZt({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 GZt({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 GZt({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 _6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new A6o({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 T6o({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 YMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new Q0a({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 Q0a({input:{[$7o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new d6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>n6o({namespace:LM(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 f6o({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=Sf_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:wf_(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:Y_i(this.queryParameters)?.flat(),headers:Y_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,f=this.auth?.convert();f!=null&&(l=Object.keys(f));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:Y_i(this.pathParameters)?.flat(),queryParameters:Y_i(this.queryParameters)?.flat(),requestHeaders:Y_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 rAn=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=HZt(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 X_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 X_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 X_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 X_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 X_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 C6o(e){return"payloads"in e}var B6o=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 rAn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:HZt(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=>{C6o(a)?r[W_.WebhookId(a.id)]=a:t[W_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var x6o=class extends Wp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Ql_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||s6o(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new GZt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return XMn(this.globalHeaders,this.requiredProperties)?.flat()}};function ed_(e,t){if(pS(e)){let r=QV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var I6o=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=ed_(a,this.context.document);if(u!=null)return new rAn({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=>{C6o(i)&&(t[W_.WebhookId(i.id)]=i)}),t),{})}};var z6o=class extends Wp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=HZt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new YMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new u6o({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 B6o({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 I6o({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 tAn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new x6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Uie(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=V7o({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 iAn=class extends QMn{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 bRe(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function N9t(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:(bRe(n)&&(n=N9t(n,t,r)),n)}function td_(e,t){return bRe(e)?N9t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var ad_=li(Ax());function VYr(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]=VYr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VYr(t)):[VYr(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 VYr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VYr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VYr(r));return t}}function Y0a(e,t){return bRe(e)?N9t(e,t,{name:"",schema:{type:"object"}}):e}function rd_(e,t){return bRe(e)?N9t(e,t,void 0):e}function id_(e,t){return bRe(e)?N9t(e,t,void 0):e}function nd_(e,t){return bRe(e)?N9t(e,t,void 0):e}var oaE={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}}}},R6o=class extends iAn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Y0a(this.method.result,this.context.openrpc):void 0,r=t?new lq({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=>Y0a(l,this.context.openrpc)).filter(Nd)?.map(l=>{let f=new lq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!f)return;let s=Array.isArray(f)?f[0]:f;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 f=id_(l,this.context.openrpc);if(f)return{name:f.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:f.params.length>0?{type:"json",value:Object.fromEntries(f.params.map(s=>{let o=rd_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Nd))}:void 0,responseStatusCode:200,responseBody:f.result?{type:"json",value:f.result}:void 0}}).filter(Nd)??[];if(u.length<=0){let l=VYr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Y0a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),f={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:VYr(Y0a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(f)}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:[oaE],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=nd_(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=LM(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 ad_.UnreachableCaseError(u);return}}).filter(Nd)[0];if(n)return{statusCode:200,body:n,description:r}}};var X0a=class extends iAn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=HZt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=td_(t,this.context.openrpc);r!=null&&this.methods.push(new R6o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new tAn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Uie(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Nd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=V7o({endpoints:n});return{id:W_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var Z0a=class extends H7o{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 k0a(e,t){if(e instanceof yZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=new b9t(e.absoluteFilePath),i=await aRe({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 GMn,generatedTypes:{}},f=new z6o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=f_s(a,f.convert())}return a}var od_=require("fs/promises");async function ud_(e,t){let r=await(0,od_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Z0a({openrpc:i,logger:t.logger});return new X0a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function sd_(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 cd_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){saE(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Xrc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Xrc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Xrc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await uGt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Xrc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),uaE(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function uaE(e){return e.api!=null}function saE(e){return e[0]?.tab!=null}function HX(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ld_.default.extend(fd_.default);var caE=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),N6o=0,laE=async({ir:e})=>(N6o++,`${e.apiName.snakeCase.unsafeName}-${N6o}`),faE=async({api:e})=>(N6o++,`${e.id}-${N6o}`),F9t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=caE,f=laE,s=faE){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=f,this.registerApiV2=s}#e=F7o.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 xOs({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 cd_({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=KA(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[Xa.of(s)]=await MXs({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[Xa.of(s)]=await EXs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=sd_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=$ba(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Xa.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[Xa.of(s)]=DXs(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=daE(this.editThisPage,s);u[A9t.PageId(s)]={markdown:o,editThisPageUrl:c?A9t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=Vg(this.docsWorkspace.absoluteFilePath,o);(await(0,F6o.stat)(c)).isDirectory()?(await pxe(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),f=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,F6o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:f}}resolveFilepath(t){if(t!=null)return Vg(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return KA(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Zrc.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,Zrc.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 f=Lu(this.docsWorkspace.absoluteFilePath,Xa.of(l));r[f]=Wv(t,u)}),r}getDocsBasePath(){return new URL(HX(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?A9t.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:A9t.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:A9t.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 tyn(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??Gq(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??Gq(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?paE(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 f=u.length>0?u[u.length-1]:void 0,s;f?.type==="sidebarGroup"?s=f:(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 tyn(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=Vg(this.docsWorkspace.absoluteFilePath,Xa.of(t.openrpc));if(!await Cf(o))throw new Error(`OpenRPC file does not exist at path: ${o}`);let c=await ud_(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:L7o(t.snippetsConfiguration)}),new $0a(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=L7o(t.snippetsConfiguration),b=await k0a(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 $0a(t,b,r,o,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=L7o(t.snippetsConfiguration),a,u;this.parsedDocsConfig.experimental?.openapiParserV3?a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0}):(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0}),a=FF({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 IF(this.taskContext,u)}));let l=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=G0a(a,l,{oauth:t.playground?.oauth});return new R7o(t,f,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new LYr(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??Gq(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`),f=i.apply({urlSlug:r.slug??Gq(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:f.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,f,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 tyn(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 LYr(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??Gq(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):A9t.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(g0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:A9t.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 tyn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:A9t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function daE(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${HX(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function paE(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 JV(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof nN?t:null))).filter(g0)}async function krc(e,t,r){if(e instanceof yZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0});return WX({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var Kic=li(Gds(),1),sy_=li(f2o(),1),YZt=require("fs/promises"),M2o=require("os"),cy_=li(hre(),1),ly_=li(uy_(),1);var nsE="etag",Yic="preview",Xic="app-preview",asE="bundle",osE=".next",Zic=".fern";function usE({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic))}function N3i({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic),Xa.of(e?osE:asE))}function ssE({app:e=!1}){return Lu(Hl.of((0,M2o.homedir)()),Xa.of(Zic),Xa.of(e?Xic:Yic),Xa.of(nsE))}async function A2o({bucketUrl:e,logger:t,preferCached:r,app:i=!1}){t.debug("Setting up docs preview bundle...");let n=await(0,Kic.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let a=n.body,l=await new ly_.default.Parser().parseStringPromise(a),f=l?.ListBucketResult?.Contents?.[0]?.ETag?.[0],s=l?.ListBucketResult?.Contents?.[0]?.Key?.[0],o=ssE({app:i});if(r){let D=await Cf(o),C;if(D&&(t.debug("Reading existing ETag"),C=(await(0,YZt.readFile)(o)).toString()),C!=null&&C===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up docs preview bundle...
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 cy_.default.dir({prefix:"fern"}),b=Hl.of(c.path),g=new URL(s,e).href;t.debug(`Downloading docs preview bundle from ${g}`);let O=await(0,Kic.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=Lu(b,Xa.of("output.zip")),P=O.body;if(P==null)return{type:"failure"};let E=Buffer.from(P);await(0,YZt.writeFile)(m,new Uint8Array(E)),t.debug(`Wrote output.zip to ${m}`);let q=usE({app:i});await Cf(q)&&await(0,YZt.rm)(q,{recursive:!0}),await(0,YZt.mkdir)(q,{recursive:!0}),t.debug(`rm -rf ${q}`);let A=N3i({app:i});if(await(0,YZt.mkdir)(A,{recursive:!0}),await(0,sy_.default)(m,A),await(0,YZt.writeFile)(o,f),t.debug(`Downloaded bundle to ${A}`),i){t.debug("Checking if pnpm is installed");try{await TF(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:A,doNotPipeOutput:!0})}catch{t.debug("pnpm not found, installing pnpm"),await TF(t,"npm",["install","-g","pnpm"],{doNotPipeOutput:!0})}t.debug("Installing esbuild"),await TF(t,"pnpm",["i","esbuild"],{cwd:A,doNotPipeOutput:!0}),t.debug("Resolve esbuild imports"),await TF(t,"node",["install-esbuild.js"],{cwd:A,doNotPipeOutput:!0})}return{type:"success"}}var wy_=require("fs/promises");var rnc=li(oXt(),1),vy_=require("path");var yAn=li(LSe(),1);function q2o(e){if(e==null)return;let t=[],r=!1;if(AZt(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 kic(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return q2o(e.data?.estree)}function fy_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function dy_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function enc(e){return e.type==="mdxJsxAttribute"}function py_(e){return e.type==="mdxJsxExpressionAttribute"}var _y_=li(oXt(),1);function hy_(e){let{content:t}=(0,_y_.default)(e);return Uba(t,{extensions:[ZPn(),WPn(),Wba()],mdastExtensions:[Lzi(),Izi(),Vba()]})}function yy_(e,t){AZt(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 by_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||gy_(e)||Oy_(e)?void 0:Vg(e.startsWith("/")?t:Zd(r),Xa.of(e.replace(/^\//,"")))}function gy_(e){return/^(https?:)?\/\//.test(e)}function Oy_(e){return e.startsWith("data:")}function my_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=by_(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 inc(e,t,r,i,n){let{content:a,data:u}=(0,rnc.default)(e,{}),l=a,f=hy_(a),s=0;function o(c){if(c==null||gy_(c)||Oy_(c))return;if((0,vy_.isAbsolute)(c)){let g=Hl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=by_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return lsE(u,["image","og:image","og:logo","twitter:image"],o),dsE(u,o),xf(f,c=>{if(c.position==null)return;let{start:b,length:g}=csE(a,c.position),O=l.slice(b+s,b+s+g),m=O;function P(A){let D=o(A);A&&D&&(m=m.replace(A,D))}function E(A){let D=my_({href:A,markdownFilesToPathName:r,metadata:i});A!=null&&D!=null&&D.type==="replace"&&(m=m.replace(A,D.slug))}function q(A){yy_(A,{src:D=>P(ihi(q2o(D.value))),href:D=>E(ihi(q2o(D.value)))})}if(c.type==="image"){let A=ihi(c.url);P(ihi(A))}if(c.type==="link"&&E(ihi(c.url)),fy_(c)){let A=c.attributes.filter(enc).find(C=>C.name==="src");P(ihi(kic(A?.value)));let D=c.attributes.find(C=>C.type==="mdxJsxAttribute"&&C.name==="href");E(ihi(kic(D?.value))),c.attributes.forEach(C=>{enc(C)&&typeof C.value!="string"&&C.value!=null&&C.value.data?.estree?q(C.value.data.estree):py_(C)&&C.data?.estree&&q(C.data.estree)})}if(dy_(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}),rnc.default.stringify(l,u)}function csE(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 ihi(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function lsE(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:yAn.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:yAn.FernRegistry.FileId(a)}:{type:"url",value:yAn.FernRegistry.Url(n)}}}}}var fsE=pu.union([pu.string(),pu.object({light:pu.string().optional(),dark:pu.string().optional()})]);function tnc(e,t){let r=t(e);return r?{type:"fileId",value:yAn.FernRegistry.FileId(r)}:{type:"url",value:yAn.FernRegistry.Url(e)}}function dsE(e,t){let r=fsE.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=tnc(i,t):(i.light!=null&&(e.logo.light=tnc(i.light,t)),i.dark!=null&&(e.logo.dark=tnc(i.dark,t)))}var Py_=require("fs/promises"),jy_=li(oXt(),1);async function psE(e){let{content:t}=(0,jy_.default)(await(0,Py_.readFile)(e));return t}async function nnc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=psE}){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 f=l[0],s=l[1],o=l[2];if(f==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=Vg(o.startsWith("/")?t:Zd(r),Xa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
2015
2015
  `).map(g=>s+g).join(`