fern-api 0.53.3 → 0.53.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1684,7 +1684,7 @@ ${c.indent}`:""}${fjf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1684
1684
  `}),r.replaceAll(/\n$/g,"")}function K31(e){return e?Su.green(n3.radioOn):n3.radioOff}var tno=mi(_we(),1);function gId(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var EGn=class extends n2{_run(t){this.done=t;let r=TL(this.rl),i=r.line.pipe((0,tno.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,tno.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=`
1685
1685
  `+Su.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Su.cyan(gId(t,this.opt.mask)):Su.italic.dim("[hidden]"):this.opt.mask?gId(t,this.opt.mask):Su.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 Hzd=mi(Qds(),1),$zd=mi(_we(),1);var RGn=class extends n2{_run(t){this.done=t,this.editorResult=new $zd.Subject;let r=TL(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"?Su.dim("Received"):Su.dim("Press <enter> to launch your preferred editor."),t&&(r=Su.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,Hzd.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 kzd=mi(Jzd(),1);var Xzd=mi(require("readline"),1),Zzd=mi(Yzd(),1),Zji=class{constructor(t){this.rl||=Xzd.default.createInterface(F71(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 F71(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 Zzd.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var NGn=class extends Zji{constructor(t={}){super(t),this.log=(0,kzd.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return gGn(this.rl,this.bottomBar.split(`
1686
1686
  `).length),this}updateBottomBar(t){return gGn(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+`
1687
- `}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&&Xio(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var cRd=mi(rRd(),1),lRd=mi(tfs(),1),fRd=mi(uRd(),1),aM=mi(_we(),1),dRd=mi(A$n(),1);var mno=mi(_we(),1),sRd=mi(A$n(),1),Pno=function(e,t,r){return typeof e[t]!="function"?(0,mno.of)(e):(0,mno.from)((0,sRd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var FGn={isPlainObject:cRd.default,set:fRd.default,get:lRd.default},Iun=class extends Zji{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=FGn.isPlainObject(r)?{...r}:{},FGn.isPlainObject(t)&&(t=Object.values(t).every(n=>FGn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,aM.from)(t):t;return this.process=i.pipe((0,aM.concatMap)(this.processQuestion.bind(this)),(0,aM.publish)()),this.process.connect(),this.process.pipe((0,aM.reduce)((n,a)=>(FGn.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,aM.defer)(()=>(0,aM.of)(t).pipe((0,aM.concatMap)(this.setDefaultType.bind(this)),(0,aM.concatMap)(this.filterIfRunnable.bind(this)),(0,aM.concatMap)(()=>Pno(t,"message",this.answers)),(0,aM.concatMap)(()=>Pno(t,"default",this.answers)),(0,aM.concatMap)(()=>Pno(t,"choices",this.answers)),(0,aM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,aM.defer)(()=>(0,aM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,aM.defer)(()=>(0,aM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&FGn.get(this.answers,t.name)!==void 0)return(0,aM.empty)();if(t.when===!1)return(0,aM.empty)();if(typeof t.when!="function")return(0,aM.of)(t);let{answers:r}=this;return(0,aM.defer)(()=>(0,aM.from)((0,dRd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,aM.filter)(i=>i!=null)))}};function pRd(e){let t=function(r,i){let n;try{n=new Iun(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",mGn),this.registerPrompt("input",Hji),this.registerPrompt("number",PGn),this.registerPrompt("confirm",jGn),this.registerPrompt("rawlist",wGn),this.registerPrompt("expand",SGn),this.registerPrompt("checkbox",DGn),this.registerPrompt("password",EGn),this.registerPrompt("editor",RGn)},t.restoreDefaultPrompts(),t}var Yds=pRd();function i21(e,t){Yds.registerPrompt(e,t)}function n21(){Yds.restoreDefaultPrompts()}var a21={prompt:Yds,ui:{BottomBar:NGn,Prompt:Iun},createPromptModule:pRd,registerPrompt:i21,restoreDefaultPrompts:n21,Separator:bte},jno=a21;var jNd=mi(_Rd()),M41="4.2.1",o2t;(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"})(o2t||(o2t={}));function q41(e,t){if(!e)throw new Error(t)}function T41(e){return e?.replace(/\/+$/,"")}async function C41(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 B41(){return new Date().getTime()}function hNd(){return new Date().toISOString()}function wNd(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var XGn=String.fromCharCode,yNd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",zno={};function x41(e,t){if(!zno[e]){zno[e]={};for(let r=0;r<e.length;r++)zno[e][e.charAt(r)]=r}return zno[e][t]}var ZGn={compressToBase64:function(e){if(e==null)return"";let t=ZGn._compress(e,6,function(r){return yNd.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:ZGn._decompress(e.length,32,function(t){return x41(yNd,e.charAt(t))})},compress:function(e){return ZGn._compress(e,16,function(t){return XGn(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,w;for(w=0;w<e.length;w+=1)if(f=e.charAt(w),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:ZGn._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,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=XGn(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=XGn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,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(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=XGn(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=XGn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},zps=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 Rno="0123456789abcdef",Nno=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+=Rno.charAt(this.bytes[r]>>>4),t+=Rno.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+=Rno.charAt(this.bytes[r]>>>4),t+=Rno.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}},Rps=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??I41()}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 Nno.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,Nno.ofInner(t)}},I41=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),vNd,bNd=()=>z41().toString(),z41=()=>(vNd||(vNd=new Rps)).generate(),Fno=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},kGn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function gNd(e){return typeof e=="object"&&(e instanceof Fno||e instanceof kGn)}var Nps=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new zps,this._isInitialized=!1,q41(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=T41(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:gNd},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(o2t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(o2t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(o2t.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=bNd();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:hNd(),uuid:i?.uuid?i.uuid:bNd()};(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(o2t.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(o2t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=wNd(()=>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(o2t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(o2t.Queue)||[];this.setPersistedProperty(o2t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:hNd()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${B41()}&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(ZGn.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 kGn||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 C41(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new kGn(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Fno(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(o2t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!gNd(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Fps=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Lps=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Lps){let e=_Nd();Lps=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 SNd=Lps,R41=1152921504606847e3,N41=["is_not"],Lno=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},a2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ups=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||SNd,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 a2?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 a2||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 a2("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 a2("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 a2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new a2("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=ENd(l,n,this.cohorts,this.debugMode):s=DNd(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&ONd(t.key,r)>a/100)}getMatchingVariant(t,r){let i=ONd(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 Lno("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 Lno&&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=wNd(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function ONd(e,t,r=""){let i=(0,jNd.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/R41}function DNd(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 a2("Operator is_not_set is not supported")}else throw new a2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!N41.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 mNd(String(n))&&String(u).match(String(n))!==null;case"not_regex":return mNd(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=F41(String(n));if(s==null&&(s=PNd(n)),s==null)throw new a2(`Invalid date: ${n}`);let o=PNd(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new a2(`Unknown operator: ${a}`)}}function ENd(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new a2("can't match cohort without a given cohort property value");let a=r[n];return ANd(a,t,r,i)}function ANd(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=ANd(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof a2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new a2("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=ENd(l,t,r,i):f=DNd(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 a2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new a2("can't match cohort without a given cohort property value");return n==="AND"}}function mNd(e){try{return new RegExp(e),!0}catch{return!1}}function PNd(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 a2(`${e} is in an invalid date format`)}else throw new a2(`The date provided ${e} must be a string, number, or date object`)}function F41(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 L41=30*1e3,U41=50*1e3,Vun=class extends Nps{constructor(t,r={}){super(t,r),this._memoryStorage=new Fps,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ups({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:L41,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||U41}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):SNd(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return M41}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,w]of Object.entries(b))g[`$feature/${m}`]=w;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties: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}}},Vps=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})}};Vps.POSTHOG_ID_TAG="posthog_distinct_id";var Uno=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vun(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.53.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var eQn=class{async sendEvent(){}async identify(){}async flush(){}};var Wun=require("fs/promises"),CNd=require("os"),BNd=require("path");var MNd=mi(require("crypto")),Wno=new Uint8Array(256),Vno=Wno.length;function Wps(){return Vno>Wno.length-16&&(MNd.default.randomFillSync(Wno),Vno=0),Wno.slice(Vno,Vno+=16)}var xL=[];for(let e=0;e<256;++e)xL.push((e+256).toString(16).slice(1));function qNd(e,t=0){return xL[e[t+0]]+xL[e[t+1]]+xL[e[t+2]]+xL[e[t+3]]+"-"+xL[e[t+4]]+xL[e[t+5]]+"-"+xL[e[t+6]]+xL[e[t+7]]+"-"+xL[e[t+8]]+xL[e[t+9]]+"-"+xL[e[t+10]]+xL[e[t+11]]+xL[e[t+12]]+xL[e[t+13]]+xL[e[t+14]]+xL[e[t+15]]}var TNd=mi(require("crypto")),Hps={randomUUID:TNd.default.randomUUID};function V41(e,t,r){if(Hps.randomUUID&&!t&&!e)return Hps.randomUUID();e=e||{};let i=e.random||(e.rng||Wps)();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 qNd(i)}var tBe=V41;var W41="id",H41=".fern",tQn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Vun(r),this.userId=t==null?void 0:sos(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.53.3",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=ku(Ul.of((0,CNd.homedir)()),po.of(H41),po.of(W41));await Nf(t)||(await(0,Wun.mkdir)((0,BNd.dirname)(t),{recursive:!0}),await(0,Wun.writeFile)(t,tBe())),this.persistedDistinctId=(await(0,Wun.readFile)(t)).toString()}return this.persistedDistinctId}};var $ps;async function Hun(){return $ps==null&&($ps=await $41()),$ps}async function $41(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new eQn;let r=await eZa();return r!=null?new tQn({token:r,posthogApiKey:e}):await kXa()!=null?new Uno({posthogApiKey:e}):new tQn({token:void 0,posthogApiKey:e})}catch{return new eQn}}function rQn(e,t){return function(){return e.apply(t,arguments)}}var{toString:G41}=Object.prototype,{getPrototypeOf:Jps}=Object,$no=(e=>t=>{let r=G41.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),u2t=e=>(e=e.toLowerCase(),t=>$no(t)===e),Gno=e=>t=>typeof t===e,{isArray:$un}=Array,iQn=Gno("undefined");function Q41(e){return e!==null&&!iQn(e)&&e.constructor!==null&&!iQn(e.constructor)&&ywe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var zNd=u2t("ArrayBuffer");function J41(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&zNd(e.buffer),t}var K41=Gno("string"),ywe=Gno("function"),RNd=Gno("number"),Qno=e=>e!==null&&typeof e=="object",Y41=e=>e===!0||e===!1,Hno=e=>{if($no(e)!=="object")return!1;let t=Jps(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},X41=u2t("Date"),Z41=u2t("File"),k41=u2t("Blob"),e81=u2t("FileList"),t81=e=>Qno(e)&&ywe(e.pipe),r81=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ywe(e.append)&&((t=$no(e))==="formdata"||t==="object"&&ywe(e.toString)&&e.toString()==="[object FormData]"))},i81=u2t("URLSearchParams"),[n81,a81,o81,u81]=["ReadableStream","Request","Response","Headers"].map(u2t),s81=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function nQn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),$un(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 NNd(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 rwi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,FNd=e=>!iQn(e)&&e!==rwi;function Qps(){let{caseless:e}=FNd(this)&&this||{},t={},r=(i,n)=>{let a=e&&NNd(t,n)||n;Hno(t[a])&&Hno(i)?t[a]=Qps(t[a],i):Hno(i)?t[a]=Qps({},i):$un(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&nQn(arguments[i],r);return t}var c81=(e,t,r,{allOwnKeys:i}={})=>(nQn(t,(n,a)=>{r&&ywe(n)?e[a]=rQn(n,r):e[a]=n},{allOwnKeys:i}),e),l81=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),f81=(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)},d81=(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&&Jps(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},p81=(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},_81=e=>{if(!e)return null;if($un(e))return e;let t=e.length;if(!RNd(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},h81=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Jps(Uint8Array)),y81=(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])}},v81=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},b81=u2t("HTMLFormElement"),g81=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),xNd=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),O81=u2t("RegExp"),LNd=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};nQn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},m81=e=>{LNd(e,(t,r)=>{if(ywe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(ywe(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+"'")})}})},P81=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return $un(e)?i(e):i(String(e).split(t)),r},j81=()=>{},w81=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,Gps="abcdefghijklmnopqrstuvwxyz",INd="0123456789",UNd={DIGIT:INd,ALPHA:Gps,ALPHA_DIGIT:Gps+Gps.toUpperCase()+INd},S81=(e=16,t=UNd.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function D81(e){return!!(e&&ywe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var E81=e=>{let t=new Array(10),r=(i,n)=>{if(Qno(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=$un(i)?[]:{};return nQn(i,(u,l)=>{let f=r(u,n+1);!iQn(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},A81=u2t("AsyncFunction"),M81=e=>e&&(Qno(e)||ywe(e))&&ywe(e.then)&&ywe(e.catch),VNd=((e,t)=>e?setImmediate:t?((r,i)=>(rwi.addEventListener("message",({source:n,data:a})=>{n===rwi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),rwi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ywe(rwi.postMessage)),q81=typeof queueMicrotask<"u"?queueMicrotask.bind(rwi):typeof process<"u"&&process.nextTick||VNd,os={isArray:$un,isArrayBuffer:zNd,isBuffer:Q41,isFormData:r81,isArrayBufferView:J41,isString:K41,isNumber:RNd,isBoolean:Y41,isObject:Qno,isPlainObject:Hno,isReadableStream:n81,isRequest:a81,isResponse:o81,isHeaders:u81,isUndefined:iQn,isDate:X41,isFile:Z41,isBlob:k41,isRegExp:O81,isFunction:ywe,isStream:t81,isURLSearchParams:i81,isTypedArray:h81,isFileList:e81,forEach:nQn,merge:Qps,extend:c81,trim:s81,stripBOM:l81,inherits:f81,toFlatObject:d81,kindOf:$no,kindOfTest:u2t,endsWith:p81,toArray:_81,forEachEntry:y81,matchAll:v81,isHTMLForm:b81,hasOwnProperty:xNd,hasOwnProp:xNd,reduceDescriptors:LNd,freezeMethods:m81,toObjectSet:P81,toCamelCase:g81,noop:j81,toFiniteNumber:w81,findKey:NNd,global:rwi,isContextDefined:FNd,ALPHABET:UNd,generateString:S81,isSpecCompliantForm:D81,toJSONObject:E81,isAsyncFn:A81,isThenable:M81,setImmediate:VNd,asap:q81};function Gun(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)}os.inherits(Gun,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var WNd=Gun.prototype,HNd={};["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=>{HNd[e]={value:e}});Object.defineProperties(Gun,HNd);Object.defineProperty(WNd,"isAxiosError",{value:!0});Gun.from=(e,t,r,i,n,a)=>{let u=Object.create(WNd);return os.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),Gun.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Gun;var $Nd=mi(HLn(),1),Jno=$Nd.default;function Kps(e){return os.isPlainObject(e)||os.isArray(e)}function QNd(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function GNd(e,t,r){return e?e.concat(t).map(function(n,a){return n=QNd(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function T81(e){return os.isArray(e)&&!e.some(Kps)}var C81=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function B81(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(Jno||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(!f&&os.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let A=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&T81(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(A=os.toArray(O)))return m=QNd(m),A.forEach(function(q,D){!(os.isUndefined(q)||q===null)&&t.append(u===!0?GNd([m],D,a):u===null?m:m+"[]",s(q))}),!1}return Kps(O)?!0:(t.append(GNd(w,m,a),s(O)),!1)}let c=[],b=Object.assign(C81,{defaultVisitor:o,convertValue:s,isVisitable:Kps});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(A,M){(!(os.isUndefined(A)||A===null)&&n.call(t,A,os.isString(M)?M.trim():M,m,b))===!0&&g(A,m?m.concat(M):[M])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ckr=B81;function JNd(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function KNd(e,t){this._pairs=[],e&&ckr(e,this,t)}var YNd=KNd.prototype;YNd.append=function(t,r){this._pairs.push([t,r])};YNd.toString=function(t){let r=t?function(i){return t.call(this,i,JNd)}:JNd;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var XNd=KNd;function x81(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function iwi(e,t,r){if(!t)return e;let i=r&&r.encode||x81,n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new XNd(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Yps=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},Xps=Yps;var Qun={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var ZNd=mi(require("url"),1),kNd=ZNd.default.URLSearchParams;var eFd={isNode:!0,classes:{URLSearchParams:kNd,FormData:Jno,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var e_s={};Ro(e_s,{hasBrowserEnv:()=>kps,hasStandardBrowserEnv:()=>I81,hasStandardBrowserWebWorkerEnv:()=>z81,navigator:()=>Zps,origin:()=>R81});var kps=typeof window<"u"&&typeof document<"u",Zps=typeof navigator=="object"&&navigator||void 0,I81=kps&&(!Zps||["ReactNative","NativeScript","NS"].indexOf(Zps.product)<0),z81=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",R81=kps&&window.location.href||"http://localhost";var sT={...e_s,...eFd};function t_s(e,t){return ckr(e,new sT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return sT.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function N81(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function F81(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 L81(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&&os.isArray(n)?n.length:u,f?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=F81(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(N81(i),n,r,0)}),r}return null}var Kno=L81;function U81(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var r_s={transitional:Qun,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(Kno(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.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 t_s(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return ckr(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),U81(t)):t}],transformResponse:[function(t){let r=this.transitional||r_s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?yp.from(l,yp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:sT.classes.FormData,Blob:sT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{r_s.headers[e]={}});var Jun=r_s;var V81=os.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"]),tFd=e=>{let t={},r,i,n;return e&&e.split(`
1687
+ `}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&&Xio(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var cRd=mi(rRd(),1),lRd=mi(tfs(),1),fRd=mi(uRd(),1),aM=mi(_we(),1),dRd=mi(A$n(),1);var mno=mi(_we(),1),sRd=mi(A$n(),1),Pno=function(e,t,r){return typeof e[t]!="function"?(0,mno.of)(e):(0,mno.from)((0,sRd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var FGn={isPlainObject:cRd.default,set:fRd.default,get:lRd.default},Iun=class extends Zji{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=FGn.isPlainObject(r)?{...r}:{},FGn.isPlainObject(t)&&(t=Object.values(t).every(n=>FGn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,aM.from)(t):t;return this.process=i.pipe((0,aM.concatMap)(this.processQuestion.bind(this)),(0,aM.publish)()),this.process.connect(),this.process.pipe((0,aM.reduce)((n,a)=>(FGn.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,aM.defer)(()=>(0,aM.of)(t).pipe((0,aM.concatMap)(this.setDefaultType.bind(this)),(0,aM.concatMap)(this.filterIfRunnable.bind(this)),(0,aM.concatMap)(()=>Pno(t,"message",this.answers)),(0,aM.concatMap)(()=>Pno(t,"default",this.answers)),(0,aM.concatMap)(()=>Pno(t,"choices",this.answers)),(0,aM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,aM.defer)(()=>(0,aM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,aM.defer)(()=>(0,aM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&FGn.get(this.answers,t.name)!==void 0)return(0,aM.empty)();if(t.when===!1)return(0,aM.empty)();if(typeof t.when!="function")return(0,aM.of)(t);let{answers:r}=this;return(0,aM.defer)(()=>(0,aM.from)((0,dRd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,aM.filter)(i=>i!=null)))}};function pRd(e){let t=function(r,i){let n;try{n=new Iun(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",mGn),this.registerPrompt("input",Hji),this.registerPrompt("number",PGn),this.registerPrompt("confirm",jGn),this.registerPrompt("rawlist",wGn),this.registerPrompt("expand",SGn),this.registerPrompt("checkbox",DGn),this.registerPrompt("password",EGn),this.registerPrompt("editor",RGn)},t.restoreDefaultPrompts(),t}var Yds=pRd();function i21(e,t){Yds.registerPrompt(e,t)}function n21(){Yds.restoreDefaultPrompts()}var a21={prompt:Yds,ui:{BottomBar:NGn,Prompt:Iun},createPromptModule:pRd,registerPrompt:i21,restoreDefaultPrompts:n21,Separator:bte},jno=a21;var jNd=mi(_Rd()),M41="4.2.1",o2t;(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"})(o2t||(o2t={}));function q41(e,t){if(!e)throw new Error(t)}function T41(e){return e?.replace(/\/+$/,"")}async function C41(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 B41(){return new Date().getTime()}function hNd(){return new Date().toISOString()}function wNd(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var XGn=String.fromCharCode,yNd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",zno={};function x41(e,t){if(!zno[e]){zno[e]={};for(let r=0;r<e.length;r++)zno[e][e.charAt(r)]=r}return zno[e][t]}var ZGn={compressToBase64:function(e){if(e==null)return"";let t=ZGn._compress(e,6,function(r){return yNd.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:ZGn._decompress(e.length,32,function(t){return x41(yNd,e.charAt(t))})},compress:function(e){return ZGn._compress(e,16,function(t){return XGn(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,w;for(w=0;w<e.length;w+=1)if(f=e.charAt(w),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:ZGn._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,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=XGn(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=XGn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,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(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=XGn(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=XGn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},zps=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 Rno="0123456789abcdef",Nno=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+=Rno.charAt(this.bytes[r]>>>4),t+=Rno.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+=Rno.charAt(this.bytes[r]>>>4),t+=Rno.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}},Rps=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??I41()}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 Nno.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,Nno.ofInner(t)}},I41=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),vNd,bNd=()=>z41().toString(),z41=()=>(vNd||(vNd=new Rps)).generate(),Fno=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},kGn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function gNd(e){return typeof e=="object"&&(e instanceof Fno||e instanceof kGn)}var Nps=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new zps,this._isInitialized=!1,q41(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=T41(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:gNd},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(o2t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(o2t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(o2t.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=bNd();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:hNd(),uuid:i?.uuid?i.uuid:bNd()};(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(o2t.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(o2t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=wNd(()=>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(o2t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(o2t.Queue)||[];this.setPersistedProperty(o2t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:hNd()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${B41()}&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(ZGn.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 kGn||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 C41(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new kGn(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Fno(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(o2t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!gNd(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Fps=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Lps=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Lps){let e=_Nd();Lps=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 SNd=Lps,R41=1152921504606847e3,N41=["is_not"],Lno=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},a2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ups=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||SNd,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 a2?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 a2||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 a2("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 a2("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 a2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new a2("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=ENd(l,n,this.cohorts,this.debugMode):s=DNd(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&ONd(t.key,r)>a/100)}getMatchingVariant(t,r){let i=ONd(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 Lno("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 Lno&&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=wNd(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function ONd(e,t,r=""){let i=(0,jNd.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/R41}function DNd(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 a2("Operator is_not_set is not supported")}else throw new a2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!N41.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 mNd(String(n))&&String(u).match(String(n))!==null;case"not_regex":return mNd(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=F41(String(n));if(s==null&&(s=PNd(n)),s==null)throw new a2(`Invalid date: ${n}`);let o=PNd(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new a2(`Unknown operator: ${a}`)}}function ENd(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new a2("can't match cohort without a given cohort property value");let a=r[n];return ANd(a,t,r,i)}function ANd(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=ANd(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof a2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new a2("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=ENd(l,t,r,i):f=DNd(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 a2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new a2("can't match cohort without a given cohort property value");return n==="AND"}}function mNd(e){try{return new RegExp(e),!0}catch{return!1}}function PNd(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 a2(`${e} is in an invalid date format`)}else throw new a2(`The date provided ${e} must be a string, number, or date object`)}function F41(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 L41=30*1e3,U41=50*1e3,Vun=class extends Nps{constructor(t,r={}){super(t,r),this._memoryStorage=new Fps,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ups({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:L41,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||U41}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):SNd(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return M41}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,w]of Object.entries(b))g[`$feature/${m}`]=w;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties: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}}},Vps=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})}};Vps.POSTHOG_ID_TAG="posthog_distinct_id";var Uno=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vun(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.53.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var eQn=class{async sendEvent(){}async identify(){}async flush(){}};var Wun=require("fs/promises"),CNd=require("os"),BNd=require("path");var MNd=mi(require("crypto")),Wno=new Uint8Array(256),Vno=Wno.length;function Wps(){return Vno>Wno.length-16&&(MNd.default.randomFillSync(Wno),Vno=0),Wno.slice(Vno,Vno+=16)}var xL=[];for(let e=0;e<256;++e)xL.push((e+256).toString(16).slice(1));function qNd(e,t=0){return xL[e[t+0]]+xL[e[t+1]]+xL[e[t+2]]+xL[e[t+3]]+"-"+xL[e[t+4]]+xL[e[t+5]]+"-"+xL[e[t+6]]+xL[e[t+7]]+"-"+xL[e[t+8]]+xL[e[t+9]]+"-"+xL[e[t+10]]+xL[e[t+11]]+xL[e[t+12]]+xL[e[t+13]]+xL[e[t+14]]+xL[e[t+15]]}var TNd=mi(require("crypto")),Hps={randomUUID:TNd.default.randomUUID};function V41(e,t,r){if(Hps.randomUUID&&!t&&!e)return Hps.randomUUID();e=e||{};let i=e.random||(e.rng||Wps)();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 qNd(i)}var tBe=V41;var W41="id",H41=".fern",tQn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Vun(r),this.userId=t==null?void 0:sos(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.53.4",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=ku(Ul.of((0,CNd.homedir)()),po.of(H41),po.of(W41));await Nf(t)||(await(0,Wun.mkdir)((0,BNd.dirname)(t),{recursive:!0}),await(0,Wun.writeFile)(t,tBe())),this.persistedDistinctId=(await(0,Wun.readFile)(t)).toString()}return this.persistedDistinctId}};var $ps;async function Hun(){return $ps==null&&($ps=await $41()),$ps}async function $41(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new eQn;let r=await eZa();return r!=null?new tQn({token:r,posthogApiKey:e}):await kXa()!=null?new Uno({posthogApiKey:e}):new tQn({token:void 0,posthogApiKey:e})}catch{return new eQn}}function rQn(e,t){return function(){return e.apply(t,arguments)}}var{toString:G41}=Object.prototype,{getPrototypeOf:Jps}=Object,$no=(e=>t=>{let r=G41.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),u2t=e=>(e=e.toLowerCase(),t=>$no(t)===e),Gno=e=>t=>typeof t===e,{isArray:$un}=Array,iQn=Gno("undefined");function Q41(e){return e!==null&&!iQn(e)&&e.constructor!==null&&!iQn(e.constructor)&&ywe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var zNd=u2t("ArrayBuffer");function J41(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&zNd(e.buffer),t}var K41=Gno("string"),ywe=Gno("function"),RNd=Gno("number"),Qno=e=>e!==null&&typeof e=="object",Y41=e=>e===!0||e===!1,Hno=e=>{if($no(e)!=="object")return!1;let t=Jps(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},X41=u2t("Date"),Z41=u2t("File"),k41=u2t("Blob"),e81=u2t("FileList"),t81=e=>Qno(e)&&ywe(e.pipe),r81=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ywe(e.append)&&((t=$no(e))==="formdata"||t==="object"&&ywe(e.toString)&&e.toString()==="[object FormData]"))},i81=u2t("URLSearchParams"),[n81,a81,o81,u81]=["ReadableStream","Request","Response","Headers"].map(u2t),s81=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function nQn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),$un(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 NNd(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 rwi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,FNd=e=>!iQn(e)&&e!==rwi;function Qps(){let{caseless:e}=FNd(this)&&this||{},t={},r=(i,n)=>{let a=e&&NNd(t,n)||n;Hno(t[a])&&Hno(i)?t[a]=Qps(t[a],i):Hno(i)?t[a]=Qps({},i):$un(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&nQn(arguments[i],r);return t}var c81=(e,t,r,{allOwnKeys:i}={})=>(nQn(t,(n,a)=>{r&&ywe(n)?e[a]=rQn(n,r):e[a]=n},{allOwnKeys:i}),e),l81=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),f81=(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)},d81=(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&&Jps(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},p81=(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},_81=e=>{if(!e)return null;if($un(e))return e;let t=e.length;if(!RNd(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},h81=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Jps(Uint8Array)),y81=(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])}},v81=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},b81=u2t("HTMLFormElement"),g81=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),xNd=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),O81=u2t("RegExp"),LNd=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};nQn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},m81=e=>{LNd(e,(t,r)=>{if(ywe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(ywe(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+"'")})}})},P81=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return $un(e)?i(e):i(String(e).split(t)),r},j81=()=>{},w81=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,Gps="abcdefghijklmnopqrstuvwxyz",INd="0123456789",UNd={DIGIT:INd,ALPHA:Gps,ALPHA_DIGIT:Gps+Gps.toUpperCase()+INd},S81=(e=16,t=UNd.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function D81(e){return!!(e&&ywe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var E81=e=>{let t=new Array(10),r=(i,n)=>{if(Qno(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=$un(i)?[]:{};return nQn(i,(u,l)=>{let f=r(u,n+1);!iQn(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},A81=u2t("AsyncFunction"),M81=e=>e&&(Qno(e)||ywe(e))&&ywe(e.then)&&ywe(e.catch),VNd=((e,t)=>e?setImmediate:t?((r,i)=>(rwi.addEventListener("message",({source:n,data:a})=>{n===rwi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),rwi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ywe(rwi.postMessage)),q81=typeof queueMicrotask<"u"?queueMicrotask.bind(rwi):typeof process<"u"&&process.nextTick||VNd,os={isArray:$un,isArrayBuffer:zNd,isBuffer:Q41,isFormData:r81,isArrayBufferView:J41,isString:K41,isNumber:RNd,isBoolean:Y41,isObject:Qno,isPlainObject:Hno,isReadableStream:n81,isRequest:a81,isResponse:o81,isHeaders:u81,isUndefined:iQn,isDate:X41,isFile:Z41,isBlob:k41,isRegExp:O81,isFunction:ywe,isStream:t81,isURLSearchParams:i81,isTypedArray:h81,isFileList:e81,forEach:nQn,merge:Qps,extend:c81,trim:s81,stripBOM:l81,inherits:f81,toFlatObject:d81,kindOf:$no,kindOfTest:u2t,endsWith:p81,toArray:_81,forEachEntry:y81,matchAll:v81,isHTMLForm:b81,hasOwnProperty:xNd,hasOwnProp:xNd,reduceDescriptors:LNd,freezeMethods:m81,toObjectSet:P81,toCamelCase:g81,noop:j81,toFiniteNumber:w81,findKey:NNd,global:rwi,isContextDefined:FNd,ALPHABET:UNd,generateString:S81,isSpecCompliantForm:D81,toJSONObject:E81,isAsyncFn:A81,isThenable:M81,setImmediate:VNd,asap:q81};function Gun(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)}os.inherits(Gun,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var WNd=Gun.prototype,HNd={};["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=>{HNd[e]={value:e}});Object.defineProperties(Gun,HNd);Object.defineProperty(WNd,"isAxiosError",{value:!0});Gun.from=(e,t,r,i,n,a)=>{let u=Object.create(WNd);return os.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),Gun.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Gun;var $Nd=mi(HLn(),1),Jno=$Nd.default;function Kps(e){return os.isPlainObject(e)||os.isArray(e)}function QNd(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function GNd(e,t,r){return e?e.concat(t).map(function(n,a){return n=QNd(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function T81(e){return os.isArray(e)&&!e.some(Kps)}var C81=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function B81(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(Jno||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(!f&&os.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let A=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&T81(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(A=os.toArray(O)))return m=QNd(m),A.forEach(function(q,D){!(os.isUndefined(q)||q===null)&&t.append(u===!0?GNd([m],D,a):u===null?m:m+"[]",s(q))}),!1}return Kps(O)?!0:(t.append(GNd(w,m,a),s(O)),!1)}let c=[],b=Object.assign(C81,{defaultVisitor:o,convertValue:s,isVisitable:Kps});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(A,M){(!(os.isUndefined(A)||A===null)&&n.call(t,A,os.isString(M)?M.trim():M,m,b))===!0&&g(A,m?m.concat(M):[M])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ckr=B81;function JNd(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function KNd(e,t){this._pairs=[],e&&ckr(e,this,t)}var YNd=KNd.prototype;YNd.append=function(t,r){this._pairs.push([t,r])};YNd.toString=function(t){let r=t?function(i){return t.call(this,i,JNd)}:JNd;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var XNd=KNd;function x81(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function iwi(e,t,r){if(!t)return e;let i=r&&r.encode||x81,n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new XNd(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Yps=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},Xps=Yps;var Qun={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var ZNd=mi(require("url"),1),kNd=ZNd.default.URLSearchParams;var eFd={isNode:!0,classes:{URLSearchParams:kNd,FormData:Jno,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var e_s={};Ro(e_s,{hasBrowserEnv:()=>kps,hasStandardBrowserEnv:()=>I81,hasStandardBrowserWebWorkerEnv:()=>z81,navigator:()=>Zps,origin:()=>R81});var kps=typeof window<"u"&&typeof document<"u",Zps=typeof navigator=="object"&&navigator||void 0,I81=kps&&(!Zps||["ReactNative","NativeScript","NS"].indexOf(Zps.product)<0),z81=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",R81=kps&&window.location.href||"http://localhost";var sT={...e_s,...eFd};function t_s(e,t){return ckr(e,new sT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return sT.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function N81(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function F81(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 L81(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&&os.isArray(n)?n.length:u,f?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=F81(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(N81(i),n,r,0)}),r}return null}var Kno=L81;function U81(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var r_s={transitional:Qun,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(Kno(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.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 t_s(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return ckr(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),U81(t)):t}],transformResponse:[function(t){let r=this.transitional||r_s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?yp.from(l,yp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:sT.classes.FormData,Blob:sT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{r_s.headers[e]={}});var Jun=r_s;var V81=os.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"]),tFd=e=>{let t={},r,i,n;return e&&e.split(`
1688
1688
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&V81[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var rFd=Symbol("internals");function aQn(e){return e&&String(e).trim().toLowerCase()}function Yno(e){return e===!1||e==null?e:os.isArray(e)?e.map(Yno):String(e)}function W81(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 H81=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function i_s(e,t,r,i,n){if(os.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!os.isString(t)){if(os.isString(i))return t.indexOf(i)!==-1;if(os.isRegExp(i))return i.test(t)}}function $81(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function G81(e,t){let r=os.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 Kun=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,f,s){let o=aQn(f);if(!o)throw new Error("header name must be a non-empty string");let c=os.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||f]=Yno(l))}let u=(l,f)=>os.forEach(l,(s,o)=>a(s,o,f));if(os.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(os.isString(t)&&(t=t.trim())&&!H81(t))u(tFd(t),r);else if(os.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=aQn(t),t){let i=os.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return W81(n);if(os.isFunction(r))return r.call(this,n,i);if(os.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=aQn(t),t){let i=os.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||i_s(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=aQn(u),u){let l=os.findKey(i,u);l&&(!r||i_s(i,i[l],l,r))&&(delete i[l],n=!0)}}return os.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||i_s(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return os.forEach(this,(n,a)=>{let u=os.findKey(i,a);if(u){r[u]=Yno(n),delete r[a];return}let l=t?$81(a):String(a).trim();l!==a&&delete r[a],r[l]=Yno(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return os.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&os.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(`
1689
1689
  `)}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[rFd]=this[rFd]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=aQn(u);i[l]||(G81(n,u),i[l]=!0)}return os.isArray(t)?t.forEach(a):a(t),this}};Kun.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);os.reduceDescriptors(Kun.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});os.freezeMethods(Kun);var lI=Kun;function oQn(e,t){let r=this||Jun,i=t||r,n=lI.from(i.headers),a=i.data;return os.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function uQn(e){return!!(e&&e.__CANCEL__)}function iFd(e,t,r){yp.call(this,e??"canceled",yp.ERR_CANCELED,t,r),this.name="CanceledError"}os.inherits(iFd,yp,{__CANCEL__:!0});var vwe=iFd;function bGt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new yp("Request failed with status code "+r.status,[yp.ERR_BAD_REQUEST,yp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function n_s(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function a_s(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function nwi(e,t){return e&&!n_s(t)?a_s(e,t):t}var gFd=mi(UGn(),1),OFd=mi(require("http"),1),mFd=mi(require("https"),1),PFd=mi(require("util"),1),jFd=mi(lps(),1),$4r=mi(require("zlib"),1);var awi="1.7.7";function sQn(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var Q81=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function o_s(e,t,r){let i=r&&r.Blob||sT.classes.Blob,n=sQn(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=Q81.exec(e);if(!a)throw new yp("Invalid URL",yp.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 yp("Blob is not supported",yp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new yp("Unsupported protocol "+n,yp.ERR_NOT_SUPPORT)}var owi=mi(require("stream"),1);var nFd=mi(require("stream"),1);var u_s=Symbol("internals"),s_s=class extends nFd.default.Transform{constructor(t){t=os.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!os.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[u_s]={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[u_s];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[u_s],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),w=null,A=u,M,q=0;if(a){let D=Date.now();(!n.ts||(q=D-n.ts)>=l)&&(n.ts=D,M=s-n.bytes,n.bytes=M<0?-M:0,q=0),M=s-n.bytes}if(a){if(M<=0)return setTimeout(()=>{O(null,g)},l-q);M<A&&(A=M)}A&&m>A&&m-A>o&&(w=g.subarray(A),g=g.subarray(0,A)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},c_s=s_s;var wFd=require("events");var oFd=require("util"),uFd=require("stream");var{asyncIterator:aFd}=Symbol,J81=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[aFd]?yield*e[aFd]():yield e},Xno=J81;var K81=os.ALPHABET.ALPHA_DIGIT+"-_",cQn=new oFd.TextEncoder,lkr=`\r
1690
1690
  `,Y81=cQn.encode(lkr),X81=2,l_s=class{constructor(t,r){let{escapeName:i}=this.constructor,n=os.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${lkr}`;n?r=cQn.encode(String(r).replace(/\r?\n|\r\n?/g,lkr)):a+=`Content-Type: ${r.type||"application/octet-stream"}${lkr}`,this.headers=cQn.encode(a+lkr),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+X81,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;os.isTypedArray(t)?yield t:yield*Xno(t),yield Y81}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},Z81=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+os.generateString(n,K81)}=r||{};if(!os.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=cQn.encode("--"+a+lkr),l=cQn.encode("--"+a+"--"+lkr+lkr),f=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new l_s(c,b);return f+=g.size,g});f+=u.byteLength*s.length,f=os.toFiniteNumber(f);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(o["Content-Length"]=f),t&&t(o),uFd.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},sFd=Z81;var cFd=mi(require("stream"),1),f_s=class extends cFd.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)}},lFd=f_s;var k81=(e,t)=>os.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,fFd=k81;function e51(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 dFd=e51;function t51(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 pFd=t51;var H4r=(e,t,r=3)=>{let i=0,n=dFd(50,250);return pFd(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)},Yun=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Xun=e=>(...t)=>os.asap(()=>e(...t));var _Fd={flush:$4r.default.constants.Z_SYNC_FLUSH,finishFlush:$4r.default.constants.Z_SYNC_FLUSH},r51={flush:$4r.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:$4r.default.constants.BROTLI_OPERATION_FLUSH},hFd=os.isFunction($4r.default.createBrotliDecompress),{http:i51,https:n51}=jFd.default,a51=/https:?/,yFd=sT.protocols.map(e=>e+":"),vFd=(e,[t,r])=>(e.on("end",r).on("error",r),t);function o51(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function SFd(e,t,r){let i=t;if(!i&&i!==!1){let n=(0,gFd.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){SFd(a,t,a.href)}}var u51=typeof process<"u"&&os.kindOf(process)==="process",s51=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)}),c51=({address:e,family:t})=>{if(!os.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},bFd=(e,t)=>c51(os.isObject(e)?e:{address:e,family:t}),DFd=u51&&function(t){return s51(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 we=fFd(l,Xe=>os.isArray(Xe)?Xe:[Xe]);l=(Xe,Mt,De)=>{we(Xe,Mt,(Te,It,Ee)=>{if(Te)return De(Te);let St=os.isArray(It)?It.map(ut=>bFd(ut)):[bFd(It,Ee)];Mt.all?De(Te,St):De(Te,St[0].address,St[0].family)})}}let m=new wFd.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(A),t.signal&&t.signal.removeEventListener("abort",A),m.removeAllListeners()};a((we,Xe)=>{b=!0,Xe&&(g=!0,w())});function A(we){m.emit("abort",!we||we.type?new vwe(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(A),t.signal&&(t.signal.aborted?A():t.signal.addEventListener("abort",A)));let M=nwi(t.baseURL,t.url),q=new URL(M,sT.hasBrowserEnv?sT.origin:void 0),D=q.protocol||yFd[0];if(D==="data:"){let we;if(c!=="GET")return bGt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=o_s(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Xe){throw yp.from(Xe,yp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=os.stripBOM(we))):s==="stream"&&(we=owi.default.Readable.from(we)),bGt(i,n,{data:we,status:200,statusText:"OK",headers:new lI,config:t})}if(yFd.indexOf(D)===-1)return n(new yp("Unsupported protocol "+D,yp.ERR_BAD_REQUEST,t));let C=lI.from(t.headers).normalize();C.set("User-Agent","axios/"+awi,!1);let{onUploadProgress:F,onDownloadProgress:$}=t,I=t.maxRate,U,H;if(os.isSpecCompliantForm(u)){let we=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=sFd(u,Xe=>{C.set(Xe)},{tag:`axios-${awi}-boundary`,boundary:we&&we[1]||void 0})}else if(os.isFormData(u)&&os.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let we=await PFd.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&C.setContentLength(we)}catch{}}else if(os.isBlob(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=owi.default.Readable.from(Xno(u));else if(u&&!os.isStream(u)){if(!Buffer.isBuffer(u))if(os.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(os.isString(u))u=Buffer.from(u,"utf-8");else return n(new yp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",yp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new yp("Request body larger than maxBodyLength limit",yp.ERR_BAD_REQUEST,t))}let te=os.toFiniteNumber(C.getContentLength());os.isArray(I)?(U=I[0],H=I[1]):U=H=I,u&&(F||U)&&(os.isStream(u)||(u=owi.default.Readable.from(u,{objectMode:!1})),u=owi.default.pipeline([u,new c_s({maxRate:os.toFiniteNumber(U)})],os.noop),F&&u.on("progress",vFd(u,Yun(te,H4r(Xun(F),!1,3)))));let J;if(t.auth){let we=t.auth.username||"",Xe=t.auth.password||"";J=we+":"+Xe}if(!J&&q.username){let we=q.username,Xe=q.password;J=we+":"+Xe}J&&C.delete("authorization");let ee;try{ee=iwi(q.pathname+q.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Xe=new Error(we.message);return Xe.config=t,Xe.url=t.url,Xe.exists=!0,n(Xe)}C.set("Accept-Encoding","gzip, compress, deflate"+(hFd?", br":""),!1);let fe={path:ee,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:D,family:f,beforeRedirect:o51,beforeRedirects:{}};!os.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=q.hostname.startsWith("[")?q.hostname.slice(1,-1):q.hostname,fe.port=q.port,SFd(fe,t.proxy,D+"//"+q.hostname+(q.port?":"+q.port:"")+fe.path));let me,ve=a51.test(fe.protocol);if(fe.agent=ve?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=ve?mFd.default:OFd.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),me=ve?n51:i51),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=me.request(fe,function(Xe){if(O.destroyed)return;let Mt=[Xe],De=+Xe.headers["content-length"];if($||H){let ut=new c_s({maxRate:os.toFiniteNumber(H)});$&&ut.on("progress",vFd(ut,Yun(De,H4r(Xun($),!0,3)))),Mt.push(ut)}let Te=Xe,It=Xe.req||O;if(t.decompress!==!1&&Xe.headers["content-encoding"])switch((c==="HEAD"||Xe.statusCode===204)&&delete Xe.headers["content-encoding"],(Xe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Mt.push($4r.default.createUnzip(_Fd)),delete Xe.headers["content-encoding"];break;case"deflate":Mt.push(new lFd),Mt.push($4r.default.createUnzip(_Fd)),delete Xe.headers["content-encoding"];break;case"br":hFd&&(Mt.push($4r.default.createBrotliDecompress(r51)),delete Xe.headers["content-encoding"])}Te=Mt.length>1?owi.default.pipeline(Mt,os.noop):Mt[0];let Ee=owi.default.finished(Te,()=>{Ee(),w()}),St={status:Xe.statusCode,statusText:Xe.statusMessage,headers:new lI(Xe.headers),config:t,request:It};if(s==="stream")St.data=Te,bGt(i,n,St);else{let ut=[],ge=0;Te.on("data",function(wt){ut.push(wt),ge+=wt.length,t.maxContentLength>-1&&ge>t.maxContentLength&&(g=!0,Te.destroy(),n(new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,It)))}),Te.on("aborted",function(){if(g)return;let wt=new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,It);Te.destroy(wt),n(wt)}),Te.on("error",function(wt){O.destroyed||n(yp.from(wt,null,t,It))}),Te.on("end",function(){try{let wt=ut.length===1?ut[0]:Buffer.concat(ut);s!=="arraybuffer"&&(wt=wt.toString(o),(!o||o==="utf8")&&(wt=os.stripBOM(wt))),St.data=wt}catch(wt){return n(yp.from(wt,null,t,St.request,St))}bGt(i,n,St)})}m.once("abort",ut=>{Te.destroyed||(Te.emit("error",ut),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Xe){n(yp.from(Xe,null,t,O))}),O.on("socket",function(Xe){Xe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new yp("error trying to parse `config.timeout` to int",yp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Mt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||Qun;t.timeoutErrorMessage&&(Mt=t.timeoutErrorMessage),n(new yp(Mt,De.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,t,O)),A()})}if(os.isStream(u)){let we=!1,Xe=!1;u.on("end",()=>{we=!0}),u.once("error",Mt=>{Xe=!0,O.destroy(Mt)}),u.on("close",()=>{!we&&!Xe&&A(new vwe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var EFd=sT.hasStandardBrowserEnv?function(){let t=sT.navigator&&/(msie|trident)/i.test(sT.navigator.userAgent),r=document.createElement("a"),i;function n(a){let u=a;return t&&(r.setAttribute("href",u),u=r.href),r.setAttribute("href",u),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return i=n(window.location.href),function(u){let l=os.isString(u)?n(u):u;return l.protocol===i.protocol&&l.host===i.host}}():function(){return function(){return!0}}();var AFd=sT.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];os.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),os.isString(i)&&u.push("path="+i),os.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 MFd=e=>e instanceof lI?{...e}:e;function s2t(e,t){t=t||{};let r={};function i(s,o,c){return os.isPlainObject(s)&&os.isPlainObject(o)?os.merge.call({caseless:c},s,o):os.isPlainObject(o)?os.merge({},o):os.isArray(o)?o.slice():o}function n(s,o,c){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s,c)}else return i(s,o,c)}function a(s,o){if(!os.isUndefined(o))return i(void 0,o)}function u(s,o){if(os.isUndefined(o)){if(!os.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)=>n(MFd(s),MFd(o),!0)};return os.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=f[o]||n,b=c(e[o],t[o],o);os.isUndefined(b)&&c!==l||(r[o]=b)}),r}var Zno=e=>{let t=s2t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=lI.from(u),t.url=iwi(nwi(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(os.isFormData(r)){if(sT.hasStandardBrowserEnv||sT.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(sT.hasStandardBrowserEnv&&(i&&os.isFunction(i)&&(i=i(t)),i||i!==!1&&EFd(t.url))){let s=n&&a&&AFd.read(a);s&&u.set(n,s)}return t};var l51=typeof XMLHttpRequest<"u",qFd=l51&&function(e){return new Promise(function(r,i){let n=Zno(e),a=n.data,u=lI.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 w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function A(){if(!w)return;let q=lI.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:q,config:e,request:w};bGt(function($){r($),m()},function($){i($),m()},C),w=null}"onloadend"in w?w.onloadend=A:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(A)},w.onabort=function(){w&&(i(new yp("Request aborted",yp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new yp("Network Error",yp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||Qun;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new yp(D,C.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&os.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),os.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=H4r(s,!0),w.addEventListener("progress",b)),f&&w.upload&&([c,g]=H4r(f),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=q=>{w&&(i(!q||q.type?new vwe(null,e,w):q),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let M=sQn(n.url);if(M&&sT.protocols.indexOf(M)===-1){i(new yp("Unsupported protocol "+M+":",yp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var f51=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof yp?o:new vwe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new yp(`timeout ${t} of ms exceeded`,yp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:f}=i;return f.unsubscribe=()=>os.asap(l),f}},TFd=f51;var d51=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},p51=async function*(e,t){for await(let r of _51(e))yield*d51(r,t)},_51=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()}},d_s=(e,t,r,i)=>{let n=p51(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 eao=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",BFd=eao&&typeof ReadableStream=="function",h51=eao&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),xFd=(e,...t)=>{try{return!!e(...t)}catch{return!1}},y51=BFd&&xFd(()=>{let e=!1,t=new Request(sT.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),CFd=64*1024,p_s=BFd&&xFd(()=>os.isReadableStream(new Response("").body)),kno={stream:p_s&&(e=>e.body)};eao&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!kno[t]&&(kno[t]=os.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new yp(`Response type '${t}' is not supported`,yp.ERR_NOT_SUPPORT,i)})})})(new Response);var v51=async e=>{if(e==null)return 0;if(os.isBlob(e))return e.size;if(os.isSpecCompliantForm(e))return(await new Request(sT.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(os.isArrayBufferView(e)||os.isArrayBuffer(e))return e.byteLength;if(os.isURLSearchParams(e)&&(e=e+""),os.isString(e))return(await h51(e)).byteLength},b51=async(e,t)=>{let r=os.toFiniteNumber(e.getContentLength());return r??v51(t)},IFd=eao&&(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}=Zno(e);s=s?(s+"").toLowerCase():"text";let g=TFd([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(f&&y51&&r!=="get"&&r!=="head"&&(w=await b51(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),F;if(os.isFormData(i)&&(F=C.headers.get("content-type"))&&o.setContentType(F),C.body){let[$,I]=Yun(w,H4r(Xun(f)));i=d_s(C.body,CFd,$,I)}}os.isString(c)||(c=c?"include":"omit");let A="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:A?c:void 0});let M=await fetch(O),q=p_s&&(s==="stream"||s==="response");if(p_s&&(l||q&&m)){let C={};["status","statusText","headers"].forEach(U=>{C[U]=M[U]});let F=os.toFiniteNumber(M.headers.get("content-length")),[$,I]=l&&Yun(F,H4r(Xun(l),!0))||[];M=new Response(d_s(M.body,CFd,$,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await kno[os.findKey(kno,s)||"text"](M,e);return!q&&m&&m(),await new Promise((C,F)=>{bGt(C,F,{data:D,headers:lI.from(M.headers),status:M.status,statusText:M.statusText,config:e,request:O})})}catch(A){throw m&&m(),A&&A.name==="TypeError"&&/fetch/i.test(A.message)?Object.assign(new yp("Network Error",yp.ERR_NETWORK,e,O),{cause:A.cause||A}):yp.from(A,A&&A.code,e,O)}});var __s={http:DFd,xhr:qFd,fetch:IFd};os.forEach(__s,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var zFd=e=>`- ${e}`,g51=e=>os.isFunction(e)||e===null||e===!1,tao={getAdapter:e=>{e=os.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,!g51(r)&&(i=__s[(u=String(r)).toLowerCase()],i===void 0))throw new yp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,f])=>`adapter ${l} `+(f===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1922,7 +1922,7 @@ ${q}${M}${D}${dup.default.cursorHide}`});var rZn=mi(pPi(),1);function nSs(e,t){i
1922
1922
  Run ${Su.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1923
1923
  Run ${Su.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),kun(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function hSs({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!zup(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+=`
1924
1924
  ${await KjS(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Su.dim(l.currentVersion)+Su.reset(" \u2192 ")+Su.green(l.latestVersion);return n+=`
1925
- `,i?kun(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function KjS(e){let r=await new Iup.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 YjS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await Nup({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=NYr(o.name,c),g=await BWt({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 Nup({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=NYr(s.name,o),b=await BWt({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 Nup({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 B7t({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 Fup(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=Bte(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 i_o({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await YjS({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(...Fup(s,f,t.logger));else u.push(...Fup(l.versions,void 0,t.logger))}return u}var lZn=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 Lfn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ufn=e=>e!==null&&typeof e=="object";var fZn=(...e)=>{for(let t of e)if((!Ufn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return bSs({},...e)},ySs=(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 n_o(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:bSs(e[r]??[],t[r]??[])}var vSs=(e={},t={})=>({beforeRequest:n_o(e,t,"beforeRequest"),beforeRetry:n_o(e,t,"beforeRetry"),afterResponse:n_o(e,t,"afterResponse"),beforeError:n_o(e,t,"beforeError")}),bSs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ufn(n)){for(let[a,u]of Object.entries(n))Ufn(u)&&a in t&&(u=bSs(t[a],u)),t={...t,[a]:u};Ufn(n.hooks)&&(i=vSs(i,n.hooks),t.hooks=i),Ufn(n.headers)&&(r=ySs(r,n.headers),t.headers=r)}return t};var Lup=(()=>{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})(),Uup=typeof globalThis.AbortController=="function",Vup=typeof globalThis.ReadableStream=="function",Wup=typeof globalThis.FormData=="function",a_o=["get","post","put","patch","head","delete"],XjS=()=>{};XjS();var Hup={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},o_o=2147483647,u_o=Symbol("stop"),$up={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},Gup={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 Jup=e=>a_o.includes(e)?e.toUpperCase():e,ZjS=["get","put","head","delete","options","trace"],kjS=[408,413,429,500,502,503,504],ewS=[413,429,503],Qup={limit:2,methods:ZjS,statusCodes:kjS,afterStatusCodes:ewS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Kup=(e={})=>{if(typeof e=="number")return{...Qup,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{...Qup,...e}};async function gSs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new Lfn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function OSs(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 Yup=(e,t)=>{let r={};for(let i in t)!(i in Gup)&&!(i in $up)&&!(i in e)&&(r[i]=t[i]);return r};var dZn=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>o_o)throw new RangeError(`The \`timeout\` option cannot be greater than ${o_o}`);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 lZn(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(!Vup)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(Hup))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:ySs(this._input.headers,r.headers),hooks:vSs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Jup(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Kup(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(Uup){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(Lup&&(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);(Wup&&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 Lfn)throw t;if(t instanceof lZn){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),o_o);if(this._retryCount<1)throw r;await OSs(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})===u_o)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=Yup(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):gSs(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 mSs=e=>{let t=(r,i)=>dZn.create(r,fZn(e,i));for(let r of a_o)t[r]=(i,n)=>dZn.create(i,fZn(e,n,{method:r}));return t.create=r=>mSs(fZn(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),mSs(fZn(e,r))),t.stop=u_o,t},twS=mSs(),Xup=twS;var Osp=mi(gsp(),1);function DSs(e){let t=(0,Osp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var _cp=mi(pcp(),1),hcp=mi(pPi(),1),LSs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},USs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function VSs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??DSs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,_cp.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 Xup(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new LSs(e):c}if(t.allVersions)return s;let o=new USs(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=hcp.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 bZn(e,t){let{version:r}=await VSs(e.toLowerCase(),t);return r}async function zei({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:bZn(e.packageName,{version:t?"prerelease":"latest"})}var ycp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],g_o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eg.Info;constructor(t){this.ttyAwareLogger=new r_o(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.53.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Su.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Yk}failWithoutThrowing(t,r){this.didSucceed=!1,Zpo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Hun()).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 Rup({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1925
+ `,i?kun(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function KjS(e){let r=await new Iup.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 YjS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await Nup({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=NYr(o.name,c),g=await BWt({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 Nup({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=NYr(s.name,o),b=await BWt({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 Nup({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 B7t({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 Fup(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=Bte(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 i_o({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await YjS({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(...Fup(s,f,t.logger));else u.push(...Fup(l.versions,void 0,t.logger))}return u}var lZn=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 Lfn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ufn=e=>e!==null&&typeof e=="object";var fZn=(...e)=>{for(let t of e)if((!Ufn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return bSs({},...e)},ySs=(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 n_o(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:bSs(e[r]??[],t[r]??[])}var vSs=(e={},t={})=>({beforeRequest:n_o(e,t,"beforeRequest"),beforeRetry:n_o(e,t,"beforeRetry"),afterResponse:n_o(e,t,"afterResponse"),beforeError:n_o(e,t,"beforeError")}),bSs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ufn(n)){for(let[a,u]of Object.entries(n))Ufn(u)&&a in t&&(u=bSs(t[a],u)),t={...t,[a]:u};Ufn(n.hooks)&&(i=vSs(i,n.hooks),t.hooks=i),Ufn(n.headers)&&(r=ySs(r,n.headers),t.headers=r)}return t};var Lup=(()=>{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})(),Uup=typeof globalThis.AbortController=="function",Vup=typeof globalThis.ReadableStream=="function",Wup=typeof globalThis.FormData=="function",a_o=["get","post","put","patch","head","delete"],XjS=()=>{};XjS();var Hup={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},o_o=2147483647,u_o=Symbol("stop"),$up={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},Gup={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 Jup=e=>a_o.includes(e)?e.toUpperCase():e,ZjS=["get","put","head","delete","options","trace"],kjS=[408,413,429,500,502,503,504],ewS=[413,429,503],Qup={limit:2,methods:ZjS,statusCodes:kjS,afterStatusCodes:ewS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Kup=(e={})=>{if(typeof e=="number")return{...Qup,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{...Qup,...e}};async function gSs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new Lfn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function OSs(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 Yup=(e,t)=>{let r={};for(let i in t)!(i in Gup)&&!(i in $up)&&!(i in e)&&(r[i]=t[i]);return r};var dZn=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>o_o)throw new RangeError(`The \`timeout\` option cannot be greater than ${o_o}`);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 lZn(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(!Vup)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(Hup))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:ySs(this._input.headers,r.headers),hooks:vSs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Jup(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Kup(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(Uup){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(Lup&&(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);(Wup&&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 Lfn)throw t;if(t instanceof lZn){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),o_o);if(this._retryCount<1)throw r;await OSs(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})===u_o)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=Yup(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):gSs(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 mSs=e=>{let t=(r,i)=>dZn.create(r,fZn(e,i));for(let r of a_o)t[r]=(i,n)=>dZn.create(i,fZn(e,n,{method:r}));return t.create=r=>mSs(fZn(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),mSs(fZn(e,r))),t.stop=u_o,t},twS=mSs(),Xup=twS;var Osp=mi(gsp(),1);function DSs(e){let t=(0,Osp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var _cp=mi(pcp(),1),hcp=mi(pPi(),1),LSs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},USs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function VSs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??DSs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,_cp.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 Xup(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new LSs(e):c}if(t.allVersions)return s;let o=new USs(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=hcp.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 bZn(e,t){let{version:r}=await VSs(e.toLowerCase(),t);return r}async function zei({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:bZn(e.packageName,{version:t?"prerelease":"latest"})}var ycp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],g_o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eg.Info;constructor(t){this.ttyAwareLogger=new r_o(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.53.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Su.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Yk}failWithoutThrowing(t,r){this.didSucceed=!1,Zpo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Hun()).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 Rup({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1926
1926
  `)||(r+=`
1927
1927
  `),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=Q$u(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 iZn(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 Yk}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await Hun()).sendEvent(t)}logger=j6r(this.log.bind(this));constructTaskInitForWorkspace(t){let r=vcp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?vcp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=ycp[this.numTasks++%ycp.length],u=Su.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===IT.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=>eYr.indexOf(i.level)>=eYr.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===eg.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 zei({cliEnvironment:this.environment,includePreReleases:t}),i=Bte(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await i_o({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Z1s({message:t,default:r})}async getInput(t){return await k1s({message:t.message,default:t.default})}};function vcp(e){return`[${e}]:`}var qAp=require("fs/promises");function VBe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Su.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Su.dim(r)),i.join(`
1928
1928
  `)}var Zjp=require("fs/promises");var L2t=class e{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;type=e.Type;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var zwe=class extends L2t{definition;sources;constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var gZn=class{context;constructor(t){this.context=t}};var O_o=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let f=n!=null?Wh.of(`${n}${X3t}${u}`):Wh.of(u);t[f]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${X3t}${u}`:u,f=i.directories[u];r(f,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(X3t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Wh.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 pSi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new O_o,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return X6r(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"]))o1S(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??NP((Zqe(r)+"/"+vmi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Wh.of(WF))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=i8a(Zqe(Xtn.of(`/${t}`)),Xtn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=i8a(Zqe(Xtn.of(`/${t}`)),Xtn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>U3t(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=Ez(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:Ez(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:Ez(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===m1?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 o1S(e){return e?.header!=null}var xte={openapi:e=>({...e,type:"openapi",_visit:function(t){return xte._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return xte._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 Jfn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Jfn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var e8={basic:e=>({...e,type:"basic",_visit:function(t){return e8._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return e8._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return e8._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return e8._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return e8._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 M0={primitive:e=>({value:e,type:"primitive",_visit:function(t){return M0._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return M0._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return M0._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return M0._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return M0._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return M0._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return M0._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return M0._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 Jp={int:e=>({value:e,type:"int",_visit:function(t){return Jp._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return Jp._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return Jp._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return Jp._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return Jp._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return Jp._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Jp._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return Jp._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return Jp._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return Jp._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return Jp._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 Kfn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Kfn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Kfn._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 Rei={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return Rei._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return Rei._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 GL={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case GL.GenerallyAvailable:return t.generallyAvailable();case GL.Beta:return t.beta();case GL.Deprecated:return t.deprecated();default:return t._other()}}};var F8r={cursor:e=>({...e,type:"cursor",_visit:function(t){return F8r._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return F8r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);default:return t._other(e)}}};var L8r={language:e=>({...e,type:"language",_visit:function(t){return L8r._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return L8r._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 QL={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 QL.Curl:return t.curl();case QL.Python:return t.python();case QL.Javascript:return t.javascript();case QL.Typescript:return t.typescript();case QL.Go:return t.go();case QL.Ruby:return t.ruby();case QL.Csharp:return t.csharp();case QL.Java:return t.java();case QL.Js:return t.js();case QL.Node:return t.node();case QL.Ts:return t.ts();case QL.Nodets:return t.nodets();case QL.Golang:return t.golang();case QL.Dotnet:return t.dotnet();case QL.Jvm:return t.jvm();default:return t._other()}}};var U2t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return U2t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return U2t._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 WBe={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return WBe._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return WBe._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 FH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case FH.Get:return t.get();case FH.Post:return t.post();case FH.Put:return t.put();case FH.Patch:return t.patch();case FH.Delete:return t.delete();case FH.Head:return t.head();case FH.Options:return t.options();case FH.Trace:return t.trace();default:return t._other()}}};var Nei={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Nei._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Nei._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Nei._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 HBe={file:e=>({...e,type:"file",_visit:function(t){return HBe._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return HBe._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 Ite={file:e=>({...e,type:"file",_visit:function(t){return Ite._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Ite._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Ite._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return Ite._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return Ite._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return Ite._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var ey={primitive:e=>({...e,type:"primitive",_visit:function(t){return ey._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ey._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return ey._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return ey._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return ey._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return ey._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return ey._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return ey._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ey._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return ey._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return ey._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var VP={int:e=>({...e,type:"int",_visit:function(t){return VP._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return VP._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return VP._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return VP._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return VP._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return VP._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return VP._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return VP._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return VP._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return VP._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return VP._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 OB={boolean:e=>({value:e,type:"boolean",_visit:function(t){return OB._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return OB._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 U8r={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return U8r._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return U8r._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 Rwe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Rwe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Rwe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Rwe._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 mB={file:e=>({...e,type:"file",_visit:function(t){return mB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return mB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return mB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return mB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return mB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return mB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Tl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Tl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Tl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Tl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Tl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Tl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Tl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Tl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Tl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Tl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Tl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Tl._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 hK={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return hK._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return hK._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 Gd={int:e=>({...e,type:"int",_visit:function(t){return Gd._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Gd._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return Gd._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return Gd._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return Gd._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return Gd._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Gd._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return Gd._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return Gd._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return Gd._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Gd._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 Uy={};Ro(Uy,{AllOfPropertyConflict:()=>vdn,ArraySchema:()=>Cho,ArraySchemaWithExample:()=>oyo,Availability:()=>q_o,Base64WithExample:()=>tyo,BasicSecurityScheme:()=>B_o,BearerSecurityScheme:()=>x_o,BooleanSchema:()=>Dho,BooleanWithExample:()=>ryo,CasingOverrides:()=>R_o,CommonProperty:()=>Lho,CommonPropertyWithExample:()=>hyo,CursorPagination:()=>pho,CustomCodeSample:()=>fho,CustomCodeSampleLanguage:()=>sho,CustomCodeSampleSdk:()=>lho,DateWithExample:()=>eyo,DatetimeWithExample:()=>kho,DiscriminatedOneOfSchema:()=>Nho,DiscriminatedOneOfSchemaWithExample:()=>pyo,DoubleSchema:()=>who,DoubleWithExample:()=>Xho,Encoding:()=>M_o,Endpoint:()=>hho,EndpointExample:()=>ddn,EndpointResponseExample:()=>uho,EndpointSdkName:()=>cQt,EndpointWithExample:()=>Qcp,EnumSchema:()=>kfn,EnumSchemaWithExample:()=>nyo,EnumValue:()=>Uei,ErrorExample:()=>rho,FernExample:()=>nho,FileResponse:()=>udn,FileSchema:()=>Y_o,FloatWithExample:()=>Yho,FullEndpointExample:()=>dho,FullExample:()=>sM,FullObjectExample:()=>$_o,FullOneOfExample:()=>Q_o,GlobalHeader:()=>Aho,Header:()=>Wei,HeaderExample:()=>fdn,HeaderSecurityScheme:()=>I_o,HeaderWithExample:()=>Gei,HttpEndpointServer:()=>cdn,HttpError:()=>iho,HttpErrorWithExample:()=>$ho,HttpMethod:()=>rdn,IdempotencyHeader:()=>Mho,Int64WithExample:()=>Qho,IntSchema:()=>Pho,IntWithExample:()=>Gho,JsonRequest:()=>k_o,JsonRequestWithExample:()=>Vho,JsonResponse:()=>sdn,JsonResponseWithExample:()=>Odn,KeyValuePair:()=>G_o,LiteralExample:()=>H_o,LiteralSchema:()=>ydn,LiteralSchemaValue:()=>qho,LongSchema:()=>jho,MapSchema:()=>Bho,MapSchemaWithExample:()=>uyo,MultipartRequest:()=>odn,MultipartRequestProperty:()=>Z_o,MultipartSchema:()=>X_o,NamedFullExample:()=>fQt,Namespace:()=>N_o,NamespaceId:()=>W_o,NullableSchema:()=>Iho,NullableSchemaWithExample:()=>cyo,OauthSecurityScheme:()=>L_o,ObjectProperty:()=>Rho,ObjectPropertyConflictInfo:()=>bdn,ObjectPropertyWithExample:()=>dyo,ObjectSchema:()=>Tho,ObjectSchemaWithExample:()=>lyo,OctetStreamRequest:()=>adn,OffsetPagination:()=>_ho,OneOfSchema:()=>zho,OneOfSchemaWithExample:()=>fyo,OpenApiIntermediateRepresentation:()=>$cp,OpenApiSource:()=>S_o,OptionalSchema:()=>xho,OptionalSchemaWithExample:()=>syo,Pagination:()=>pdn,PathParameter:()=>idn,PathParameterExample:()=>aho,PathParameterWithExample:()=>Uho,PrimitiveExample:()=>tdn,PrimitiveSchema:()=>$ei,PrimitiveSchemaValue:()=>Eho,PrimitiveSchemaValueWithExample:()=>iyo,PrimitiveSchemaWithExample:()=>mdn,PropertyKey:()=>edn,ProtobufEncoding:()=>A_o,ProtobufSource:()=>D_o,QueryParameter:()=>ndn,QueryParameterExample:()=>ldn,QueryParameterWithExample:()=>gdn,QuerySecurityScheme:()=>z_o,ReferencedSchema:()=>lQt,Request:()=>eho,RequestWithExample:()=>Who,Response:()=>tho,ResponseWithExample:()=>Hho,Schema:()=>uO,SchemaId:()=>yK,SchemaWithExample:()=>QE,Schemas:()=>mho,SdkGroup:()=>F_o,SdkGroupInfo:()=>J_o,SdkGroupName:()=>Vei,SecurityScheme:()=>U_o,SecuritySchemeId:()=>C_o,Server:()=>V_o,Source:()=>E_o,StatusCode:()=>oQt,StreamingResponseExample:()=>oho,StringSchema:()=>Sho,StringSchemaWithExample:()=>Zho,SupportedSdkLanguage:()=>cho,Tag:()=>T_o,TagId:()=>vK,Tags:()=>K_o,TextResponse:()=>Hei,Uint64WithExample:()=>Kho,UintWithExample:()=>Jho,UnDiscriminatedOneOfSchema:()=>Fho,UnDiscriminatedOneOfSchemaWithExample:()=>_yo,UnknownSchemaWithExample:()=>ayo,Webhook:()=>yho,WebhookExampleCall:()=>hdn,WebhookHttpMethod:()=>_dn,WebhookWithExample:()=>Jcp,WebsocketChannel:()=>Oho,WebsocketHandshake:()=>vho,WebsocketHandshakeWithExample:()=>Gcp,WebsocketMessageExample:()=>bho,WebsocketSessionExample:()=>gho,WithAvailability:()=>J_,WithDescription:()=>vf,WithEncoding:()=>zte,WithInline:()=>AD,WithName:()=>Ib,WithNamespace:()=>sQt,WithSdkGroupName:()=>oO,WithSource:()=>$h,WithStatusCode:()=>uQt,WithTitle:()=>aO,commons:()=>QSs,example:()=>JSs,finalIr:()=>KSs,parseIr:()=>YSs});var QSs={};Ro(QSs,{BasicSecurityScheme:()=>B_o,BearerSecurityScheme:()=>x_o,Encoding:()=>M_o,HeaderSecurityScheme:()=>I_o,Namespace:()=>N_o,NamespaceId:()=>W_o,OauthSecurityScheme:()=>L_o,OpenApiSource:()=>S_o,ProtobufEncoding:()=>A_o,ProtobufSource:()=>D_o,QuerySecurityScheme:()=>z_o,SchemaId:()=>yK,SdkGroup:()=>F_o,SdkGroupName:()=>Vei,SecurityScheme:()=>U_o,SecuritySchemeId:()=>C_o,Server:()=>V_o,Source:()=>E_o,StatusCode:()=>oQt,Tag:()=>T_o,TagId:()=>vK,WithAvailability:()=>J_,WithDescription:()=>vf,WithEncoding:()=>zte,WithInline:()=>AD,WithName:()=>Ib,WithNamespace:()=>sQt,WithSdkGroupName:()=>oO,WithSource:()=>$h,WithStatusCode:()=>uQt,WithTitle:()=>aO});var Tt={};Ro(Tt,{JsonError:()=>Yfn,ParseError:()=>Xfn,any:()=>Ccp,bigint:()=>gcp,boolean:()=>Bcp,booleanLiteral:()=>Tcp,date:()=>Ocp,discriminant:()=>Vcp,enum_:()=>P_o,getObjectLikeUtils:()=>V2t,getObjectUtils:()=>_Si,getSchemaUtils:()=>uM,isProperty:()=>Lei,lazy:()=>mcp,lazyObject:()=>Acp,list:()=>w_o,number:()=>xcp,object:()=>j_o,objectWithoutOptionalProperties:()=>Ecp,optional:()=>WSs,property:()=>jcp,record:()=>Ncp,set:()=>Fcp,string:()=>Icp,stringLiteral:()=>qcp,transform:()=>HSs,undiscriminatedUnion:()=>Ucp,union:()=>Hcp,unknown:()=>zcp,withParsedProperties:()=>GSs});var OP={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 GE(e,t){return`Expected ${t}. Received ${u1S(e)}.`}function u1S(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 t8(e){return{...e,json:bcp(e.json),parse:bcp(e.parse)}}function bcp(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(`
@@ -1961,7 +1961,7 @@ ${b}
1961
1961
  `)}];if(t["base-properties"]!=null){let q=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=lEi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:q,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 F3p(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&D1(O.declaration)){let q=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return lEi({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:q,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]:w,...A}=c,M=[];return w==null?M.push({message:`Missing property "${m}"`}):M.push(...y8({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:f+1})),M.push(...F3p(A)),M}function F3p(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function Fjo({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:f}){return KR(t,{alias:s=>C3p({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:f}),enum:s=>B3p({rawEnum:s,example:a,breadcrumbs:l}),object:s=>lEi({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f}),discriminatedUnion:s=>L3p({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f}),undiscriminatedUnion:s=>x3p({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:f})})}var K3p=/^([+-]?\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)?)?)?)?$/,VdD=/^[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}$/,WdD=/^\d{4}-\d{2}-\d{2}$/,HdD=128;function y8({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>HdD)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(xWt)){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?[]:ihn({expected:f,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return APi({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>$dD({primitiveType:f,example:t}),named:f=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:f,file:n});return s==null?[]:Fjo({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})=>Sj(t)?Object.entries(t).flatMap(([o,c])=>[...y8({rawTypeReference:f,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...y8({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):_xe(t,"a map"),list:f=>Array.isArray(t)?t.flatMap((s,o)=>y8({rawTypeReference:f,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):_xe(t,"a list"),set:f=>{if(!Array.isArray(t))return _xe(t,"a list");let s=M$u(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
1962
1962
  `+s.map(o=>` - ${JSON.stringify(o)}`).join(`
1963
1963
  `)}]:t.flatMap((o,c)=>y8({rawTypeReference:f,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:f=>t==null?[]:y8({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:f=>t==null?[]:y8({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 Ywe(s=>s===f.boolean,f.boolean.toString())(t);case"string":return Ywe(s=>s===f.string,`"${f.string}"`)(t);default:Zo(f)}}}})}function $dD({primitiveType:e,example:t}){return e.v2!=null?yP._visit(e.v2,{integer:r=>GdD({example:t,rules:r.validation}),long:()=>H3p(t),uint:()=>U3p(t),uint64:()=>V3p(t),double:r=>QdD({example:t,rules:r.validation}),float:()=>W3p(t),boolean:()=>$3p(t),string:r=>JdD({example:t,rules:r.validation}),uuid:()=>G3p(t),date:()=>J3p(t),dateTime:()=>Q3p(t),base64:()=>rhn(t),bigInteger:()=>rhn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):Gb._visit(e.v1,{integer:()=>Y3p(t),long:()=>H3p(t),uint:()=>U3p(t),uint64:()=>V3p(t),double:()=>X3p(t),float:()=>W3p(t),boolean:()=>$3p(t),string:()=>rhn(t),uuid:()=>G3p(t),dateTime:()=>Q3p(t),date:()=>J3p(t),base64:()=>rhn(t),bigInteger:()=>rhn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function GdD({example:e,rules:t}){let r=Y3p(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 QdD({example:e,rules:t}){let r=X3p(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 JdD({example:e,rules:t}){let r=rhn(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 rhn=Ywe(e=>typeof e=="string","a string"),Y3p=Ywe(e=>Number.isInteger(e),"an integer"),U3p=Ywe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),V3p=Ywe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),W3p=Ywe(e=>typeof e=="number","a float"),X3p=Ywe(e=>typeof e=="number","a double"),H3p=Ywe(e=>Number.isInteger(e),"an integer"),$3p=Ywe(e=>typeof e=="boolean","a boolean"),G3p=Ywe(e=>typeof e=="string"&&VdD.test(e),"a UUID"),Q3p=Ywe(e=>typeof e=="string"&&K3p.test(e),"an ISO 8601 timestamp"),J3p=Ywe(e=>typeof e=="string"&&WdD.test(e)&&K3p.test(e),"a date");function Ywe(e,t){return r=>e(r)?[]:_xe(r,t)}function ihn({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&&ihn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return ihn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return ihn({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&&ihn({expected:e.container.keyType,actual:t.container.keyType})&&ihn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:KdD({expected:e.container.literal,actual:t.container.literal});default:Zo(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Zo(e)}function KdD({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:Zo(e)}}function Ljo({_enum:e,file:t}){let r=e.enum.map(n=>({...i$(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:nhn(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 Z3p(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 nhn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function t7s({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return KR(t,{alias:f=>Ej.alias({value:CD({example:r,rawTypeBeingExemplified:typeof f=="string"?f:f.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:f=>k3p({typeName:e,rawObject:f,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:f=>{let s=fEi(f);if(!Sj(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 Ej.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:Sri(f).name,wireValue:s}),singleUnionType:XdD({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 Ej.enum({value:u.casingsGenerator.generateNameAndWireValue({name:Z3p(r,f).name,wireValue:r})})},undiscriminatedUnion:f=>{for(let[c,b]of f.union.entries())if(y8({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Ej.undiscriminatedUnion({index:c,singleUnionType:CD({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 CD({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:APi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>YdD({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!Sj(l))throw new Error("Example is not an object");return ab.container(gO.map({map:Object.entries(l).map(([g,O])=>({key:CD({example:g,fileContainingExample:f,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:CD({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 ab.container(gO.list({list:l.map(b=>CD({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 ab.container(gO.set({set:l.map(b=>CD({example:b,fileContainingExample:f,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>ab.container(gO.optional({optional:l!=null?CD({example:l,fileContainingExample:f,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>ab.container(gO.nullable({nullable:l!=null?CD({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 ab.container(gO.literal({literal:$p.boolean(c.boolean)}));case"string":return ab.container(gO.literal({literal:$p.string({original:c.string})}));default:Zo(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 ab.named({typeName:O,shape:t7s({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:f,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>ab.unknown(s)}}),jsonExample:s}}function YdD({example:e,typeBeingExemplified:t}){return Gb._visit(t,{string:()=>{if(typeof e!="string")throw new Error(`Expected string. Received ${e}`);return ab.primitive($p.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error(`Expected ISO datetime. Received ${e}`);return ab.primitive($p.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error(`Expected ISO date. Received ${e}`);return ab.primitive($p.date(e))},base64:()=>{if(typeof e!="string")throw new Error(`Expected base64 encoded string. Received ${e}`);return ab.primitive($p.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error(`Expected unsigned integer. Received ${e}`);return ab.primitive($p.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error(`Expected unsigned 64-bit integer. Received ${e}`);return ab.primitive($p.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error(`Expected integer. Received ${e}`);return ab.primitive($p.integer(e))},float:()=>{if(typeof e!="number")throw new Error(`Expected float. Received ${e}`);return ab.primitive($p.float(e))},double:()=>{if(typeof e!="number")throw new Error(`Expected double. Received ${e}`);return ab.primitive($p.double(e))},long:()=>{if(typeof e!="number")throw new Error(`Expected long. Received ${e}`);return ab.primitive($p.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error(`Expected boolean. Received ${e}`);return ab.primitive($p.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error(`Expected uuid. Received ${e}`);return ab.primitive($p.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error(`Expected big integer. Received ${e}`);return ab.primitive($p.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function k3p({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!Sj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Ej.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((f,[s,o])=>{let c=e7p({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return f;let b=CD({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:uU({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),f},[]):[]})}function e7p({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:jra({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function jra({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"||!D1(u.declaration))throw new Error("Extension is not of a named object");let l=e7p({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function XdD({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:thn({unionKey:f,rawSingleUnionType:t}).name,wireValue:f});if(e==null)return{wireDiscriminantValue:o,shape:QR.noProperties()};let c=e7s({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!Sj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:QR.singleProperty(CD({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!Sj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;mXr(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!D1(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:QR.samePropertiesAsObject({typeId:Og.generateTypeId(m),object:k3p({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:Zo(c)}}function Ujo({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=C5r({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...i$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function C5r({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function t7p({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:f}){let s=kdD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:f});return{id:r.name??Njo(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:npD({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...epD({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:C5r({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:CD({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:f}),shape:ZdD({queryParameter:b})}}):[],request:tpD({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:f}),response:rpD({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:f})}}function ZdD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?k7.exploded():k7.single()}function kdD({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=wra({parameter:g,variableResolver:a,file:u});return{name:b,value:CD({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=y6t(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],w=e["path-parameters"]?.[g],A=b[g];if(m!=null)f.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(A!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:A,examplePathParameter:O}));else if(w!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:f,endpointPathParameters:o,servicePathParameters:s}}function epD({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:eJt({headerKey:s,header:c}).name,wireValue:s}),value:CD({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:eJt({headerKey:s,header:b}).name,wireValue:s}),value:CD({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 tpD({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"&&uHn(u)!=null)return;if(!oT(u))return pH.reference(CD({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(!Sj(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&&FTe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:uU({propertyKey:f,property:o}).name,wireValue:f}),value:CD({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=jra({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:uU({propertyKey:f,property:b.rawPropertyType}).name,wireValue:f}),value:CD({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 pH.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function rpD({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?QM.ok(uT.body(void 0)):qPi(e,t.response,{body:l=>{if(l.error!=null){let f=i.getDeclarationOrThrow(l.error,a);return QM.error({error:jri({errorName:l.error,file:a}),body:f.declaration.type!=null?CD({example:l.body,rawTypeBeingExemplified:f.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:f.file,fileContainingExample:a,workspace:u}):void 0})}return QM.ok(uT.body(ipD({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 QM.ok(uT.stream(l.stream.map(s=>{if(f!=null)return CD({example:s,rawTypeBeingExemplified:f,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(dg)))},events:l=>{let f=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return QM.ok(uT.sse(l.stream.map(({event:s,data:o})=>{if(f==null)return;let c=CD({example:o,rawTypeBeingExemplified:f,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(dg)))}})}function ipD({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 CD({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function npD({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=av(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 r7p({endpoint:e,file:t,typeResolver:r}){return{body:apD({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function apD({endpoint:e,file:t,typeResolver:r}){let i=opD({endpoint:e,file:t,typeResolver:r}),n=upD({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=hL.fileDownload({...i});break}case"json":{a=hL.json({...i.value});break}case"text":{a=hL.text({...i});break}case"bytes":{a=hL.bytes({...i});break}default:Zo(i)}return RT.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return RT.streaming(n)}}function opD({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 FTe(a)!=null?RT.fileDownload({docs:n}):sHn(a)!=null?RT.text({docs:n}):GWt(a)!=null?RT.bytes({docs:n}):spD(i,n,t,r)}}function upD({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 Cin(a)?xee.text({docs:n}):typeof i!="string"&&u==="sse"?xee.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0}):xee.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0})}}function spD(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?RT.json(w7t.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:gra({typeResolver:i,file:r,resolvedType:u,property:l})})):RT.json(w7t.response({docs:t,responseBodyType:a}))}function i7p({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return xTe.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 n7p({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return xTe.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 a7p(e){return cpD(e)?{type:"offset",offset:h6t(e.offset),results:q5r(e.results),step:e.step!=null?h6t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?q5r(e["has-next-page"]):void 0}:{type:"cursor",cursor:h6t(e.cursor),next_cursor:q5r(e.next_cursor),results:q5r(e.results)}}function cpD(e){return e.offset!=null&&e.results!=null}function o7p({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=a7p(n);switch(a.type){case"cursor":return i7p({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return n7p({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});default:Zo(a)}}function Vjo({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function u7p({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:Vjo({source:e}),name:wri.generateName(r)}}function s7p({file:e,serviceDeclaration:t,sourceResolver:r}){return NWt(t.source)?l7p(e,t.source,r,t.transport?.grpc?.["service-name"]):TTe.http()}function c7p({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=NWt(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 TTe.http();if(n&&u){let f=r.source,s=r.transport?.grpc?.["service-name"];return s?l7p(e,f,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
1964
- ${JSON.stringify(r)}"`)}}function l7p(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=u7p({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return TTe.grpc({service:a})}function f7p({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=ahn({pathParameters:r["path-parameters"],location:CTe.Service,file:i,variableResolver:f}),g=s7p({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:tre(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:pxe(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,A])=>hxe({headerKey:w,header:A,file:i})):[],pathParameters:b,encoding:ppD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,A])=>{let M=ahn({pathParameters:y6t(A),location:CTe.Endpoint,file:i,variableResolver:f}),q={...i$(A),id:"",name:i.casingsGenerator.generateName(w),displayName:A["display-name"],auth:A.auth??r.auth,idempotent:A.idempotent??r.idempotent??!1,baseUrl:A.url??r.url??e,method:A.method!=null?dpD(A.method):Cee.Post,basePath:A["base-path"]!=null?pxe(A["base-path"]):void 0,path:pxe(A.path),fullPath:pxe(A["base-path"]!=null?av(A["base-path"],A.path):i.rootApiFile["base-path"]!=null?av(i.rootApiFile["base-path"],r["base-path"],A.path):av(r["base-path"],A.path)),pathParameters:M,allPathParameters:A["base-path"]!=null?M:[...t,...b,...M],queryParameters:typeof A.request!="string"&&A.request?.["query-parameters"]!=null?Object.entries(A.request["query-parameters"]).map(([D,C])=>Ujo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof A.request!="string"&&A.request?.headers!=null?Object.entries(A.request.headers).map(([D,C])=>hxe({headerKey:D,header:C,file:i})):[],requestBody:S3p({request:A.request,file:i}),sdkRequest:q3p({service:r,request:A.request,endpoint:A,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:r7p({endpoint:A,file:i,typeResolver:a}),errors:[...m3p({errors:A.errors,file:i}),...o],userSpecifiedExamples:A.examples!=null?A.examples.map(D=>({example:t7p({service:r,endpoint:A,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:f,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>T3p({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:o7p({propertyResolver:u,file:i,endpointName:w,endpointSchema:A}),transport:c7p({file:i,serviceTransport:g,endpointDeclaration:A,sourceResolver:s})};return q.id=Og.generateEndpointId(O,q),q})}}function ahn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>lpD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function lpD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...i$(t),name:i.casingsGenerator.generateName(e),valueType:fpD({parameter:t,variableResolver:n,file:i}),location:r,variable:Enn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function fpD({parameter:e,variableResolver:t,file:r}){let i=wra({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function wra({parameter:e,variableResolver:t,file:r}){let i=Wjo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function Wjo({parameter:e,variableResolver:t,file:r}){if(Enn(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 dpD(e){switch(e){case"GET":return Cee.Get;case"POST":return Cee.Post;case"PUT":return Cee.Put;case"PATCH":return Cee.Patch;case"DELETE":return Cee.Delete;default:Zo(e)}}function hxe({headerKey:e,header:t,file:r}){let{name:i}=eJt({headerKey:e,header:t});return{...i$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function eJt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function ppD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Zo(e)}}var n$={};Ro(n$,{validateObjectExample:()=>lEi,validateTypeExample:()=>Fjo,validateTypeReferenceExample:()=>y8});var Hjo=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:Og.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:ld(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!d7p(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(!d7p(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=Og.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 d7p(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 p7p(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function $jo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function _7p({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Og.generateEndpointIdFromResolvedEndpoint(n),serviceId:Og.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:$jo({fernFilePath:n.file.fernFilepath})?void 0:Og.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 h7p({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:Og.generateEndpointIdFromResolvedEndpoint(n),serviceId:Og.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:$jo({fernFilePath:n.file.fernFilepath})?void 0:Og.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:_pD({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 _pD=({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 y7p({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=h7p({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?_7p({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 Sra={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}},r7s={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 v7p(e){return{endpoint:e["get-token"].endpoint,requestProperties:hpD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ypD({responseProperties:e["get-token"]?.["response-properties"]})}}function b7p(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:vpD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:bpD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function hpD({requestProperties:e}){if(e==null)return Sra.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?h6t(t):Sra.requestProperties.client_id,client_secret:r!=null?h6t(r):Sra.requestProperties.client_secret,scopes:i!=null?h6t(i):Sra.requestProperties.scopes}}function ypD({responseProperties:e}){return g7p({responseProperties:e,defaultValue:Sra.responseProperties})}function vpD({requestProperties:e}){if(e==null)return r7s.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?h6t(t):r7s.requestProperties.refresh_token}}function bpD({responseProperties:e}){return g7p({responseProperties:e,defaultValue:r7s.responseProperties})}function g7p({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?q5r(r):t.access_token,expires_in:i!=null?q5r(i):t.expires_in,refresh_token:n!=null?q5r(n):t.refresh_token}}function w7p({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:sXr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return cHn(e.auth,{single:a=>{let u=O7p({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:sXr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:sXr.Any,schemes:a.map(u=>O7p({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function O7p({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 Xts(s,{header:o=>_L.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=>P7p({file:r,docs:f,rawScheme:o}),bearer:o=>m7p({file:r,docs:f,rawScheme:o}),oauth:o=>j7p({file:r,docs:f,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return m7p({file:r,docs:void 0,rawScheme:void 0});case"basic":return P7p({file:r,docs:void 0,rawScheme:void 0});case"oauth":return j7p({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function m7p({file:e,docs:t,rawScheme:r}){return _L.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function P7p({file:e,docs:t,rawScheme:r}){return _L.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 j7p({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return _L.oauth({docs:t,configuration:cXr.clientCredentials(y7p({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:v7p(r),refreshTokenEndpoint:b7p(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function S7p({file:e,rawApiFileSchema:t}){if(t.version!=null)return fXr.header({header:gpD({file:e,header:t.version.header}),value:OpD({file:e,versionDeclaration:t.version})})}function gpD({file:e,header:t}){return typeof t=="string"?hxe({file:e,headerKey:t,header:{type:"string"}}):hxe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function OpD({file:e,versionDeclaration:t}){return Ljo({_enum:{default:t.default,enum:t.values},file:e})}function D7p({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:tre(f.availability),docs:f.docs,origin:f.origin,body:jpD({body:f.body,file:n}),displayName:f["display-name"]});return{availability:tre(e.availability),path:pxe(e.path),auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,f])=>hxe({headerKey:l,header:f,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?ahn({pathParameters:e["path-parameters"],location:CTe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,f])=>{let{name:s}=C5r({queryParameterKey:l,queryParameter:f}),o=n.parseTypeReference(f);return{...i$(f),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof f!="string"&&f["allow-multiple"]!=null?f["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let f=SpD({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:EpD({channel:e,example:l,pathParams:f}),...f,...DpD({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:C5r({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:CD({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:mpD({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:PpD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function mpD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?k7.exploded():k7.single()}function PpD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!ApD(e.body))return E7t.reference(CD({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Sj(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:uU({propertyKey:l,property:s}).name,wireValue:l}),value:CD({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=jra({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:uU({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:CD({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 E7t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function jpD({body:e,file:t}){return typeof e=="string"?Fee.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):wpD(e)?Fee.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Fee.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:_6t(e.extends??[]).map(r=>h8({typeName:r,file:t})),properties:[]})}function wpD(e){return e.type!=null}function SpD({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=wra({parameter:o,variableResolver:n,file:a});return{name:s,value:CD({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=y6t(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 DpD({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:eJt({headerKey:l,header:s}).name,wireValue:l}),value:CD({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 EpD({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 ApD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function i7s({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:X6r(i,{singleBaseUrl:()=>m7t.singleBaseUrl(MpD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>m7t.multipleBaseUrls(qpD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function MpD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>X6r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:E7p(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function qpD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>X6r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:ld(a.urls,u=>E7p(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function E7p(e){return e.endsWith("/")?e.slice(0,-1):e}function A7p({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:CD({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:jri({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var M7p="content";function q7p(e,t){if(e==null||e.strategy==="status-code")return S7t.statusCode();switch(e.strategy){case"property":return S7t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:M7p,wireValue:M7p})});default:Zo(e)}}function T7p({readme:e,services:t}){let r=new n7s(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 n7s=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=CpD({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:TpD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function TpD(e){let t="";e.fullPath.head.length>0&&(t=av(t,e.fullPath.head));for(let r of e.fullPath.parts)t=av(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=av(t,r.tail));return t.startsWith("/")?t:`/${t}`}function CpD({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 C7p({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Og.generateWebhookId(t.fernFilepath,u),availability:tre(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])=>hxe({headerKey:f,header:s,file:t})):[],payload:BpD({payload:l.payload,file:t}),examples:l.examples!=null?IpD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function BpD({payload:e,file:t}){return typeof e=="string"?Nee.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):Gjo(e)?Nee.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Nee.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:_6t(e.extends).map(r=>h8({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>xpD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?tre(i.availability):void 0,file:t})):[]})}function xpD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uU({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function IpD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:Gjo(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:CD({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Sj(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:CD({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function Gjo(e){return e.type!=null}function ohn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function B7p({name:e,source:t}){return LP.userDefined({file:Vjo({source:t}),name:wri.generateName(e)})}function x7p({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=zpD({type:e.proto.type});if(t!=null)return t}}function zpD({type:e}){switch(e){case"google.protobuf.Any":return LP.wellKnown(Kf.any());case"google.protobuf.Api":return LP.wellKnown(Kf.api());case"google.protobuf.BoolValue":return LP.wellKnown(Kf.boolValue());case"google.protobuf.BytesValue":return LP.wellKnown(Kf.bytesValue());case"google.protobuf.DoubleValue":return LP.wellKnown(Kf.doubleValue());case"google.protobuf.Duration":return LP.wellKnown(Kf.duration());case"google.protobuf.Empty":return LP.wellKnown(Kf.empty());case"google.protobuf.Enum":return LP.wellKnown(Kf.enum());case"google.protobuf.EnumValue":return LP.wellKnown(Kf.enumValue());case"google.protobuf.Field":return LP.wellKnown(Kf.field());case"google.protobuf.FieldCardinality":return LP.wellKnown(Kf.fieldCardinality());case"google.protobuf.FieldKind":return LP.wellKnown(Kf.fieldKind());case"google.protobuf.FieldMask":return LP.wellKnown(Kf.fieldMask());case"google.protobuf.FloatVlaue":return LP.wellKnown(Kf.floatValue());case"google.protobuf.Int32Value":return LP.wellKnown(Kf.int32Value());case"google.protobuf.Int64Value":return LP.wellKnown(Kf.int64Value());case"google.protobuf.ListValue":return LP.wellKnown(Kf.listValue());case"google.protobuf.Method":return LP.wellKnown(Kf.method());case"google.protobuf.Mixin":return LP.wellKnown(Kf.mixin());case"google.protobuf.NullValue":return LP.wellKnown(Kf.nullValue());case"google.protobuf.Option":return LP.wellKnown(Kf.option());case"google.protobuf.SourceContext":return LP.wellKnown(Kf.sourceContext());case"google.protobuf.StringValue":return LP.wellKnown(Kf.stringValue());case"google.protobuf.Struct":return LP.wellKnown(Kf.struct());case"google.protobuf.Syntax":return LP.wellKnown(Kf.syntax());case"google.protobuf.Timestamp":return LP.wellKnown(Kf.timestamp());case"google.protobuf.Type":return LP.wellKnown(Kf.type());case"google.protobuf.Uint32Value":return LP.wellKnown(Kf.uint32Value());case"google.protobuf.Uint64Value":return LP.wellKnown(Kf.uint64Value());case"google.protobuf.Value":return LP.wellKnown(Kf.value())}}function I7p({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=aI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&D1(a.declaration)){let u=aI(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 mq.object({extends:_6t(a.declaration.extends).map(f=>h8({typeName:f,file:t})),properties:bra({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function z7p({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return qTe(i)?I7p({generic:i,file:t,typeResolver:r}):mq.alias({aliasOf:t.parseTypeReference(e),resolvedType:RpD({aliasOf:i,file:t,typeResolver:r})})}function RpD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return yL.primitive(i.originalTypeReference.primitive);case"container":return yL.container(i.originalTypeReference.container);case"unknown":return yL.unknown();case"named":{let n=D1(i.declaration)?D7t.Object:PXr(i.declaration)?D7t.Union:T7t(i.declaration)?D7t.Enum:Ann(i.declaration)?D7t.UndiscriminatedUnion:Zo(i.declaration);return yL.named({name:i.name,shape:n})}}}function R7p({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 mq.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function N7p(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 o7s({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new a7s}){let n=KR(e,{alias:u=>{let l=typeof u=="string"?u:u.type,f=aI(l);if(f!=null){let s=new Set(f.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=aI(o.typeName)?.arguments;if(D1(o.declaration)){let b=N7p(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>N7p(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=vL({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=h8({typeName:f,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t});if(qTe(o.typeName))continue;a.push(...o7s({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var a7s=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 F7p({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=i$(t),f=h8({typeName:e,file:r}),s=o7s({typeDeclaration:t,file:r,typeResolver:i}),o={};D1(t)&&(o=ohn(t.properties??{}));let c=FpD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:WpD(t),name:f,shape:NpD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:LpD({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:t7s({typeName:f,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function NpD({typeDeclaration:e,file:t,typeResolver:r}){return KR(e,{alias:i=>z7p({alias:i,file:t,typeResolver:r}),object:i=>j3p({object:i,file:t}),discriminatedUnion:i=>N3p({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>R7p({union:i,file:t}),enum:i=>mq.enum(Ljo({_enum:i,file:t}))})}function FpD({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=x7p({encoding:t.encoding});if(a!=null)return K6r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return K6r.proto(B7p({source:n,name:r}))}function LpD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?UpD(e.encoding):VpD(t)}function UpD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function VpD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function WpD(e){if(typeof e!="string"&&"inline"in e)return e.inline}var L7p="1.0.0";var Qjo=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:L7p,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints(),environments:this.ir.environments}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:Uc.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Uc.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return Uc.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Zo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Uc.ReferencedRequestBodyType.bytes();case"typeReference":return Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Zo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Uc.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return Uc.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Zo(r)}}convertFileUploadRequestBody({properties:t}){return Uc.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return Uc.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Zo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Uc.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Uc.FileUploadRequestBodyProperty.fileArray(t.key);default:Zo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=Uc.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Zo(t)}}convertContainerType(t){switch(t.type){case"list":return Uc.TypeReference.list(this.convertTypeReference(t.list));case"map":return Uc.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Uc.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Uc.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Uc.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Uc.TypeReference.literal(this.convertLiteral(t.literal));default:Zo(t)}}convertNamedType(t){return Uc.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Zo(t.shape)}}convertAlias({declaration:t,alias:r}){return Uc.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Uc.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i})}convertObjectProperties({declaration:t,properties:r}){return Uc.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Uc.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Zo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Uc.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Uc.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return Uc.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Uc.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Uc.LiteralType.boolean(t.boolean);case"string":return Uc.LiteralType.string(t.string);default:Zo(t)}}convertPrimitiveType(t){return Uc.TypeReference.primitive(t.v1)}convertUnknownType(){return Uc.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Uc.Auth.basic(r);case"bearer":return Uc.Auth.bearer(r);case"header":return Uc.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Zo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=av(r,t.fullPath.head));for(let i of t.fullPath.parts)r=av(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=av(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function U7p(e){return new Qjo(e).convert()}function V7p({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return tJt({containerType:t});switch(t.type){case"list":{let u=dT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gO.literal({literal:t.literal._visit({boolean:u=>$p.boolean(u),string:u=>$p.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return tJt({containerType:t});let u=dT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return tJt({containerType:t});let u=dT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=dT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=dT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=dT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Zo(t)}}function tJt({containerType:e}){switch(e.type){case"list":return{type:"success",example:gO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gO.literal({literal:e.literal._visit({boolean:t=>$p.boolean(t),string:t=>$p.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:gO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:gO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:gO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Zo(e)}}function H7p({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return QpD({fieldName:e,validation:HpD(t.v2)});case"BASE_64":return{type:"success",example:$p.base64(Z0.BASE64),jsonExample:Z0.BASE64};case"BOOLEAN":return{type:"success",example:$p.boolean(Z0.BOOLEAN),jsonExample:Z0.BOOLEAN};case"DATE":return{type:"success",example:$p.date(Z0.DATE),jsonExample:Z0.DATE};case"DATE_TIME":return{type:"success",example:$p.datetime({datetime:new Date(Z0.DATE_TIME),raw:Z0.DATE_TIME}),jsonExample:Z0.DATE_TIME};case"DOUBLE":return JpD({fieldName:e,validation:$pD(t.v2)});case"FLOAT":return{type:"success",example:$p.float(Z0.FLOAT),jsonExample:Z0.FLOAT};case"INTEGER":return KpD({fieldName:e,validation:GpD(t.v2)});case"UINT_64":return{type:"success",example:$p.uint64(Z0.INT64),jsonExample:Z0.INT64};case"UINT":return{type:"success",example:$p.uint(Z0.UINT),jsonExample:Z0.UINT};case"BIG_INTEGER":return{type:"success",example:$p.bigInteger(Z0.INT64.toString()),jsonExample:`${Z0.INT64}`};case"LONG":return{type:"success",example:$p.long(Z0.INT64),jsonExample:Z0.INT64};case"UUID":return{type:"success",example:$p.uuid(Z0.UUID),jsonExample:Z0.UUID};default:Zo(t.v1)}}function HpD(e){if(e?.type==="string")return e.validation}function $pD(e){if(e?.type==="double")return e.validation}function GpD(e){if(e?.type==="integer")return e.validation}function W7p(e){if(e<=Z0.SAMPLE_STRINGS.length){let t=Z0.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Z0.SAMPLE_STRINGS[Z0.SAMPLE_STRINGS.length-1]+".".repeat(e-Z0.SAMPLE_STRINGS.length)}function QpD({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=W7p(i);return{type:"success",example:$p.string({original:a}),jsonExample:a}}else if(n){let a=W7p(n);return{type:"success",example:$p.string({original:a}),jsonExample:a}}}let r=e??Z0.STRING;return{type:"success",example:$p.string({original:r}),jsonExample:r}}function JpD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$p.double(r),jsonExample:r};if(i)return{type:"success",example:$p.double(i),jsonExample:i}}return{type:"success",example:$p.double(Z0.DOUBLE),jsonExample:Z0.DOUBLE}}function KpD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$p.integer(r),jsonExample:r};if(i)return{type:"success",example:$p.integer(i),jsonExample:i}}return{type:"success",example:$p.integer(Z0.INT),jsonExample:Z0.INT}}function dT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let l=Dra({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:f,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ab.named({shape:f,typeName:u.name})},jsonExample:s}}case"container":{let u=V7p({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=tJt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ab.container(s)},jsonExample:o}}let{example:l,jsonExample:f}=u;return{type:"success",example:{jsonExample:f,shape:ab.container(l)},jsonExample:f}}case"primitive":{let{jsonExample:u,example:l}=H7p({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ab.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ab.unknown(u)},jsonExample:u}}}}function uhn({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function Dra({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=dT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:f}=u;return{type:"success",example:Ej.alias({value:l}),jsonExample:f}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Ej.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${c.typeId}`);let g=Dra({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let f=$7p({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:s,jsonExample:o}=f;return{type:"success",example:Ej.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let f=dT({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure"){++u;continue}let{example:s,jsonExample:o}=f;return{type:"success",example:Ej.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let s=dT({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[f.name.wireValue]=s.jsonExample)}for(let f of r.shape.types){let s=f.shape._visit({noProperties:()=>({type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)throw new Error(`Failed to find type declaration with id ${o.typeId}`);if(c.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${c.shape.type}`);let b=$7p({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:c.shape,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.samePropertiesAsObject({typeId:c.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=dT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.singleProperty(b)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function $7p({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},f=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=dT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!uhn({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;f.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Ej.object({properties:f}),jsonExample:l}}var u7s=S1.primitive({v1:Gb.String,v2:yP.string({default:void 0,validation:void 0})});function Era({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:QM.ok(uT.body(void 0)),docs:void 0},l=[{params:t.pathParameters,add:s=>u.endpointPathParameters.push(s)},{params:r.pathParameters,add:s=>u.servicePathParameters.push(s)},{params:e.pathParameters,add:s=>u.rootPathParameters.push(s)}];for(let s of l)for(let o of s.params){let c=dT({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}for(let s of t.queryParameters){if(n&&uhn({typeDeclarations:i,typeReference:s.valueType}))continue;let o=dT({fieldName:s.name.name.originalName,currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:s.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:c}=o;u.queryParameters.push({name:s.name,shape:s.allowMultiple?k7.exploded():k7.single(),value:c})}let f=[{params:t.headers,add:s=>u.endpointHeaders.push(s)},{params:r.headers,add:s=>u.serviceHeaders.push(s)}];for(let s of f)for(let o of s.params){if(n&&uhn({typeDeclarations:i,typeReference:o.valueType}))continue;let c=dT({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let s={},o=[];if(t.requestBody.extends!=null)for(let c of t.requestBody.extends){let b=i[c.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${c.typeId}`);let g=Dra({typeDeclaration:b,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});g.type==="success"&&Object.assign(s,g.jsonExample)}for(let c of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=dT({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!uhn({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:g,jsonExample:O}=b;o.push({name:c.name,originalTypeDeclaration:void 0,value:g}),s[c.name.wireValue]=O}u.request=pH.inlinedRequestBody({jsonExample:s,properties:o});break}case"reference":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.request=pH.reference(o);break}default:Zo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"streamParameter":{let s;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1});break;default:Zo(t.response.body.nonStreamResponse)}if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"streaming":{let s;switch(t.response.body.value.type){case"sse":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.sse([{data:{...o,jsonExample:c},event:""}]));break}case"json":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.stream([{...o,jsonExample:c}]));break}case"text":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.stream([{...o,jsonExample:c}]));break}default:Zo(t.response.body.value)}break}case"text":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Zo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=QM.error({body:void 0,error:a.declaration.name});else{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.response=QM.error({body:o,error:a.declaration.name})}try{return{type:"success",example:{id:Njo(u),url:YpD(t,u),...u},jsonExample:void 0}}catch(s){return{type:"failure",message:`Parse failure with exceptions ${s}`}}}function YpD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function G7p(e,t){let r=t[e];if(r==null)throw new P6r(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Q7p(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,ZpD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>XpD({endpoint:i,ir:e}))}]))}}function XpD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>J7p(r,t))}}}function ZpD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>J7p(r,t))}}}return e}function J7p(e,t){let r=s7s(e.typeId,t);return K7p({objectTypeDeclaration:r,ir:t})}function s7s(e,t){let r=G7p(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return s7s(r.shape.resolvedType.name.typeId,t)}throw new P6r(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function K7p({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=s7s(i.typeId,t);return K7p({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function X7p({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:OI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?QR.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=OI({filteredIr:e,exampleTypeReference:r});return i!==void 0?QR.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function OI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ab.container(gO.list({...i,list:i.list.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ab.container(gO.set({...i,set:i.set.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?OI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ab.container(gO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?OI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ab.container(gO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ab.container(gO.map({...i,map:i.map.map(n=>{let a=OI({filteredIr:e,exampleTypeReference:n.key}),u=OI({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=OI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ab.named({...r,shape:Ej.enum(i)})}),object:i=>({...t,shape:ab.named({...r,shape:Ej.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:OI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=X7p({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=OI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function c7s({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function kpD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Y7p({filteredIr:e,headers:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function e_D({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=OI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=OI({filteredIr:e,exampleTypeReference:r});return i!==void 0?pH.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function t_D({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>QM.ok(uT.body(i!=null?OI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>QM.ok(uT.stream(i.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(dg))),sse:i=>QM.ok(uT.sse(i.map(({event:n,data:a})=>{let u=OI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(dg))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>QM.error({error:r,body:i!=null?OI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function l7s({filteredIr:e,example:t}){return{...t,rootPathParameters:c7s({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:c7s({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:c7s({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:Y7p({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:Y7p({filteredIr:e,headers:t.endpointHeaders}),queryParameters:kpD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?e_D({filteredIr:e,requestBody:t.request}):void 0,response:t_D({filteredIr:e,response:t.response})}}function Z7p({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Ej.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Ej.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:OI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=X7p({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Ej.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=OI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Ej.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var Jjo=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:f,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=f,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Og.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Og.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Og.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Yjo=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=r_D(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Og.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Og.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Og.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&mI(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Og.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,f=new Set;for(let s of[...t.headers,...r.headers])mI(s.valueType,u,f);for(let s of[...t.pathParameters,...r.pathParameters])mI(s.valueType,u,f);for(let s of r.queryParameters)mI(s.valueType,u,f);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=ohn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&e3._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)Kjo(o,u,f);for(let o of s.properties)mI(o.valueType,u,f);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oT(i.request.body)){let o=ohn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{mI(s,u,f)},fileUpload:({properties:s})=>{for(let o of s)Bee._visit(o,{file:Jo,bodyProperty:({valueType:c})=>{mI(c,u,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&RT._visit(r.response.body,{fileDownload:Jo,json:s=>{mI(s.responseBodyType,u,f)},streaming:s=>{s._visit({sse:o=>mI(o.payload,u,f),json:o=>mI(o.payload,u,f),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>mI(o.payload,u,f),json:o=>mI(o.payload,u,f),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&mI(s.nonStreamResponse.value.responseBodyType,u,f)},text:Jo,bytes:Jo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Og.generateErrorId(s.error)),f.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:f}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Og.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&Nee._visit(r.payload,{inlinedPayload:l=>{for(let f of l.extends)Kjo(f,a,u);for(let f of l.properties)mI(f.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!Gjo(i.payload)){let f=ohn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:f}}},reference:({payloadType:l})=>{mI(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Fee._visit(l.body,{reference:({bodyType:f})=>{mI(f,a,u)},inlinedBody:f=>{for(let s of f.extends)Kjo(s,a,u);for(let s of f.properties)mI(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(l);for(let s of f.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(l);this.addReferencedTypes(t,f.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(l);this.addReferencedTypes(t,f.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,f]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new Jjo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Zo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Og.generateSubpackageId(i))}}};function r_D(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Zo(e)}}function mI(e,t,r){S1._visit(e,{container:i=>{i_D(i,t,r)},named:i=>{Kjo(i,t,r)},primitive:Jo,unknown:Jo,_other:Jo})}function Kjo(e,t,r){t.add(Og.generateTypeId(e)),r.add(e.fernFilepath)}function i_D(e,t,r){FE._visit(e,{list:i=>{mI(i,t,r)},map:i=>{mI(i.keyType,t,r),mI(i.valueType,t,r)},optional:i=>{mI(i,t,r)},nullable:i=>{mI(i,t,r)},set:i=>{mI(i,t,r)},literal:Jo,_other:Jo})}function k7p({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:Pri({referencedIn:t,importPath:l})}}var dEi=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 dN(this.workspace,(n,a,u)=>{let l=Ab({relativeFilepath:n,definitionFile:a,casingsGenerator:wri,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})}),KSi(this.workspace,(n,a)=>{let u=Ab({relativeFilepath:n,definitionFile:a,casingsGenerator:wri,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 TPi().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=k7p({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var pEi=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=Kwe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Ab({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Xwe=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(Sj(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(`\\${xWt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(xWt))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(xWt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(xWt.length),exampleName:n}}};var Xjo=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:Iee.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:Iee.query(Ujo({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:Iee.body(u)}}if(oT(i.body)){let u=X3s({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Iee.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:Iee.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Y3s({typeResolver:this.typeResolver,file:Ora(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 Bw=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=Kwe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=aI(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:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return vL({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:S1.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:S1.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:S1.container(FE.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:S1.container(FE.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:S1.container(FE.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:S1.container(FE.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:S1.container(FE.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:S1.container(FE.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(mXr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=Pra({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||Hte(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 b6t=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:T5r({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 Zjo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function m2({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:f,context:s,fdrApiDefinitionId:o,sourceResolver:c}){let b=ZQt({generationLanguage:t,keywords:r,smartCasing:i}),g=new Yjo(a),O=T5r({casingsGenerator:b,rootApiFile:e.definition.rootApiFile.contents}),m=(e.definition.rootApiFile.contents.errors??[]).map(St=>({error:jri({errorName:St,file:O}),docs:void 0})),w=new Bw(e),A=new dEi(e),M=new Xjo(w,A),q=new pEi(e),D=new Xwe(w),C=new b6t,F={fdrApiDefinitionId:o,apiVersion:S7p({file:O,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:b.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:xjo(e.definition.rootApiFile.contents.docs),auth:w7p({rawApiFileSchema:e.definition.rootApiFile.contents,file:O,propertyResolver:M,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([St,ut])=>hxe({headerKey:St,header:ut,file:O})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([St,ut])=>hxe({headerKey:St,header:ut,file:O})):[],types:{},errors:{},services:{},constants:p7p(b),environments:i7s({casingsGenerator:b,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:q7p(e.definition.rootApiFile.contents["error-discrimination"],O),basePath:e.definition.rootApiFile.contents["base-path"]!=null?pxe(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:ahn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:O,location:CTe.Root,variableResolver:C}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([St,ut])=>({docs:typeof ut!="string"?ut.docs:void 0,id:St,name:O.casingsGenerator.generateName(St),type:O.parseTypeReference(ut)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},$=new Hjo,I=St=>{$.addSubpackage(St.fernFilepath),wj(St.definitionFile,{imports:Jo,docs:ut=>{ut!=null&&$.addDocs(St.fernFilepath,ut)},types:ut=>{if(ut!=null)for(let[ge,Pe]of Object.entries(ut)){if(qTe(ge))continue;let wt=F7p({typeName:ge,typeDeclaration:Pe,file:St,typeResolver:w,exampleResolver:D,sourceResolver:c,workspace:e}),Ot=wt.typeDeclaration;n.disabled&&(Ot.userProvidedExamples=[],Ot.autogeneratedExamples=[]);let vr=wt.descendantFilepaths,ur=Og.generateTypeId(Ot.name);F.types[ur]=Ot,$.addType(ur,Ot),g.addType({declaredTypeName:Ot.name,descendantTypeIds:Ot.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:vr}),g.markTypeForAudiences(Ot.name,P3p(Pe))}},errors:ut=>{if(ut==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[Pe,wt]of Object.entries(ut)){let Ot=A7p({errorName:Pe,errorDeclaration:wt,file:St,typeResolver:w,exampleResolver:D,workspace:e}),vr=Og.generateErrorId(Ot.name);F.errors[vr]=Ot,$.addError(vr,Ot),g.addError(Ot)}},service:ut=>{if(ut==null)return;let ge=f7p({rootDefaultUrl:St.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:ut,file:St,errorResolver:q,typeResolver:w,propertyResolver:M,exampleResolver:D,sourceResolver:c,globalErrors:m,variableResolver:C,workspace:e}),Pe=Og.generateServiceId(ge.name);F.services[Pe]=ge,$.addService(Pe,ge);let wt={};ge.endpoints.forEach(Ot=>{n.disabled&&(Ot.autogeneratedExamples=[],Ot.userSpecifiedExamples=[]);let vr=ut.endpoints[Ot.name.originalName];g.addEndpoint(ge,Ot,vr),wt[Ot.name.originalName]=Ot}),ut.audiences!=null&&g.markEndpointForAudience(ge.name,ge.endpoints,ut.audiences),Object.entries(ut.endpoints).map(([Ot,vr])=>{let ur=wt[Ot];ur!=null&&vr.audiences!=null&&g.markEndpointForAudience(ge.name,[ur],vr.audiences)})},webhooks:ut=>{if(ut==null)return;let ge=Og.generateWebhookGroupId(St.fernFilepath),Pe=C7p({webhooks:ut,file:St,typeResolver:w,exampleResolver:D,workspace:e}),wt={};for(let Ot of Pe)wt[Ot.name.originalName]=Ot;Object.entries(ut).forEach(([Ot,vr])=>{let ur=wt[Ot];ur!=null&&(g.addWebhook(St,ur,vr),vr.audiences!=null&&g.markWebhookForAudiences(St,ur,vr.audiences))}),F.webhookGroups[ge]=Pe,$.addWebhookGroup(ge,St.fernFilepath)},channel:ut=>{if(ut==null)return;let ge=Og.generateWebSocketChannelId(St.fernFilepath),Pe=D7p({channel:ut,file:St,variableResolver:C,typeResolver:w,exampleResolver:D,workspace:e});g.addChannel(St,ge,Pe,ut),ut.audiences!=null&&g.markChannelForAudiences(St,ge,ut.audiences),F.websocketChannels!=null&&(F.websocketChannels[ge]=Pe,$.addWebSocketChannel(ge,St.fernFilepath))}})};dN(e,(St,ut,ge)=>{I(Ab({relativeFilepath:St,definitionFile:ut,casingsGenerator:b,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:ge.defaultUrl}))}),KSi(e,(St,ut)=>{if(ut.navigation!=null)if(typeof ut.navigation=="string")$.addPackageRedirection({from:ere({relativeFilepath:St,casingsGenerator:b}),to:ere({relativeFilepath:Ez(Zqe(St),Wh.of(ut.navigation)),casingsGenerator:b})});else{let ge=ut.navigation.map(Pe=>Og.generateSubpackageId(ere({relativeFilepath:Ez(Zqe(St),Wh.of(Pe)),casingsGenerator:b})));St===m1?$.sortRootPackage(ge):$.sortSubpackage(Og.generateSubpackageId(ere({relativeFilepath:St,casingsGenerator:b})),ge)}}),F.serviceTypeReferenceInfo=a_D(g);let U=n.disabled?F:n_D({ir:F,context:s,exampleGeneration:n}),H=e.definition.rootApiFile.contents,te=i7s({casingsGenerator:b,rawApiFileSchema:H}),J=te?.environments._visit({singleBaseUrl:St=>St.environments.filter(ut=>Zjo(ut.id,H.environments)!=null).length===0,multipleBaseUrls:St=>St.environments.filter(ut=>Zjo(ut.id,H.environments)!=null).length===0,_other:()=>!1});te?.environments.environments.forEach(St=>{g.markEnvironmentForAudiences(St,Zjo(St.id,H.environments)??[],J)});let ee=g.hasNoAudiences()?void 0:g.build(),fe=o_D(U,ee),me=e.definition.rootApiFile.contents.auth!=null&&Object.values(fe.services).every(St=>St.endpoints.every(ut=>ut.auth)),ve=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.response?.body?.type==="streaming")),we=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.pagination!=null)),Xe=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.response?.body?.type==="fileDownload")),Mt={isAuthMandatory:me,hasStreamingEndpoints:ve,hasPaginatedEndpoints:we,hasFileDownloadEndpoints:Xe,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}},De=u!=null?T7p({readme:u,services:F.services}):void 0,{types:Te,services:It}=Q7p(fe),Ee={...fe,...$.build(ee),types:Te,services:It,sdkConfig:Mt,readmeConfig:De};return{...Ee,dynamic:U7p(Ee)}}function n_D({ir:e,context:t,exampleGeneration:r}){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){if(a.userSpecifiedExamples.length>0&&r?.skipAutogenerationIfManualExamplesExist===!0)continue;t.logger.debug(`Generating example for ${a.id}`);let u=Era({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.trace(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:l}=u;a.autogeneratedExamples=[{example:l}]}return e}function a_D(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 o_D(e,t){if(t==null)return e;let r=FOi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let f=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Z7p({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:mq.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:FOi(e.errors,u=>t.hasError(u)),services:ld(FOi(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:l7s({filteredIr:t,example:f.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(f=>({...f,example:f.example!=null?l7s({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:u_D(e.serviceTypeReferenceInfo,t)}}function u_D(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 e2p(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var r2p=mi(OUn(),1);var t2p=["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 Zwe(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,r2p.default)(e,{special:t2p}).replace(/V\s(\d)/g,"V$1")}function Ara(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&e2p(e),r._other(e))}}}function rJt(e){return typeof e.subpackageId=="string"}function tC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function yxe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var f7s="__package__",Dri=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 rJt(t)?t.subpackageId:f7s}getSubpackageByIdOrLocator(t){if(t==null)return;let r=g2.SubpackageId(t);return r===f7s?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=g2.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} ${tC(u.path.parts)}`),f.push(`${o} ${yxe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${av(c.baseUrl,tC(u.path.parts))}`),f.push(`${o} ${av(c.baseUrl,yxe(u.path.parts))}`);let b=kjo(c);b!=null&&(f.push(`${o} ${av(b,tC(u.path.parts))}`),f.push(`${o} ${av(b,yxe(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} ${tC(u.path.parts)}`),f.push(`${o} ${yxe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${av(c.baseUrl,tC(u.path.parts))}`),f.push(`${o} ${av(c.baseUrl,yxe(u.path.parts))}`);let b=kjo(c);b!=null&&(f.push(`${o} ${av(b,tC(u.path.parts))}`),f.push(`${o} ${av(b,yxe(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=rJt(t)?[...r,t.name]:r,n=i.length===0?[f7s]: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 To.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return To.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return To.WebhookId(`${r}.${t.id}`)}};function kjo(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 shn=mi(zPo(),1),n2p=mi(RPo(),1);function i2p(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{}}shn.default.extend(n2p.default);var s_D="Changelog",c_D=["summary","index","overview"],B5r=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=i,this.idgen=n}toChangelogNode(t){let r=t.title??s_D,i=[],n;for(let c of this.changelogFiles??[]){let b=V$u(c.split("/"));if(b==null)continue;let g=i2p(b);if(g==null){let m=b.split(".")[0]?.toLowerCase();m!=null&&c_D.includes(m)&&(n=c);continue}let O=this.toRelativeFilepath(c);i.push({date:g,pageId:To.PageId(O),absoluteFilepath:c})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??BE(r)}),u=i.map(c=>{let b=shn.default.utc(c.date);return{id:this.idgen.get(c.pageId),type:"changelogEntry",title:b.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(c.absoluteFilepath)?.split("/"),urlSlug:b.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:c.date.toISOString(),pageId:c.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),l=d7s(u,c=>c.date,"desc"),f=n!=null?To.PageId(this.toRelativeFilepath(n)):void 0,s=this.idgen.get(f??"changelog"),o=this.groupByYear(s,l,a);return{id:s,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:f,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=shn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return d7s(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=shn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return d7s(Array.from(n.entries()).map(([a,u])=>{let l=(0,shn.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 xT(this.docsWorkspace.absoluteFilePath,t)}};function d7s(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 ewo(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>To.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:To.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Mra({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=To.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Mra({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),f=i(l,u);return{...e,children:f,pointsTo:void 0}}return e}function chn({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:To.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function two({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return chn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function iJt(e,t){if(t!=null)return xT(e.absoluteFilePath,t)}function rwo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n}){let a=To.V1.PageId(iJt(e,t.absolutePath)),u=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??BE(t.title)});return{id:i.get(a),type:"page",pageId:a,title:t.title,slug:u.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var iwo=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,f){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=To.V1.ApiDefinitionId(r.id),this.#e=Dri.create(r,u),this.#u=f,this.#c=this.apiSection.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??BE(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(o=>this.#g(o)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=To.V1.followRedirects(this.#o),r=new B5r(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#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?Dri.getSubpackageId(r):void 0;return t.map(a=>Ara(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:To.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(dg)}#f(t,r){return rwo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,idgen:this.#u})}#h(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(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=Dri.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??(rJt(a)?a.urlSlug:this.apiSection.slug??BE(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??(rJt(a)?a.displayName??Zwe(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#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??BE(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}:${BE(t.package)}`),type:"apiPackage",children:f,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#e.getSubpackageByIdOrLocator(o);return c!=null?Dri.getSubpackageId(c):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(dg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??BE(t.title),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#s(t.contents,void 0,f);return{id:a,type:"apiPackage",children:s,title:t.title,slug:f.get(),icon:t.icon,hidden: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}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=Dri.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=rJt(n)?n.urlSlug:"",f=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:rJt(n)?n.displayName??Zwe(n.name):this.apiSection.title,slug:f.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(g2.SubpackageId(r))?.endpoints.get(g2.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:To.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??tC(n.path.parts),slug:f.get(),icon:t.icon,hidden: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(g2.SubpackageId(r))?.webSockets.get(g2.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??tC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:To.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(g2.SubpackageId(r))?.webhooks.get(g2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(To.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??av("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return two({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>tC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return Mra({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??tC(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??tC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:To.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:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??Zwe(n.id),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=rJt(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:rJt(a)?a.displayName??Zwe(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return ewo(t)}mergeEndpointPairs(t){return chn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>tC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var nwo=class{api;#e={};#t={};#r={};#n={};constructor(t){this.api=t;for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${av(a.baseUrl,tC(i.path))}`]=i,this.#r[`${n} ${av(a.baseUrl,yxe(i.path))}`]=i;let u=kjo(a);u!=null&&(this.#r[`${n} ${av(u,tC(i.path))}`]=i,this.#r[`${n} ${av(u,yxe(i.path))}`]=i)}),this.#r[`${i.method} ${tC(i.path)}`]=i,this.#r[`${i.method} ${yxe(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 ${tC(i.path)}`]=i,this.#n[`STREAM ${yxe(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 p7s(e){let t=e.namespace?.map(r=>BE(r.toString()))??[];return t.push(BE(e.id.split(".").pop()??"")),e.operationId!=null?BE(e.operationId):av(t)}function _7s(e){return p7s(e)}function h7s(e){return p7s(e)}function y7s(e){return p7s(e)}var qra=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;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){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.#e=r,this.#t=new nwo(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=To.V1.ApiDefinitionId(r.id),this.#s=f,this.#l=this.apiSection.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??BE(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(o=>this.#m(o)),this.#O(this.#e,this.#u))}get(){let t=To.V1.followRedirects(this.#c),r=new B5r(this.markdownFilesToFullSlugs,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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0}),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=>Ara(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:To.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(dg)}#_(t,r){return rwo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs})}#p(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(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??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??Zwe(a.name),slug:f.get(),icon:t.icon,hidden: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??BE(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}:${BE(t.package)}`),type:"apiPackage",children:f,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#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?To.V1.PageId(iJt(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(dg);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??BE(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: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=BE(n.name),f=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??Zwe(n.name),slug:f.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#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):i.apply({urlSlug:_7s(n)});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??tC(n.path),slug:l.get(),icon:t.icon,hidden: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??tC(a.path),slug:(t.slug!=null?i.append(t.slug):i.apply({urlSlug:h7s(a)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:To.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??av("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply({urlSlug:y7s(u)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return two({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>tC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t){return Mra({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#P(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))return;let u=r.apply({urlSlug:BE(a.name)}),l={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:[],title:a.displayName??Zwe(a.name),slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#f.set(n,l),i.push(l)}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);if(this.#r.has(SA.EndpointId(n)))return;let u=r.apply({urlSlug:_7s(a)}),l={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"endpoint",method:a.method,endpointId:SA.EndpointId(n),apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(a.availability),isResponseStream:a.responses?.[0]?.body.type==="stream",title:a.displayName??tC(a.path),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let f=a.namespace[0];if(f!=null){let s=this.#f.get(f);if(s==null){this.taskContext.logger.error(`Subpackage ${f} not found in ${this.apiDefinitionId}`);return}let o=r.apply({urlSlug:BE(s.slug)});for(let c of a.namespace.slice(1)){let b=s.children.find(g=>g.type==="apiPackage"&&g.id===c.toString());o=o.append(BE(c)),b==null&&(b={id:To.V1.NodeId(`${this.apiDefinitionId}:${c}`),type:"apiPackage",children:[],title:Zwe(c),slug:o.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),b!=null&&b.type==="apiPackage"&&(s=b)}s.children.push(l)}}else i.push(l)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);if(this.#n.has(SA.WebSocketId(n)))return;let u={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webSocket",webSocketId:SA.WebSocketId(n),title:a.displayName??tC(a.path),slug:r.apply({urlSlug:h7s(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(a.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=a.namespace[0];if(l!=null){let f=this.#f.get(l);if(f==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:f.slug});for(let o of a.namespace.slice(1)){let c=f.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:To.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:Zwe(o),slug:s.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),c!=null&&c.type==="apiPackage"&&(f=c)}f.children.push(u)}}else i.push(u)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);if(this.#i.has(SA.WebhookId(n)))return;let u={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webhook",webhookId:SA.WebhookId(n),method:a.method,title:a.displayName??Zwe(a.id),slug:r.apply({urlSlug:y7s(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=a.namespace[0];if(l!=null){let f=this.#f.get(l);if(f==null)throw new Error(`Subpackage subpackage_${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:f.slug});for(let o of a.namespace.slice(1)){let c=f.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:To.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:o,slug:s.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),c!=null&&c.type==="apiPackage"&&(f=c)}f.children.push(u)}}else i.push(u)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#D(t){let r=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t))),i=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t)));return{id:SA.ApiDefinitionId(t),endpoints:r,websockets:i,webhooks:n,types:{},subpackages:{},auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#P(t,r){let i=t!=null?this.#D(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return ewo(t)}mergeEndpointPairs(t){return chn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>tC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var a2p=mi(require("crypto"),1);function l_D(e){return a2p.default.createHash("sha256").update(e).digest("hex")}var awo=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),l_D(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 To.V1.NodeId(this.#n(t))}};function owo(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0}}var uwo=mi(Oee(),1);var v7s=mi(Oee(),1);function o2p(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:v7s.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:v7s.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Zo(i)}}var WP=mi(Oee(),1);var Eri=mi(Oee(),1);function s2p(e){return e._visit({alias:t=>({type:"alias",value:sD(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:M3(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>Eri.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:Eri.FernRegistry.PropertyKey(r.name.wireValue),valueType:sD(r.valueType),availability:M3(r.availability)})),extraProperties:p_D(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:Eri.FernRegistry.PropertyKey(i.name.wireValue),valueType:sD(i.valueType),availability:M3(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?M3(i.availability):void 0,additionalProperties:Bc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[Eri.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:Eri.FernRegistry.PropertyKey(n.name.wireValue),valueType:sD(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:sD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function sD(e){return e._visit({container:t=>Bc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:sD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:sD(r),valueType:sD(i)}),optional:r=>({type:"optional",itemType:sD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:sD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:sD(r)}),literal:r=>Bc.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:Eri.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Bc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>d_D(t.v2),float:()=>u2p(t.v2),double:()=>u2p(t.v2),string:()=>f_D(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 f_D(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 d_D(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 u2p(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 p_D(e){return typeof e=="boolean"?e?S1.unknown():void 0:typeof e=="string"?{type:"id",value:Eri.FernRegistry.TypeId(e),default:void 0}:sD(e)}function g7s(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?h_D(r,t):[],webhooks:i!=null?__D(i):[],websockets:n!=null?[y_D(n,t)]:[],types:e.types.map(a=>WP.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>WP.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?WP.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function __D(e){return e.map(t=>({description:t.docs??void 0,id:WP.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??gUn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:sD(r.valueType),availability:M3(r.availability)})),payload:w_D(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function h_D(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>b7s({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(dg));else if(n!=null){let l=b7s({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Era({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let f=b7s({autogeneratedExample:l,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:M3(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:O_D(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?WP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?v_D({environmentsConfig:t.environments,endpoint:i}):void 0,id:WP.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??gUn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:WP.FernRegistry.PropertyKey(l.name.originalName),type:sD(l.valueType),availability:void 0})),parts:[...lhn(i.basePath),...lhn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:WP.FernRegistry.PropertyKey(l.name.originalName),type:sD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?lhn(t.basePath):[],...lhn(e.basePath),...lhn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:sD(l.valueType),availability:M3(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:sD(l.valueType),availability:M3(l.availability)})),request:i.requestBody!=null?m_D(i.requestBody):void 0,response:i.response!=null?P_D(i.response):void 0,errors:void 0,errorsV2:j_D(i.errors,t),examples:a};r.push(u)}return r}function y_D(e,t){return{auth:e.auth,availability:M3(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?WP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?b_D({environmentsConfig:t.environments,channel:e}):[],id:WP.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??gUn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:WP.FernRegistry.PropertyKey(r.name.originalName),type:sD(r.valueType),availability:void 0})),parts:lhn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:sD(r.valueType),description:r.docs,availability:M3(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:sD(r.valueType),availability:M3(r.availability)})),messages:e.messages.map(r=>({type:WP.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:S_D(r.body),description:r.docs,availability:M3(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[WP.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:WP.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function M3(e){if(e!=null)switch(e.status){case"DEPRECATED":return WP.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return WP.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return WP.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return WP.FernRegistry.Availability.Beta;default:Zo(e.status)}}function v_D({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:WP.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:WP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Zo(r)}}function b_D({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:WP.FernRegistry.EnvironmentId(i.id),baseUrl:g_D(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Zo(r)}}function g_D(e,t){return e.replace(/^[^:]+/,t)}function O_D(e){return Bc.http.HttpMethod._visit(e,{get:()=>WP.FernRegistry.HttpMethod.Get,post:()=>WP.FernRegistry.HttpMethod.Post,put:()=>WP.FernRegistry.HttpMethod.Put,patch:()=>WP.FernRegistry.HttpMethod.Patch,delete:()=>WP.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function lhn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:WP.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function m_D(e){let t=Bc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??oB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>WP.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:WP.FernRegistry.PropertyKey(i.name.wireValue),valueType:sD(i.valueType),availability:M3(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??oB.APPLICATION_JSON,shape:{type:"reference",value:sD(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:WP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:WP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:WP.FernRegistry.PropertyKey(n.name.wireValue),valueType:sD(n.valueType),contentType:n.contentType,description:n.docs,availability:M3(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(dg)},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 P_D(e){if(e.body==null)return;let t,r=Bc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:sD(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:sD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:sD(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 j_D(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:sD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:WP.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:WP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:sD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function b7s({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:Bc.ExampleTypeReferenceShape.primitive(Bc.ExamplePrimitive.string({original:f}))}}}).filter(dg),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[WP.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(Sj(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:F3t})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Bc.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=>awe._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(dg)}}function w_D(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>WP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:WP.FernRegistry.PropertyKey(t.name.wireValue),valueType:sD(t.valueType),availability:M3(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:sD(e.payloadType)},description:e.docs};default:Zo(e)}}function S_D(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>WP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:WP.FernRegistry.PropertyKey(t.name.wireValue),valueType:sD(t.valueType),availability:M3(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:sD(e.bodyType)};default:Zo(e)}}function kwe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:g7s(e.rootPackage,e),auth:o2p(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:M3(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:sD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[uwo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:s2p(a.shape),availability:M3(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[uwo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:uwo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...g7s(a,e)}}return i}var O7s=mi(Oee(),1);async function m7s({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=m2({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 b2(r,t)}),f=tji({token:i.value}),s=kwe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await f.api.v1.register.registerApiDefinition({orgId:O7s.FernRegistry.OrgId(e),apiId:O7s.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 D_D=new iEi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Tra(e,t,r){return ara(rra(kwe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),g2.ApiDefinitionId(t),D_D))}var S_={};Ro(S_,{AlgoliaSearchIndex:()=>c2p,ApiDefinitionId:()=>q2p,ApiId:()=>x2p,Availability:()=>K2p,DocsConfigId:()=>I2p,EndpointId:()=>R2p,EndpointPathLiteral:()=>Q2p,EnvironmentId:()=>z2p,FileId:()=>V2p,HttpMethod:()=>J2p,IndexSegmentId:()=>l2p,JqString:()=>H2p,OrgId:()=>C2p,PageId:()=>U2p,PayloadLocation:()=>P6p,PropertyKey:()=>$2p,PullRequestState:()=>v6p,RoleId:()=>G2p,TokenId:()=>B2p,TypeId:()=>L2p,Url:()=>W2p,VersionId:()=>T2p,WebSocketId:()=>N2p,WebhookId:()=>F2p,algolia:()=>P7s,api:()=>C7s,commons:()=>B7s,diff:()=>Y2p,docs:()=>V7s,generators:()=>H7s,git:()=>$7s,navigation:()=>J7s,sdks:()=>Y7s,snippets:()=>O6p,snippetsFactory:()=>m6p,templates:()=>X7s,tokens:()=>j6p});var P7s={};Ro(P7s,{AlgoliaSearchIndex:()=>c2p,IndexSegmentId:()=>l2p});function c2p(e){return e}function l2p(e){return e}var C7s={};Ro(C7s,{latest:()=>S7s,v1:()=>T7s});var S7s={};Ro(S7s,{AuthSchemeId:()=>f2p,WebhookHttpMethod:()=>h2p,auth:()=>j7s,commons:()=>d2p,endpoint:()=>p2p,type_:()=>_2p,webhook:()=>w7s,websocket:()=>y2p});var j7s={};Ro(j7s,{AuthSchemeId:()=>f2p});function f2p(e){return e}var d2p={};var p2p={};var _2p={};var w7s={};Ro(w7s,{WebhookHttpMethod:()=>h2p});var h2p={Get:"GET",Post:"POST"};var y2p={};var T7s={};Ro(T7s,{SubpackageId:()=>D2p,WebSocketMessageId:()=>E2p,WebSocketMessageOrigin:()=>A2p,WebhookHttpMethod:()=>M2p,commons:()=>q7s,db:()=>D7s,read:()=>A7s,register:()=>M7s});var D7s={};Ro(D7s,{endpoint:()=>v2p});var v2p={};var A7s={};Ro(A7s,{SupportedLanguage:()=>b2p,endpoint:()=>E7s,type_:()=>g2p,webhook:()=>O2p,websocket:()=>m2p});var E7s={};Ro(E7s,{SupportedLanguage:()=>b2p});var b2p={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby"};var g2p={};var O2p={};var m2p={};var M7s={};Ro(M7s,{SourceId:()=>E_D,endpoint:()=>P2p,type_:()=>j2p,webhook:()=>w2p,websocket:()=>S2p});var P2p={};var j2p={};var w2p={};var S2p={};function E_D(e){return e}var q7s={};Ro(q7s,{SubpackageId:()=>D2p,WebSocketMessageId:()=>E2p,WebSocketMessageOrigin:()=>A2p,WebhookHttpMethod:()=>M2p});function D2p(e){return e}function E2p(e){return e}var A2p={Client:"client",Server:"server"};var M2p={Get:"GET",Post:"POST"};var B7s={};Ro(B7s,{ApiDefinitionId:()=>q2p,ApiId:()=>x2p,Availability:()=>K2p,DocsConfigId:()=>I2p,EndpointId:()=>R2p,EndpointPathLiteral:()=>Q2p,EnvironmentId:()=>z2p,FileId:()=>V2p,HttpMethod:()=>J2p,JqString:()=>H2p,OrgId:()=>C2p,PageId:()=>U2p,PropertyKey:()=>$2p,RoleId:()=>G2p,TokenId:()=>B2p,TypeId:()=>L2p,Url:()=>W2p,VersionId:()=>T2p,WebSocketId:()=>N2p,WebhookId:()=>F2p});function q2p(e){return e}function T2p(e){return e}function C2p(e){return e}function B2p(e){return e}function x2p(e){return e}function I2p(e){return e}function z2p(e){return e}function R2p(e){return e}function N2p(e){return e}function F2p(e){return e}function L2p(e){return e}function U2p(e){return e}function V2p(e){return e}function W2p(e){return e}function H2p(e){return e}function $2p(e){return e}function G2p(e){return e}function Q2p(e){return e}var J2p={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var K2p={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var Y2p={};var V7s={};Ro(V7s,{latest:()=>z7s,v1:()=>L7s,v2:()=>U7s});var z7s={};Ro(z7s,{Layout:()=>Z2p,MdxEngine:()=>A_D,TwitterCardSetting:()=>k2p,commons:()=>X2p,frontmatter:()=>x7s,seo:()=>I7s});var A_D={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var X2p={};var x7s={};Ro(x7s,{Layout:()=>Z2p});var Z2p={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var I7s={};Ro(I7s,{TwitterCardSetting:()=>k2p});var k2p={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var L7s={};Ro(L7s,{commons:()=>F7s,db:()=>e6p,read:()=>t6p,write:()=>R7s});var e6p={};var t6p={};var R7s={};Ro(R7s,{DocsRegistrationId:()=>q_D,FilePath:()=>M_D});function M_D(e){return e}function q_D(e){return e}var F7s={};Ro(F7s,{ContentAlignment:()=>a6p,FontDisplay:()=>l6p,FontStyle:()=>c6p,HeaderPosition:()=>o6p,JsScriptStrategy:()=>s6p,ProgrammingLanguage:()=>r6p,SearchbarPlacement:()=>i6p,TabsPlacement:()=>n6p,TwitterCardSetting:()=>u6p,commons:()=>N7s});var N7s={};Ro(N7s,{ContentAlignment:()=>a6p,FontDisplay:()=>l6p,FontStyle:()=>c6p,HeaderPosition:()=>o6p,JsScriptStrategy:()=>s6p,ProgrammingLanguage:()=>r6p,SearchbarPlacement:()=>i6p,TabsPlacement:()=>n6p,TwitterCardSetting:()=>u6p});var r6p={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 i6p={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var n6p={Header:"HEADER",Sidebar:"SIDEBAR"};var a6p={Center:"CENTER",Left:"LEFT"};var o6p={Fixed:"FIXED",Absolute:"ABSOLUTE"};var u6p={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var s6p={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var c6p={Normal:"normal",Italic:"italic"};var l6p={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var U7s={};Ro(U7s,{read:()=>f6p,write:()=>d6p});var f6p={};var d6p={};var H7s={};Ro(H7s,{ChangelogEntryType:()=>_6p,GeneratorId:()=>T_D,GeneratorLanguage:()=>C_D,ReleaseType:()=>h6p,cli:()=>p6p,commons:()=>W7s,versions:()=>y6p});var p6p={};var W7s={};Ro(W7s,{ChangelogEntryType:()=>_6p,ReleaseType:()=>h6p});var _6p={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var h6p={Ga:"GA",Rc:"RC"};var y6p={};function T_D(e){return e}var C_D={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var $7s={};Ro($7s,{PullRequestState:()=>v6p});var v6p={Open:"open",Closed:"closed",Merged:"merged"};var J7s={};Ro(J7s,{latest:()=>G7s,v1:()=>Q7s});var G7s={};Ro(G7s,{NodeId:()=>I_D,ProductId:()=>z_D,Slug:()=>B_D,TabId:()=>x_D});function B_D(e){return e}function x_D(e){return e}function I_D(e){return e}function z_D(e){return e}var Q7s={};Ro(Q7s,{NavigationV1Availability:()=>U_D,NodeId:()=>F_D,ProductId:()=>L_D,Slug:()=>R_D,TabId:()=>N_D});function R_D(e){return e}function N_D(e){return e}function F_D(e){return e}function L_D(e){return e}var U_D={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Y7s={};Ro(Y7s,{Language:()=>b6p,VersionBump:()=>g6p,versions:()=>K7s});var K7s={};Ro(K7s,{Language:()=>b6p,VersionBump:()=>g6p});var b6p={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var g6p={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var O6p={};var m6p={};var X7s={};Ro(X7s,{PayloadLocation:()=>P6p});var P6p={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var j6p={};var fhn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Cd(e){return e!=null}var S6p=mi(OUn(),1);var w6p=["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 nJt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,S6p.default)(e,{special:w6p}).replace(/V\s(\d)/g,"V$1")}function swo({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];return i.namespace?.forEach(a=>{let u=a,l=[...n,u],f=S_.api.v1.SubpackageId(l.join("."));r[f]={id:f,name:l.join("/"),displayName:nJt(u)},n.push(u)})}),r}var cwo=class{errors=new fhn},dhn=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 D6p(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var lwo=class extends cwo{},Mp=class extends dhn{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 ${D6p(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})}}},ON=class extends Mp{},rre=class extends ON{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var E6p="x-fern-base-path",A6p="x-fern-availability",fwo="x-fern-sdk-group-name",M6p="x-fern-global-headers",q6p="x-fern-sdk-method-name";var T6p="x-fern-webhook",C6p="x-fern-access-token-locator",B6p="x-fern-basic",x6p="x-fern-username-variable-name",I6p="x-fern-password-variable-name",z6p="x-fern-bearer",R6p="x-fern-token-variable-name",N6p="x-fern-header",F6p="x-fern-header-variable-name",L6p="x-fern-server-name",U6p="x-fern-examples";var dwo=class extends Mp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[L6p]}convert(){if(this.serverName!=null)return this.serverName}};var pwo=class extends Mp{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 dwo({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:S_.EnvironmentId(t),baseUrl:this.url}}};function aJt(e,t,r,i){return[...e??[],...(t??[]).map((n,a)=>new pwo({input:n,context:r,accessPath:i,pathId:["servers",`${a}`]}))]}function q1(e){return typeof e=="object"&&Cd(e)&&"$ref"in e&&typeof e.$ref=="string"}function sU(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:(q1(n)&&(n=sU(n,t,r)),n)}function _wo(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return q1(r)?sU(r,t,void 0):r}var J6p=mi(eC());var hwo=class extends Mp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[B6p];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var ywo=class extends Mp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[I6p]}convert(){return this.passwordVariableName}};var vwo=class extends Mp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[x6p]}convert(){return this.usernameVariableName}};var bwo=class extends Mp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[z6p];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var gwo=class extends Mp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[R6p]}convert(){return this.tokenVariableName}};function V6p(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var W6p="x-bearer-format",H6p="x-code-samples",$6p="x-codeSamples";var Owo=class extends Mp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[W6p]}convert(){return this.bearerFormat}};var mwo=class extends Mp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[N6p];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Pwo=class extends Mp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[F6p]}convert(){return this.headerVariableName}};function G6p(e){return e.type==="apiKey"}var phn=class extends Mp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){G6p(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new mwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Pwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Owo({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 XE(e){if(e!=null)return Array.isArray(e)?e:[e]}function jwo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,isWebhook:a}){if(t==null)return;let u=r!=null&&t!=null?`${r}/${t}`:r??t;if(u!=null)return`${V_D(a)}${W_D(e)}.${H_D(i,n,u)}`}function V_D(e){return e?"webhook_":"endpoint_"}function W_D(e){return e!=null?XE(e)?.map(t=>p6t(t)).join("."):""}function H_D(e,t,r){return p6t(e??"")||t||p6t(r)}function Q6p(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var wwo=class extends Mp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[C6p],this.accessTokenLocator!=null&&(Q6p(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 Swo=class extends Mp{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 phn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new wwo({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=jwo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:S_.EndpointId(r),accessTokenLocator:S_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var _hn=class extends Mp{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 hwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new vwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new ywo({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 bwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new gwo({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":{V6p(this.input)?(this.authScheme="header",this.headerAuthNode=new phn({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 Swo({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 J6p.UnreachableCaseError(this.authScheme);return}}};var hhn=class extends Mp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=_wo(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 _hn({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(Cd))}};var Dwo=class extends Mp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[E6p],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 K6p(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Y6p(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function yhn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>XE(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!K6p(n))&&(u=Y6p(u,u.type==="enum"?u.default:void 0)),{key:S_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Cd)).filter(Cd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Ewo(e,t){return q1(e)?sU(e,t,void 0):e}function Ari(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function X6p(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 Z6p(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 k6p=mi(eC());var Z7s=["decimal","decimal128","double-int","double","float","sf-decimal"],k7s=["int16","int32","int64","int8","sf-integer","uint8"],e2s=["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"],t2s=["beta","pre-release","in-development","generally-available","deprecated"];function mN(e,t){return q1(e)?sU(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var vxe=class extends Mp{availability;constructor(t){super(t),this.safeParse()}parse(){if(mN(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[A6p];r!=null&&(t2s.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${t2s.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return S_.Availability.Beta;case"in-development":return S_.Availability.InDevelopment;case"generally-available":return S_.Availability.GenerallyAvailable;case"deprecated":return S_.Availability.Deprecated;case void 0:return;default:new k6p.UnreachableCaseError(this.availability);return}}};var Mwo=mi(eC());function e4p(e){return typeof e=="object"&&e!=null&&"language"in e}function t4p(e){return typeof e=="object"&&e!=null&&"sdk"in e}function r4p(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function i4p(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Awo(e){return typeof e=="object"&&e!=null&&"event"in e}function r2s(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Awo)}function Mri(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function n4p(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var qwo=class extends Mp{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[U6p]}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 Mri(u)?[n,{type:"filenameWithData",filename:u.filename,data:S_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>Mri(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:S_.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 Mwo.UnreachableCaseError(a.multipartType);return}}).filter(Cd))};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=n4p(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 Mwo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{r4p(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{r2s(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!r2s(r.response)&&i4p(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Mwo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{e4p(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})):t4p(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])=>[S_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[S_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[S_.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 Cra=class extends Mp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[fwo]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>S_.api.v1.SubpackageId(p6t(r)))}};var Two=class extends Mp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[q6p]}convert(){return this.sdkMethodName}};var Cwo=class extends Mp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[T6p]}convert(){return this.isWebhook}};var Bwo=class extends Mp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[H6p]??[],...this.input[$6p]??[]],this.codeSamples.forEach(t=>{[...Object.values(S_.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 _Ei=mi(eC());function i2s(e,t){return q1(e)?sU(e,t,void 0):e}function a4p(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 cU="",oJt=class extends Mp{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&&(Mri(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>Mri(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new _Ei.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=i2s(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=i2s(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 _Ei.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(Awo)){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 _Ei.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 Mri(n)?[r,{type:"filenameWithData",filename:n.filename,data:S_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>Mri(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:S_.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 _Ei.UnreachableCaseError(i.multipartType);return}}).filter(Cd))};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 _Ei.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 _Ei.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?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Cd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Cd));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:a4p(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?nJt(this.name):this.summary!=null?nJt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function o4p(e,t){return q1(e)?sU(e,t,void 0):e}var g4p=mi(eC());var u4p="#/components/schemas/";function vhn(e){if(e.$ref.startsWith(u4p))return e.$ref.replace(u4p,"")}function x5r(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function qri(e){return typeof e.type=="string"&&e.type==="array"}function s4p(e){return e.type==="boolean"}function c4p(e){return e.type==="integer"}function Tri(e){return!Array.isArray(e.type)&&!qri(e)}function l4p(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||Tri(t)||qri(t))}function f4p(e){return"nullable"in e&&typeof e.nullable=="boolean"}function d4p(e){return e.type==="null"}function p4p(e){return e.type==="number"}function n2s(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function _4p(e){return e.type==="string"}var xwo=class extends rre{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new _M({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 XE(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 Iwo=class extends ON{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 vxe({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 zwo=class extends rre{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 _M({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Cd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>XE(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Cd).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(x5r).filter(Cd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Rwo(e){return e!=null&&e.length>0?e:[void 0]}var bhn=class extends rre{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 _M({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 _M({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(q1(t))return vhn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new _M({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Cd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return yhn(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}}}]:XE(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(Cd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Rwo(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=>S_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=mN(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new _M({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 Nwo=class extends rre{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=>mN(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>mN(t,this.context.document)?.type!=="null"?new _M({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Cd);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=mN({$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 _M({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(Cd);return this.isNullable&&n!=null?n.map(x5r).filter(Cd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:S_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>XE(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??nJt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Cd)).filter(Cd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>XE(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?nJt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?nJt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Cd)).filter(Cd)}:void 0,i=this.isNullable?x5r(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 Fwo=class extends ON{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 Cri=class extends ON{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(q1(r)){let n=mN(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(Cd),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 h4p=mi(eC());function $_D(e){return k7s.includes(e)}var Lwo=class extends ON{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&&($_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${k7s.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 h4p.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 Uwo=class extends ON{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return x5r({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var y4p=mi(eC());function G_D(e){return Z7s.includes(e)}var Vwo=class extends ON{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&&(G_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Z7s.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 y4p.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 v4p=mi(eC());function Q_D(e){return e2s.includes(e)}var Wwo=class extends ON{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 v4p.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&&(Q_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${e2s.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new Cri({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 b4p=mi(eC());var Hwo=class extends ON{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,b4p.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var hEi=class extends rre{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=vhn(this.input);let t=mN(this.input,this.context.document);t?.enum!=null&&Tri(t)&&(this.maybeEnumConverterNode=new Cri({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:S_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=mN(this.input,this.context.document);if(r!=null)return new _M({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var _M=class e extends rre{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 vxe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),Tri(this.input)&&f4p(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),q1(this.input)){let t=vhn(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 hEi({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 Iwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(l4p(this.input))this.typeShapeNode=new zwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Tri(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new Nwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(n2s(this.input)&&this.input.allOf!=null)this.typeShapeNode=new bhn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Tri(this.input)&&this.input.enum!=null)this.typeShapeNode=new Cri({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string")switch(this.input.type){case"object":n2s(this.input)&&(this.typeShapeNode=new bhn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":qri(this.input)&&(this.typeShapeNode=new xwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":s4p(this.input)&&(this.typeShapeNode=new Fwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":c4p(this.input)&&(this.typeShapeNode=new Lwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":p4p(this.input)&&(this.typeShapeNode=new Vwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":_4p(this.input)&&(this.typeShapeNode=new Wwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":d4p(this.input)&&(this.typeShapeNode=new Uwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;default:new g4p.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 bhn({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 Hwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!q1(this.input)&&(!qri(this.input)&&this.input==null||qri(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=XE(t)?.map(i=>this.nullable?x5r(i):i).filter(Cd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function Bri(e){if(e!=null)return yhn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Cd))}var uJt=class extends ON{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;q1(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 vxe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new _M({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=o4p(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 O4p(e,t){return q1(e)?sU(e,t,void 0):e}var a2s=mi(eC());function $wo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[S_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var m4p=mi(C$u(),1),ghn=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=m4p.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 J_D(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var Ohn=class extends Mp{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 _M({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),J_D(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(q1(r)?n=_wo(r.$ref,this.context.document):n=r,n!=null)return[t,new _hn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Cd)))}convert(){if(this.typeSchemas!=null)return{auths:Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[S_.api.latest.AuthSchemeId(t),i]}).filter(Cd)),types:Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=XE(r.convert());return n==null?[t,void 0]:[S_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Cd(r)))}}};var Gwo=class extends _M{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=mN(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${q1(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=mN(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 Qwo=class extends Mp{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=mN(this.input.schema,this.context.document);this.availability=new vxe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=q1(this.input.schema)?new hEi({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=ghn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new _M({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 Gwo({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Cd))):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?{[cU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:XE(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=p6t([this.method,this.path,this.contentType,"request"].join("_"));return $wo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:S_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new a2s.UnreachableCaseError(n);return}}).filter(Cd)}convert(){if(this.schema instanceof hEi)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:S_.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:S_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=XE(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:S_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new a2s.UnreachableCaseError(n.multipartType),[]}}).filter(Cd).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 Jwo=class extends Mp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=O4p(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 Qwo({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])=>XE(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Cd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>XE(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Cd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var P4p={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 j4p(e,t){if(q1(e)){let r=sU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Kwo=mi(eC());var w4p="application/json";var S4p="application/octet-stream";function D4p(e,t){return e===t||t===cU||e===cU}var Bra=class extends Mp{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)D4p(l,a)&&(i.add(l),this.examples?.push(new oJt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Ari(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[cU];if(a!=null)for(let u of a)this.examples?.push(new oJt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,Ari(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=ghn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=w4p,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 _M({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=S4p,this.contentSubtype=mN(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 _M({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=O2(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[cU]??=[],r[cU]=[{value:this.input.example}]);let i=mN(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=O2(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[cU]??=[],r[cU]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[cU]??=[],r[cU]?.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!==cU).map(([f,s])=>[l,f,s]));let u=Object.entries(r).filter(([l,f])=>!n.has(l)&&Cd(f)&&l!==cU);this.matchExamplesByIndex(a,u),!n.has(cU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return XE(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Kwo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return XE(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=p6t([this.method,this.path,this.statusCode,"response"].join("_"));return $wo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:S_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Kwo.UnreachableCaseError(i);return}}).filter(Cd)}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 Kwo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var xra=class extends Mp{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=j4p(this.input,this.context.document);if(r==null){this.context.errors.error({message:q1(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 uJt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new Bra({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 Bra({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(Cd)}};var Ywo=class extends Mp{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 xra({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 xra({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 Rwo(Bri(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(Cd))})))}).filter(Cd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=XE(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??P4p[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(Cd)})).filter(Cd)})).filter(Cd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var xri=class extends Mp{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 oJt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,Ari(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 vxe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=aJt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Cwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(q1(i)){let a=Ewo(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 uJt({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 uJt({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 uJt({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 Bwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Jwo({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 Ywo({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 hhn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new Cra({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 Cra({input:{[fwo]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Two({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>jwo({namespace:XE(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,isWebhook:this.isWebhook})).filter(Cd),this.xFernExamplesNode=new qwo({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(Cd)}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:S_.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(Cd),n=Z6p(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:X6p(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:S_.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:Bri(this.queryParameters)?.flat(),headers:Bri(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Cd)}}).filter(Cd);let a=this.servers?.map(o=>o.convert()).filter(Cd),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(Cd);return this.endpointIds.map((o,c)=>({id:S_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>S_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>S_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:Bri(this.pathParameters)?.flat(),queryParameters:Bri(this.queryParameters)?.flat(),requestHeaders:Bri(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 mhn=class extends Mp{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=aJt(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 xri({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 xri({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 xri({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 xri({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 xri({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(Cd)}};function Xwo(e){return"payloads"in e}var Zwo=class extends Mp{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 mhn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:aJt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Cd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Xwo(a)?r[S_.WebhookId(a.id)]=a:t[S_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var kwo=class extends Mp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[M6p]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Ewo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new uJt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return yhn(this.globalHeaders,this.requiredProperties)?.flat()}};function E4p(e,t){if(q1(e)){let r=sU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var e1o=class extends Mp{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=E4p(a,this.context.document);if(u!=null)return new mhn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Cd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Xwo(i)&&(t[S_.WebhookId(i.id)]=i)}),t),{})}};var t1o=class extends Mp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=aJt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new hhn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Dwo({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 Zwo({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 e1o({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 Ohn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new kwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=tBe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=swo({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:S_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:u!=null?{...u,...this.context.generatedTypes}:{},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var Phn=class extends dhn{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 bxe(e){return typeof e=="object"&&Cd(e)&&"$ref"in e&&typeof e.$ref=="string"}function g6t(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:(bxe(n)&&(n=g6t(n,t,r)),n)}function A4p(e,t){return bxe(e)?g6t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var C4p=mi(eC());function I5r(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]=I5r(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>I5r(t)):[I5r(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 I5r(e.oneOf[0]);if(e.anyOf?.[0]!=null)return I5r(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,I5r(r));return t}}function Ira(e,t){return bxe(e)?g6t(e,t,{name:"",schema:{type:"object"}}):e}function M4p(e,t){return bxe(e)?g6t(e,t,void 0):e}function q4p(e,t){return bxe(e)?g6t(e,t,void 0):e}function T4p(e,t){return bxe(e)?g6t(e,t,void 0):e}var K_D={key:S_.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}}}},r1o=class extends Phn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Ira(this.method.result,this.context.openrpc):void 0,r=t?new _M({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=>Ira(l,this.context.openrpc)).filter(Cd)?.map(l=>{let f=new _M({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:S_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Cd),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=q4p(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=M4p(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Cd))}:void 0,responseStatusCode:200,responseBody:f.result?{type:"json",value:f.result}:void 0}}).filter(Cd)??[];if(u.length<=0){let l=I5r({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Ira(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:I5r(Ira(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:S_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:S_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[K_D],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Cd):[],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(Cd),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=T4p(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[S_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=XE(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 C4p.UnreachableCaseError(u);return}}).filter(Cd)[0];if(n)return{statusCode:200,body:n,description:r}}};var zra=class extends Phn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=aJt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=A4p(t,this.context.openrpc);r!=null&&this.methods.push(new r1o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new Ohn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=tBe(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Cd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=swo({endpoints:n});return{id:S_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var Rra=class extends lwo{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 Nra(e,t){if(e instanceof eri){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof l8))return;let r=new r6t(e.absoluteFilePath),i=await i6t({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 fhn,generatedTypes:{}},f=new t1o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=J$u(a,f.convert())}return a}var B4p=require("fs/promises");async function x4p(e,t){let r=await(0,B4p.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Rra({openrpc:i,logger:t.logger});return new zra({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function I4p(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 z4p({navigation:e,fernWorkspaces:t,visitor:r,context:i}){X_D(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await o2s({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await o2s({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function o2s({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await TUt(e,{alphabetized:Jo,api:Jo,apiName:Jo,audiences:Jo,displayErrors:Jo,snippets:Jo,summary:Jo,title:Jo,layout:Jo,icon:Jo,slug:Jo,hidden:Jo,skipSlug:Jo,paginated:Jo,playground:Jo,flattened:Jo,path:Jo,page:Jo,featureFlag:Jo,openrpc:Jo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await o2s({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:Jo,orphaned:Jo}),Y_D(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function Y_D(e){return e.api!=null}function X_D(e){return e[0]?.tab!=null}function e1e(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}R4p.default.extend(N4p.default);var Z_D=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),i1o=0,k_D=async({ir:e})=>(i1o++,`${e.apiName.snakeCase.unsafeName}-${i1o}`),ehD=async({api:e})=>(i1o++,`${e.id}-${i1o}`),O6t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=Z_D,f=k_D,s=ehD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=f,this.registerApiV2=s}#e=awo.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 qZu({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await z4p({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=xT(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,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[po.of(s)]=await VRs({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[po.of(s)]=await URs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=I4p(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=Xta(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[po.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[po.of(s)]=LRs(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=thD(this.editThisPage,s);u[d6t.PageId(s)]={markdown:o,editThisPageUrl:c?d6t.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=tO(this.docsWorkspace.absoluteFilePath,o);(await(0,n1o.stat)(c)).isDirectory()?(await rTe(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,n1o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:f}}resolveFilepath(t){if(t!=null)return tO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return xT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,u2s.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,u2s.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=To.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return To.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!To.isPage(a))return;let l=To.getPageId(a);if(l==null)return;let f=ku(this.docsWorkspace.absoluteFilePath,po.of(l));r[f]=av(t,u)}),r}getDocsBasePath(){return new URL(e1e(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?d6t.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:d6t.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:d6t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=To.V1.SlugGenerator.init(To.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=>To.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Len(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=To.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??BE(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??BE(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:To.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?rhD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let 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){return Len(r)._visit({page:async n=>this.toPageNode(n,i),apiSection:async n=>this.toApiSectionNode(n,i),section:async n=>this.toSectionNode(t,n,i),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toApiSectionNode(t,r){if(t.openrpc!=null){let s=tO(this.docsWorkspace.absoluteFilePath,po.of(t.openrpc));if(!await Nf(s))throw new Error(`OpenRPC file does not exist at path: ${s}`);let o=await x4p(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:o,apiName:t.apiName,snippetsConfig:owo(t.snippetsConfiguration)}),new qra(t,o,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let s=this.getOpenApiWorkspaceForApiSection(t),o=owo(t.snippetsConfiguration),c=await Nra(s,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:c,snippetsConfig:o,apiName:t.apiName}),new qra(t,c,r,s,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}let i=this.getFernWorkspaceForApiSection(t),n=owo(t.snippetsConfiguration),a=m2({workspace:i,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 b2(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),l=Tra(a,u,{oauth:t.playground?.oauth});return new iwo(t,l,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new B5r(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:To.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=To.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??BE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?To.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),l=i.apply({urlSlug:r.slug??BE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:l.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(f=>this.toNavigationChild(u,f,l))),authed:void 0,pointsTo:void 0,noindex:void 0,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Len(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 B5r(this.markdownFilesToFullSlugs,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:To.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??BE(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):d6t.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(dg),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:d6t.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 Len(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:d6t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function thD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${e1e(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function rhD(e){switch(e){case"beta":return To.V1.NavigationV1Availability.Beta;case"deprecated":return To.V1.NavigationV1Availability.Deprecated;case"ga":return To.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return To.V1.NavigationV1Availability.Stable;default:Zo(e)}}async function ire(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof l8?t:null))).filter(dg)}var i6s=mi(MHu(),1),ILp=mi(q1o(),1),fJt=require("fs/promises"),Q1o=require("os"),n6s=mi(require("path"),1),zLp=mi(Kk(),1),RLp=mi(xLp(),1);var QvD="etag",a6s="preview",JvD="bundle",o6s=".fern";function KvD(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s))}function J1o(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s),po.of(JvD))}function YvD(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s),po.of(QvD))}async function NLp({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,i6s.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new RLp.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],f=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=YvD();if(r){let M=await Nf(s),q;if(M&&(t.debug("Reading existing ETag"),q=(await(0,fJt.readFile)(s)).toString()),q!=null&&q===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await zLp.default.dir({prefix:"fern"}),c=Ul.of(o.path);t.debug(`Downloading docs preview bundle from ${n6s.default.join(e,f)}`);let b=await(0,i6s.fetcher)({url:`${n6s.default.join(e,f)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!b.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let g=ku(c,po.of("output.zip")),O=b.body;if(O==null)return{type:"failure"};let m=Buffer.from(O);await(0,fJt.writeFile)(g,new Uint8Array(m)),t.debug(`Wrote output.zip to ${g}`);let w=KvD();await Nf(w)&&await(0,fJt.rm)(w,{recursive:!0}),await(0,fJt.mkdir)(w,{recursive:!0}),t.debug(`rm -rf ${w}`);let A=J1o();return await(0,fJt.mkdir)(A,{recursive:!0}),await(0,ILp.default)(g,A),await(0,fJt.writeFile)(s,l),t.debug(`Downloaded bundle to ${A}`),{type:"success"}}var JLp=require("fs/promises");var s6s=mi(wGt(),1);var LLp=require("path");var Ihn=mi(Oee(),1);var ULp=`['"]([^'"]+)['"]`,FLp=new RegExp(`^${ULp}$`),XvD=new RegExp(`src={?${ULp}(?! \\+)}?`,"g"),ZvD=["img","video","audio","source","embed"];function VLp(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||WLp(e)||HLp(e)?void 0:tO(e.startsWith("/")?t:dp(r),po.of(e.replace(/^\//,"")))}function WLp(e){return/^(https?:)?\/\//.test(e)}function HLp(e){return e.startsWith("data:")}function $Lp({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=VLp(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 c6s(e,t,r,i,n){let{content:a,data:u}=(0,s6s.default)(e,{}),l=a,f=yri(a,{extensions:[FPo()],mdastExtensions:[A8r()]}),s=0;function o(c){if(c==null||WLp(c)||HLp(c))return;if((0,LLp.isAbsolute)(c)){let g=Ul.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=VLp(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return ebD(u,["image","og:image","og:logo","twitter:image"],o),rbD(u,o),xf(f,c=>{if(c.position==null)return;let{start:b,length:g}=kvD(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(M){let q=o(M);M&&q&&(m=m.replace(M,q))}function A(M){let q=$Lp({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&q!=null&&q.type==="replace"&&(m=m.replace(M,q.slug))}if(c.type==="image"){let M=Lri(c.url);w(M)}if(c.type==="mdxJsxFlowElement"||c.type==="mdxJsxTextElement")if(c.name&&ZvD.includes(c.name)){let M=c.attributes.find(q=>q.type==="mdxJsxAttribute"&&q.name==="src");if(M?.value){let q=M.value;if(typeof q!="string"){let C=q.value.match(FLp);C?.[1]&&(q=C[1])}let D=Lri(q);w(D)}}else c.attributes.forEach(M=>{if(M.type==="mdxJsxAttribute"&&M.value&&typeof M.value!="string"){let q=XvD.exec(M.value.value);if(q?.[1]){let D=Lri(q[1]);w(D)}}});if(c.type==="html"||c.type==="text"||c.type==="mdxTextExpression"){let M=/src={?['"]([^'"]+)['"](?! \+)}?/g,q;for(;(q=M.exec(c.value))!=null;){let D=Lri(q[1]);w(D)}}if(c.type==="link"&&A(Lri(c.url)),(c.type==="mdxJsxFlowElement"||c.type==="mdxJsxTextElement")&&c.name==="a"){let M=c.attributes.find(q=>q.type==="mdxJsxAttribute"&&q.name==="href");if(M?.value){let q=M.value;if(typeof q!="string"){let D=q.value.match(FLp);D?.[1]&&(q=D[1])}A(Lri(q))}}if(c.type==="html"||c.type==="text"||c.type==="mdxTextExpression"){let M=/href={?['"]([^'"]+)['"](?! \+)}?/g,q;for(;(q=M.exec(c.value))!=null;){let D=Lri(q[1]);A(D)}}m!==O&&(l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g)}),s6s.default.stringify(l,u)}function kvD(e,t){let r=e.split(`
1964
+ ${JSON.stringify(r)}"`)}}function l7p(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=u7p({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return TTe.grpc({service:a})}function f7p({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=ahn({pathParameters:r["path-parameters"],location:CTe.Service,file:i,variableResolver:f}),g=s7p({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:tre(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:pxe(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,A])=>hxe({headerKey:w,header:A,file:i})):[],pathParameters:b,encoding:ppD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,A])=>{let M=ahn({pathParameters:y6t(A),location:CTe.Endpoint,file:i,variableResolver:f}),q={...i$(A),id:"",name:i.casingsGenerator.generateName(w),displayName:A["display-name"],auth:A.auth??r.auth,idempotent:A.idempotent??r.idempotent??!1,baseUrl:A.url??r.url??e,method:A.method!=null?dpD(A.method):Cee.Post,basePath:A["base-path"]!=null?pxe(A["base-path"]):void 0,path:pxe(A.path),fullPath:pxe(A["base-path"]!=null?av(A["base-path"],A.path):i.rootApiFile["base-path"]!=null?av(i.rootApiFile["base-path"],r["base-path"],A.path):av(r["base-path"],A.path)),pathParameters:M,allPathParameters:A["base-path"]!=null?M:[...t,...b,...M],queryParameters:typeof A.request!="string"&&A.request?.["query-parameters"]!=null?Object.entries(A.request["query-parameters"]).map(([D,C])=>Ujo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof A.request!="string"&&A.request?.headers!=null?Object.entries(A.request.headers).map(([D,C])=>hxe({headerKey:D,header:C,file:i})):[],requestBody:S3p({request:A.request,file:i}),sdkRequest:q3p({service:r,request:A.request,endpoint:A,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:r7p({endpoint:A,file:i,typeResolver:a}),errors:[...m3p({errors:A.errors,file:i}),...o],userSpecifiedExamples:A.examples!=null?A.examples.map(D=>({example:t7p({service:r,endpoint:A,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:f,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>T3p({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:o7p({propertyResolver:u,file:i,endpointName:w,endpointSchema:A}),transport:c7p({file:i,serviceTransport:g,endpointDeclaration:A,sourceResolver:s})};return q.id=Og.generateEndpointId(O,q),q})}}function ahn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>lpD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function lpD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...i$(t),name:i.casingsGenerator.generateName(e),valueType:fpD({parameter:t,variableResolver:n,file:i}),location:r,variable:Enn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function fpD({parameter:e,variableResolver:t,file:r}){let i=wra({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function wra({parameter:e,variableResolver:t,file:r}){let i=Wjo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function Wjo({parameter:e,variableResolver:t,file:r}){if(Enn(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 dpD(e){switch(e){case"GET":return Cee.Get;case"POST":return Cee.Post;case"PUT":return Cee.Put;case"PATCH":return Cee.Patch;case"DELETE":return Cee.Delete;default:Zo(e)}}function hxe({headerKey:e,header:t,file:r}){let{name:i}=eJt({headerKey:e,header:t});return{...i$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function eJt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function ppD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Zo(e)}}var n$={};Ro(n$,{validateObjectExample:()=>lEi,validateTypeExample:()=>Fjo,validateTypeReferenceExample:()=>y8});var Hjo=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:Og.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:ld(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!d7p(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(!d7p(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=Og.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 d7p(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 p7p(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function $jo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function _7p({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Og.generateEndpointIdFromResolvedEndpoint(n),serviceId:Og.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:$jo({fernFilePath:n.file.fernFilepath})?void 0:Og.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 h7p({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:Og.generateEndpointIdFromResolvedEndpoint(n),serviceId:Og.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:$jo({fernFilePath:n.file.fernFilepath})?void 0:Og.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:_pD({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 _pD=({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 y7p({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=h7p({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?_7p({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 Sra={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}},r7s={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 v7p(e){return{endpoint:e["get-token"].endpoint,requestProperties:hpD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ypD({responseProperties:e["get-token"]?.["response-properties"]})}}function b7p(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:vpD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:bpD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function hpD({requestProperties:e}){if(e==null)return Sra.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?h6t(t):Sra.requestProperties.client_id,client_secret:r!=null?h6t(r):Sra.requestProperties.client_secret,scopes:i!=null?h6t(i):Sra.requestProperties.scopes}}function ypD({responseProperties:e}){return g7p({responseProperties:e,defaultValue:Sra.responseProperties})}function vpD({requestProperties:e}){if(e==null)return r7s.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?h6t(t):r7s.requestProperties.refresh_token}}function bpD({responseProperties:e}){return g7p({responseProperties:e,defaultValue:r7s.responseProperties})}function g7p({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?q5r(r):t.access_token,expires_in:i!=null?q5r(i):t.expires_in,refresh_token:n!=null?q5r(n):t.refresh_token}}function w7p({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:sXr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return cHn(e.auth,{single:a=>{let u=O7p({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:sXr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:sXr.Any,schemes:a.map(u=>O7p({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function O7p({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 Xts(s,{header:o=>_L.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=>P7p({file:r,docs:f,rawScheme:o}),bearer:o=>m7p({file:r,docs:f,rawScheme:o}),oauth:o=>j7p({file:r,docs:f,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return m7p({file:r,docs:void 0,rawScheme:void 0});case"basic":return P7p({file:r,docs:void 0,rawScheme:void 0});case"oauth":return j7p({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function m7p({file:e,docs:t,rawScheme:r}){return _L.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function P7p({file:e,docs:t,rawScheme:r}){return _L.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 j7p({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return _L.oauth({docs:t,configuration:cXr.clientCredentials(y7p({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:v7p(r),refreshTokenEndpoint:b7p(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function S7p({file:e,rawApiFileSchema:t}){if(t.version!=null)return fXr.header({header:gpD({file:e,header:t.version.header}),value:OpD({file:e,versionDeclaration:t.version})})}function gpD({file:e,header:t}){return typeof t=="string"?hxe({file:e,headerKey:t,header:{type:"string"}}):hxe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function OpD({file:e,versionDeclaration:t}){return Ljo({_enum:{default:t.default,enum:t.values},file:e})}function D7p({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:tre(f.availability),docs:f.docs,origin:f.origin,body:jpD({body:f.body,file:n}),displayName:f["display-name"]});return{availability:tre(e.availability),path:pxe(e.path),auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,f])=>hxe({headerKey:l,header:f,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?ahn({pathParameters:e["path-parameters"],location:CTe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,f])=>{let{name:s}=C5r({queryParameterKey:l,queryParameter:f}),o=n.parseTypeReference(f);return{...i$(f),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof f!="string"&&f["allow-multiple"]!=null?f["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let f=SpD({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:EpD({channel:e,example:l,pathParams:f}),...f,...DpD({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:C5r({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:CD({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:mpD({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:PpD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function mpD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?k7.exploded():k7.single()}function PpD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!ApD(e.body))return E7t.reference(CD({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Sj(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:uU({propertyKey:l,property:s}).name,wireValue:l}),value:CD({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=jra({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:uU({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:CD({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 E7t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function jpD({body:e,file:t}){return typeof e=="string"?Fee.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):wpD(e)?Fee.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Fee.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:_6t(e.extends??[]).map(r=>h8({typeName:r,file:t})),properties:[]})}function wpD(e){return e.type!=null}function SpD({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=wra({parameter:o,variableResolver:n,file:a});return{name:s,value:CD({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=y6t(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 DpD({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:eJt({headerKey:l,header:s}).name,wireValue:l}),value:CD({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 EpD({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 ApD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function i7s({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:X6r(i,{singleBaseUrl:()=>m7t.singleBaseUrl(MpD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>m7t.multipleBaseUrls(qpD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function MpD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>X6r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:E7p(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function qpD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>X6r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:ld(a.urls,u=>E7p(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function E7p(e){return e.endsWith("/")?e.slice(0,-1):e}function A7p({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:CD({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:jri({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var M7p="content";function q7p(e,t){if(e==null||e.strategy==="status-code")return S7t.statusCode();switch(e.strategy){case"property":return S7t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:M7p,wireValue:M7p})});default:Zo(e)}}function T7p({readme:e,services:t}){let r=new n7s(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 n7s=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=CpD({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:TpD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function TpD(e){let t="";e.fullPath.head.length>0&&(t=av(t,e.fullPath.head));for(let r of e.fullPath.parts)t=av(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=av(t,r.tail));return t.startsWith("/")?t:`/${t}`}function CpD({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 C7p({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Og.generateWebhookId(t.fernFilepath,u),availability:tre(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])=>hxe({headerKey:f,header:s,file:t})):[],payload:BpD({payload:l.payload,file:t}),examples:l.examples!=null?IpD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function BpD({payload:e,file:t}){return typeof e=="string"?Nee.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):Gjo(e)?Nee.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Nee.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:_6t(e.extends).map(r=>h8({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>xpD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?tre(i.availability):void 0,file:t})):[]})}function xpD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uU({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function IpD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:Gjo(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:CD({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Sj(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:CD({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function Gjo(e){return e.type!=null}function ohn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function B7p({name:e,source:t}){return LP.userDefined({file:Vjo({source:t}),name:wri.generateName(e)})}function x7p({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=zpD({type:e.proto.type});if(t!=null)return t}}function zpD({type:e}){switch(e){case"google.protobuf.Any":return LP.wellKnown(Kf.any());case"google.protobuf.Api":return LP.wellKnown(Kf.api());case"google.protobuf.BoolValue":return LP.wellKnown(Kf.boolValue());case"google.protobuf.BytesValue":return LP.wellKnown(Kf.bytesValue());case"google.protobuf.DoubleValue":return LP.wellKnown(Kf.doubleValue());case"google.protobuf.Duration":return LP.wellKnown(Kf.duration());case"google.protobuf.Empty":return LP.wellKnown(Kf.empty());case"google.protobuf.Enum":return LP.wellKnown(Kf.enum());case"google.protobuf.EnumValue":return LP.wellKnown(Kf.enumValue());case"google.protobuf.Field":return LP.wellKnown(Kf.field());case"google.protobuf.FieldCardinality":return LP.wellKnown(Kf.fieldCardinality());case"google.protobuf.FieldKind":return LP.wellKnown(Kf.fieldKind());case"google.protobuf.FieldMask":return LP.wellKnown(Kf.fieldMask());case"google.protobuf.FloatVlaue":return LP.wellKnown(Kf.floatValue());case"google.protobuf.Int32Value":return LP.wellKnown(Kf.int32Value());case"google.protobuf.Int64Value":return LP.wellKnown(Kf.int64Value());case"google.protobuf.ListValue":return LP.wellKnown(Kf.listValue());case"google.protobuf.Method":return LP.wellKnown(Kf.method());case"google.protobuf.Mixin":return LP.wellKnown(Kf.mixin());case"google.protobuf.NullValue":return LP.wellKnown(Kf.nullValue());case"google.protobuf.Option":return LP.wellKnown(Kf.option());case"google.protobuf.SourceContext":return LP.wellKnown(Kf.sourceContext());case"google.protobuf.StringValue":return LP.wellKnown(Kf.stringValue());case"google.protobuf.Struct":return LP.wellKnown(Kf.struct());case"google.protobuf.Syntax":return LP.wellKnown(Kf.syntax());case"google.protobuf.Timestamp":return LP.wellKnown(Kf.timestamp());case"google.protobuf.Type":return LP.wellKnown(Kf.type());case"google.protobuf.Uint32Value":return LP.wellKnown(Kf.uint32Value());case"google.protobuf.Uint64Value":return LP.wellKnown(Kf.uint64Value());case"google.protobuf.Value":return LP.wellKnown(Kf.value())}}function I7p({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=aI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&D1(a.declaration)){let u=aI(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 mq.object({extends:_6t(a.declaration.extends).map(f=>h8({typeName:f,file:t})),properties:bra({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function z7p({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return qTe(i)?I7p({generic:i,file:t,typeResolver:r}):mq.alias({aliasOf:t.parseTypeReference(e),resolvedType:RpD({aliasOf:i,file:t,typeResolver:r})})}function RpD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return yL.primitive(i.originalTypeReference.primitive);case"container":return yL.container(i.originalTypeReference.container);case"unknown":return yL.unknown();case"named":{let n=D1(i.declaration)?D7t.Object:PXr(i.declaration)?D7t.Union:T7t(i.declaration)?D7t.Enum:Ann(i.declaration)?D7t.UndiscriminatedUnion:Zo(i.declaration);return yL.named({name:i.name,shape:n})}}}function R7p({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 mq.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function N7p(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 o7s({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new a7s}){let n=KR(e,{alias:u=>{let l=typeof u=="string"?u:u.type,f=aI(l);if(f!=null){let s=new Set(f.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=aI(o.typeName)?.arguments;if(D1(o.declaration)){let b=N7p(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>N7p(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=vL({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=h8({typeName:f,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t});if(qTe(o.typeName))continue;a.push(...o7s({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var a7s=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 F7p({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=i$(t),f=h8({typeName:e,file:r}),s=o7s({typeDeclaration:t,file:r,typeResolver:i}),o={};D1(t)&&(o=ohn(t.properties??{}));let c=FpD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:WpD(t),name:f,shape:NpD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:LpD({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:t7s({typeName:f,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function NpD({typeDeclaration:e,file:t,typeResolver:r}){return KR(e,{alias:i=>z7p({alias:i,file:t,typeResolver:r}),object:i=>j3p({object:i,file:t}),discriminatedUnion:i=>N3p({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>R7p({union:i,file:t}),enum:i=>mq.enum(Ljo({_enum:i,file:t}))})}function FpD({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=x7p({encoding:t.encoding});if(a!=null)return K6r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return K6r.proto(B7p({source:n,name:r}))}function LpD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?UpD(e.encoding):VpD(t)}function UpD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function VpD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function WpD(e){if(typeof e!="string"&&"inline"in e)return e.inline}var L7p="1.0.0";var Qjo=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:L7p,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints(),environments:this.ir.environments}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:Uc.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Uc.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return Uc.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Zo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Uc.ReferencedRequestBodyType.bytes();case"typeReference":return Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Zo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Uc.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return Uc.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Zo(r)}}convertFileUploadRequestBody({properties:t}){return Uc.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return Uc.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Zo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Uc.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Uc.FileUploadRequestBodyProperty.fileArray(t.key);default:Zo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=Uc.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Zo(t)}}convertContainerType(t){switch(t.type){case"list":return Uc.TypeReference.list(this.convertTypeReference(t.list));case"map":return Uc.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Uc.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Uc.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Uc.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Uc.TypeReference.literal(this.convertLiteral(t.literal));default:Zo(t)}}convertNamedType(t){return Uc.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Zo(t.shape)}}convertAlias({declaration:t,alias:r}){return Uc.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Uc.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i})}convertObjectProperties({declaration:t,properties:r}){return Uc.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Uc.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Zo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Uc.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Uc.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return Uc.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Uc.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Uc.LiteralType.boolean(t.boolean);case"string":return Uc.LiteralType.string(t.string);default:Zo(t)}}convertPrimitiveType(t){return Uc.TypeReference.primitive(t.v1)}convertUnknownType(){return Uc.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Uc.Auth.basic(r);case"bearer":return Uc.Auth.bearer(r);case"header":return Uc.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Zo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=av(r,t.fullPath.head));for(let i of t.fullPath.parts)r=av(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=av(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function U7p(e){return new Qjo(e).convert()}function V7p({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return tJt({containerType:t});switch(t.type){case"list":{let u=dT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gO.literal({literal:t.literal._visit({boolean:u=>$p.boolean(u),string:u=>$p.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return tJt({containerType:t});let u=dT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return tJt({containerType:t});let u=dT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=dT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=dT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=dT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?tJt({containerType:t}):{type:"success",example:gO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Zo(t)}}function tJt({containerType:e}){switch(e.type){case"list":return{type:"success",example:gO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gO.literal({literal:e.literal._visit({boolean:t=>$p.boolean(t),string:t=>$p.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:gO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:gO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:gO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Zo(e)}}function H7p({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return QpD({fieldName:e,validation:HpD(t.v2)});case"BASE_64":return{type:"success",example:$p.base64(Z0.BASE64),jsonExample:Z0.BASE64};case"BOOLEAN":return{type:"success",example:$p.boolean(Z0.BOOLEAN),jsonExample:Z0.BOOLEAN};case"DATE":return{type:"success",example:$p.date(Z0.DATE),jsonExample:Z0.DATE};case"DATE_TIME":return{type:"success",example:$p.datetime({datetime:new Date(Z0.DATE_TIME),raw:Z0.DATE_TIME}),jsonExample:Z0.DATE_TIME};case"DOUBLE":return JpD({fieldName:e,validation:$pD(t.v2)});case"FLOAT":return{type:"success",example:$p.float(Z0.FLOAT),jsonExample:Z0.FLOAT};case"INTEGER":return KpD({fieldName:e,validation:GpD(t.v2)});case"UINT_64":return{type:"success",example:$p.uint64(Z0.INT64),jsonExample:Z0.INT64};case"UINT":return{type:"success",example:$p.uint(Z0.UINT),jsonExample:Z0.UINT};case"BIG_INTEGER":return{type:"success",example:$p.bigInteger(Z0.INT64.toString()),jsonExample:`${Z0.INT64}`};case"LONG":return{type:"success",example:$p.long(Z0.INT64),jsonExample:Z0.INT64};case"UUID":return{type:"success",example:$p.uuid(Z0.UUID),jsonExample:Z0.UUID};default:Zo(t.v1)}}function HpD(e){if(e?.type==="string")return e.validation}function $pD(e){if(e?.type==="double")return e.validation}function GpD(e){if(e?.type==="integer")return e.validation}function W7p(e){if(e<=Z0.SAMPLE_STRINGS.length){let t=Z0.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Z0.SAMPLE_STRINGS[Z0.SAMPLE_STRINGS.length-1]+".".repeat(e-Z0.SAMPLE_STRINGS.length)}function QpD({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=W7p(i);return{type:"success",example:$p.string({original:a}),jsonExample:a}}else if(n){let a=W7p(n);return{type:"success",example:$p.string({original:a}),jsonExample:a}}}let r=e??Z0.STRING;return{type:"success",example:$p.string({original:r}),jsonExample:r}}function JpD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$p.double(r),jsonExample:r};if(i)return{type:"success",example:$p.double(i),jsonExample:i}}return{type:"success",example:$p.double(Z0.DOUBLE),jsonExample:Z0.DOUBLE}}function KpD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$p.integer(r),jsonExample:r};if(i)return{type:"success",example:$p.integer(i),jsonExample:i}}return{type:"success",example:$p.integer(Z0.INT),jsonExample:Z0.INT}}function dT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let l=Dra({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:f,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ab.named({shape:f,typeName:u.name})},jsonExample:s}}case"container":{let u=V7p({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=tJt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ab.container(s)},jsonExample:o}}let{example:l,jsonExample:f}=u;return{type:"success",example:{jsonExample:f,shape:ab.container(l)},jsonExample:f}}case"primitive":{let{jsonExample:u,example:l}=H7p({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ab.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ab.unknown(u)},jsonExample:u}}}}function uhn({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function Dra({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=dT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:f}=u;return{type:"success",example:Ej.alias({value:l}),jsonExample:f}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Ej.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${c.typeId}`);let g=Dra({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let f=$7p({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:s,jsonExample:o}=f;return{type:"success",example:Ej.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let f=dT({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure"){++u;continue}let{example:s,jsonExample:o}=f;return{type:"success",example:Ej.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let s=dT({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[f.name.wireValue]=s.jsonExample)}for(let f of r.shape.types){let s=f.shape._visit({noProperties:()=>({type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)throw new Error(`Failed to find type declaration with id ${o.typeId}`);if(c.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${c.shape.type}`);let b=$7p({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:c.shape,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.samePropertiesAsObject({typeId:c.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=dT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Ej.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:QR.singleProperty(b)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function $7p({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},f=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=dT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!uhn({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;f.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Ej.object({properties:f}),jsonExample:l}}var u7s=S1.primitive({v1:Gb.String,v2:yP.string({default:void 0,validation:void 0})});function Era({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:QM.ok(uT.body(void 0)),docs:void 0},l=[{params:t.pathParameters,add:s=>u.endpointPathParameters.push(s)},{params:r.pathParameters,add:s=>u.servicePathParameters.push(s)},{params:e.pathParameters,add:s=>u.rootPathParameters.push(s)}];for(let s of l)for(let o of s.params){let c=dT({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}for(let s of t.queryParameters){if(n&&uhn({typeDeclarations:i,typeReference:s.valueType}))continue;let o=dT({fieldName:s.name.name.originalName,currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:s.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:c}=o;u.queryParameters.push({name:s.name,shape:s.allowMultiple?k7.exploded():k7.single(),value:c})}let f=[{params:t.headers,add:s=>u.endpointHeaders.push(s)},{params:r.headers,add:s=>u.serviceHeaders.push(s)}];for(let s of f)for(let o of s.params){if(n&&uhn({typeDeclarations:i,typeReference:o.valueType}))continue;let c=dT({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let s={},o=[];if(t.requestBody.extends!=null)for(let c of t.requestBody.extends){let b=i[c.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${c.typeId}`);let g=Dra({typeDeclaration:b,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});g.type==="success"&&Object.assign(s,g.jsonExample)}for(let c of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=dT({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!uhn({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:g,jsonExample:O}=b;o.push({name:c.name,originalTypeDeclaration:void 0,value:g}),s[c.name.wireValue]=O}u.request=pH.inlinedRequestBody({jsonExample:s,properties:o});break}case"reference":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.request=pH.reference(o);break}default:Zo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"streamParameter":{let s;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1});break;default:Zo(t.response.body.nonStreamResponse)}if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"streaming":{let s;switch(t.response.body.value.type){case"sse":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.sse([{data:{...o,jsonExample:c},event:""}]));break}case"json":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.stream([{...o,jsonExample:c}]));break}case"text":{if(s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.stream([{...o,jsonExample:c}]));break}default:Zo(t.response.body.value)}break}case"text":{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:u7s,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=QM.ok(uT.body({...o,jsonExample:c}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Zo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=QM.error({body:void 0,error:a.declaration.name});else{let s=dT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.response=QM.error({body:o,error:a.declaration.name})}try{return{type:"success",example:{id:Njo(u),url:YpD(t,u),...u},jsonExample:void 0}}catch(s){return{type:"failure",message:`Parse failure with exceptions ${s}`}}}function YpD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function G7p(e,t){let r=t[e];if(r==null)throw new P6r(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Q7p(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,ZpD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>XpD({endpoint:i,ir:e}))}]))}}function XpD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>J7p(r,t))}}}function ZpD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>J7p(r,t))}}}return e}function J7p(e,t){let r=s7s(e.typeId,t);return K7p({objectTypeDeclaration:r,ir:t})}function s7s(e,t){let r=G7p(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return s7s(r.shape.resolvedType.name.typeId,t)}throw new P6r(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function K7p({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=s7s(i.typeId,t);return K7p({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function X7p({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:OI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?QR.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=OI({filteredIr:e,exampleTypeReference:r});return i!==void 0?QR.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function OI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ab.container(gO.list({...i,list:i.list.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ab.container(gO.set({...i,set:i.set.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?OI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ab.container(gO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?OI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ab.container(gO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ab.container(gO.map({...i,map:i.map.map(n=>{let a=OI({filteredIr:e,exampleTypeReference:n.key}),u=OI({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=OI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ab.named({...r,shape:Ej.enum(i)})}),object:i=>({...t,shape:ab.named({...r,shape:Ej.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:OI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=X7p({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=OI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ab.named({...r,shape:Ej.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function c7s({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function kpD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Y7p({filteredIr:e,headers:t}){return t.map(r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function e_D({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=OI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=OI({filteredIr:e,exampleTypeReference:r});return i!==void 0?pH.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function t_D({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>QM.ok(uT.body(i!=null?OI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>QM.ok(uT.stream(i.map(n=>OI({filteredIr:e,exampleTypeReference:n})).filter(dg))),sse:i=>QM.ok(uT.sse(i.map(({event:n,data:a})=>{let u=OI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(dg))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>QM.error({error:r,body:i!=null?OI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function l7s({filteredIr:e,example:t}){return{...t,rootPathParameters:c7s({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:c7s({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:c7s({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:Y7p({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:Y7p({filteredIr:e,headers:t.endpointHeaders}),queryParameters:kpD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?e_D({filteredIr:e,requestBody:t.request}):void 0,response:t_D({filteredIr:e,response:t.response})}}function Z7p({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=OI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Ej.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Ej.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:OI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=X7p({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Ej.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=OI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Ej.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var Jjo=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:f,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=f,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Og.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Og.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Og.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Yjo=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=r_D(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Og.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Og.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Og.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&mI(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Og.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,f=new Set;for(let s of[...t.headers,...r.headers])mI(s.valueType,u,f);for(let s of[...t.pathParameters,...r.pathParameters])mI(s.valueType,u,f);for(let s of r.queryParameters)mI(s.valueType,u,f);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=ohn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&e3._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)Kjo(o,u,f);for(let o of s.properties)mI(o.valueType,u,f);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oT(i.request.body)){let o=ohn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{mI(s,u,f)},fileUpload:({properties:s})=>{for(let o of s)Bee._visit(o,{file:Jo,bodyProperty:({valueType:c})=>{mI(c,u,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&RT._visit(r.response.body,{fileDownload:Jo,json:s=>{mI(s.responseBodyType,u,f)},streaming:s=>{s._visit({sse:o=>mI(o.payload,u,f),json:o=>mI(o.payload,u,f),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>mI(o.payload,u,f),json:o=>mI(o.payload,u,f),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&mI(s.nonStreamResponse.value.responseBodyType,u,f)},text:Jo,bytes:Jo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Og.generateErrorId(s.error)),f.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:f}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Og.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&Nee._visit(r.payload,{inlinedPayload:l=>{for(let f of l.extends)Kjo(f,a,u);for(let f of l.properties)mI(f.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!Gjo(i.payload)){let f=ohn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:f}}},reference:({payloadType:l})=>{mI(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Fee._visit(l.body,{reference:({bodyType:f})=>{mI(f,a,u)},inlinedBody:f=>{for(let s of f.extends)Kjo(s,a,u);for(let s of f.properties)mI(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(l);for(let s of f.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(l);this.addReferencedTypes(t,f.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(l);this.addReferencedTypes(t,f.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,f]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new Jjo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Zo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Og.generateSubpackageId(i))}}};function r_D(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Zo(e)}}function mI(e,t,r){S1._visit(e,{container:i=>{i_D(i,t,r)},named:i=>{Kjo(i,t,r)},primitive:Jo,unknown:Jo,_other:Jo})}function Kjo(e,t,r){t.add(Og.generateTypeId(e)),r.add(e.fernFilepath)}function i_D(e,t,r){FE._visit(e,{list:i=>{mI(i,t,r)},map:i=>{mI(i.keyType,t,r),mI(i.valueType,t,r)},optional:i=>{mI(i,t,r)},nullable:i=>{mI(i,t,r)},set:i=>{mI(i,t,r)},literal:Jo,_other:Jo})}function k7p({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:Pri({referencedIn:t,importPath:l})}}var dEi=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 dN(this.workspace,(n,a,u)=>{let l=Ab({relativeFilepath:n,definitionFile:a,casingsGenerator:wri,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})}),KSi(this.workspace,(n,a)=>{let u=Ab({relativeFilepath:n,definitionFile:a,casingsGenerator:wri,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 TPi().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=k7p({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var pEi=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=Kwe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Ab({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Xwe=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(Sj(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(`\\${xWt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(xWt))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(xWt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(xWt.length),exampleName:n}}};var Xjo=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:Iee.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:Iee.query(Ujo({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:Iee.body(u)}}if(oT(i.body)){let u=X3s({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Iee.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:Iee.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Y3s({typeResolver:this.typeResolver,file:Ora(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 Bw=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=Kwe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=Hte(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=aI(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:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Ab({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return vL({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:S1.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:S1.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:S1.container(FE.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:S1.container(FE.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:S1.container(FE.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:S1.container(FE.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:S1.container(FE.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:S1.container(FE.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(mXr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=Pra({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||Hte(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 b6t=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:T5r({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 Zjo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function m2({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:f,context:s,fdrApiDefinitionId:o,sourceResolver:c}){let b=ZQt({generationLanguage:t,keywords:r,smartCasing:i}),g=new Yjo(a),O=T5r({casingsGenerator:b,rootApiFile:e.definition.rootApiFile.contents}),m=(e.definition.rootApiFile.contents.errors??[]).map(St=>({error:jri({errorName:St,file:O}),docs:void 0})),w=new Bw(e),A=new dEi(e),M=new Xjo(w,A),q=new pEi(e),D=new Xwe(w),C=new b6t,F={fdrApiDefinitionId:o,apiVersion:S7p({file:O,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:b.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:xjo(e.definition.rootApiFile.contents.docs),auth:w7p({rawApiFileSchema:e.definition.rootApiFile.contents,file:O,propertyResolver:M,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([St,ut])=>hxe({headerKey:St,header:ut,file:O})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([St,ut])=>hxe({headerKey:St,header:ut,file:O})):[],types:{},errors:{},services:{},constants:p7p(b),environments:i7s({casingsGenerator:b,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:q7p(e.definition.rootApiFile.contents["error-discrimination"],O),basePath:e.definition.rootApiFile.contents["base-path"]!=null?pxe(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:ahn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:O,location:CTe.Root,variableResolver:C}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([St,ut])=>({docs:typeof ut!="string"?ut.docs:void 0,id:St,name:O.casingsGenerator.generateName(St),type:O.parseTypeReference(ut)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},$=new Hjo,I=St=>{$.addSubpackage(St.fernFilepath),wj(St.definitionFile,{imports:Jo,docs:ut=>{ut!=null&&$.addDocs(St.fernFilepath,ut)},types:ut=>{if(ut!=null)for(let[ge,Pe]of Object.entries(ut)){if(qTe(ge))continue;let wt=F7p({typeName:ge,typeDeclaration:Pe,file:St,typeResolver:w,exampleResolver:D,sourceResolver:c,workspace:e}),Ot=wt.typeDeclaration;n.disabled&&(Ot.userProvidedExamples=[],Ot.autogeneratedExamples=[]);let vr=wt.descendantFilepaths,ur=Og.generateTypeId(Ot.name);F.types[ur]=Ot,$.addType(ur,Ot),g.addType({declaredTypeName:Ot.name,descendantTypeIds:Ot.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:vr}),g.markTypeForAudiences(Ot.name,P3p(Pe))}},errors:ut=>{if(ut==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[Pe,wt]of Object.entries(ut)){let Ot=A7p({errorName:Pe,errorDeclaration:wt,file:St,typeResolver:w,exampleResolver:D,workspace:e}),vr=Og.generateErrorId(Ot.name);F.errors[vr]=Ot,$.addError(vr,Ot),g.addError(Ot)}},service:ut=>{if(ut==null)return;let ge=f7p({rootDefaultUrl:St.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:ut,file:St,errorResolver:q,typeResolver:w,propertyResolver:M,exampleResolver:D,sourceResolver:c,globalErrors:m,variableResolver:C,workspace:e}),Pe=Og.generateServiceId(ge.name);F.services[Pe]=ge,$.addService(Pe,ge);let wt={};ge.endpoints.forEach(Ot=>{n.disabled&&(Ot.autogeneratedExamples=[],Ot.userSpecifiedExamples=[]);let vr=ut.endpoints[Ot.name.originalName];g.addEndpoint(ge,Ot,vr),wt[Ot.name.originalName]=Ot}),ut.audiences!=null&&g.markEndpointForAudience(ge.name,ge.endpoints,ut.audiences),Object.entries(ut.endpoints).map(([Ot,vr])=>{let ur=wt[Ot];ur!=null&&vr.audiences!=null&&g.markEndpointForAudience(ge.name,[ur],vr.audiences)})},webhooks:ut=>{if(ut==null)return;let ge=Og.generateWebhookGroupId(St.fernFilepath),Pe=C7p({webhooks:ut,file:St,typeResolver:w,exampleResolver:D,workspace:e}),wt={};for(let Ot of Pe)wt[Ot.name.originalName]=Ot;Object.entries(ut).forEach(([Ot,vr])=>{let ur=wt[Ot];ur!=null&&(g.addWebhook(St,ur,vr),vr.audiences!=null&&g.markWebhookForAudiences(St,ur,vr.audiences))}),F.webhookGroups[ge]=Pe,$.addWebhookGroup(ge,St.fernFilepath)},channel:ut=>{if(ut==null)return;let ge=Og.generateWebSocketChannelId(St.fernFilepath),Pe=D7p({channel:ut,file:St,variableResolver:C,typeResolver:w,exampleResolver:D,workspace:e});g.addChannel(St,ge,Pe,ut),ut.audiences!=null&&g.markChannelForAudiences(St,ge,ut.audiences),F.websocketChannels!=null&&(F.websocketChannels[ge]=Pe,$.addWebSocketChannel(ge,St.fernFilepath))}})};dN(e,(St,ut,ge)=>{I(Ab({relativeFilepath:St,definitionFile:ut,casingsGenerator:b,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:ge.defaultUrl}))}),KSi(e,(St,ut)=>{if(ut.navigation!=null)if(typeof ut.navigation=="string")$.addPackageRedirection({from:ere({relativeFilepath:St,casingsGenerator:b}),to:ere({relativeFilepath:Ez(Zqe(St),Wh.of(ut.navigation)),casingsGenerator:b})});else{let ge=ut.navigation.map(Pe=>Og.generateSubpackageId(ere({relativeFilepath:Ez(Zqe(St),Wh.of(Pe)),casingsGenerator:b})));St===m1?$.sortRootPackage(ge):$.sortSubpackage(Og.generateSubpackageId(ere({relativeFilepath:St,casingsGenerator:b})),ge)}}),F.serviceTypeReferenceInfo=a_D(g);let U=n.disabled?F:n_D({ir:F,context:s,exampleGeneration:n}),H=e.definition.rootApiFile.contents,te=i7s({casingsGenerator:b,rawApiFileSchema:H}),J=te?.environments._visit({singleBaseUrl:St=>St.environments.filter(ut=>Zjo(ut.id,H.environments)!=null).length===0,multipleBaseUrls:St=>St.environments.filter(ut=>Zjo(ut.id,H.environments)!=null).length===0,_other:()=>!1});te?.environments.environments.forEach(St=>{g.markEnvironmentForAudiences(St,Zjo(St.id,H.environments)??[],J)});let ee=g.hasNoAudiences()?void 0:g.build(),fe=o_D(U,ee),me=e.definition.rootApiFile.contents.auth!=null&&Object.values(fe.services).every(St=>St.endpoints.every(ut=>ut.auth)),ve=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.response?.body?.type==="streaming")),we=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.pagination!=null)),Xe=Object.values(fe.services).some(St=>St.endpoints.some(ut=>ut.response?.body?.type==="fileDownload")),Mt={isAuthMandatory:me,hasStreamingEndpoints:ve,hasPaginatedEndpoints:we,hasFileDownloadEndpoints:Xe,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}},De=u!=null?T7p({readme:u,services:F.services}):void 0,{types:Te,services:It}=Q7p(fe),Ee={...fe,...$.build(ee),types:Te,services:It,sdkConfig:Mt,readmeConfig:De};return{...Ee,dynamic:U7p(Ee)}}function n_D({ir:e,context:t,exampleGeneration:r}){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){if(a.userSpecifiedExamples.length>0&&r?.skipAutogenerationIfManualExamplesExist===!0)continue;t.logger.debug(`Generating example for ${a.id}`);let u=Era({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.trace(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:l}=u;a.autogeneratedExamples=[{example:l}]}return e}function a_D(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 o_D(e,t){if(t==null)return e;let r=FOi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let f=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Z7p({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:mq.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:FOi(e.errors,u=>t.hasError(u)),services:ld(FOi(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:l7s({filteredIr:t,example:f.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(f=>({...f,example:f.example!=null?l7s({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:u_D(e.serviceTypeReferenceInfo,t)}}function u_D(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 e2p(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var r2p=mi(OUn(),1);var t2p=["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 Zwe(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,r2p.default)(e,{special:t2p}).replace(/V\s(\d)/g,"V$1")}function Ara(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&e2p(e),r._other(e))}}}function rJt(e){return typeof e.subpackageId=="string"}function tC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function yxe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var f7s="__package__",Dri=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 rJt(t)?t.subpackageId:f7s}getSubpackageByIdOrLocator(t){if(t==null)return;let r=g2.SubpackageId(t);return r===f7s?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=g2.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} ${tC(u.path.parts)}`),f.push(`${o} ${yxe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${av(c.baseUrl,tC(u.path.parts))}`),f.push(`${o} ${av(c.baseUrl,yxe(u.path.parts))}`);let b=kjo(c);b!=null&&(f.push(`${o} ${av(b,tC(u.path.parts))}`),f.push(`${o} ${av(b,yxe(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} ${tC(u.path.parts)}`),f.push(`${o} ${yxe(u.path.parts)}`),u.environments.forEach(c=>{f.push(`${o} ${av(c.baseUrl,tC(u.path.parts))}`),f.push(`${o} ${av(c.baseUrl,yxe(u.path.parts))}`);let b=kjo(c);b!=null&&(f.push(`${o} ${av(b,tC(u.path.parts))}`),f.push(`${o} ${av(b,yxe(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=rJt(t)?[...r,t.name]:r,n=i.length===0?[f7s]: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 To.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return To.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return To.WebhookId(`${r}.${t.id}`)}};function kjo(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 shn=mi(zPo(),1),n2p=mi(RPo(),1);function i2p(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{}}shn.default.extend(n2p.default);var s_D="Changelog",c_D=["summary","index","overview"],B5r=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??s_D,i=[],n;for(let b of this.changelogFiles??[]){let g=V$u(b.split("/"));if(g==null)continue;let O=i2p(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&c_D.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:To.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??BE(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=shn.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=d7s(l,b=>b.date,"desc"),s=n!=null?To.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=shn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return d7s(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=shn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return d7s(Array.from(n.entries()).map(([a,u])=>{let l=(0,shn.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 xT(this.docsWorkspace.absoluteFilePath,t)}};function d7s(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 ewo(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>To.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:To.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Mra({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=To.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Mra({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),f=i(l,u);return{...e,children:f,pointsTo:void 0}}return e}function chn({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:To.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function two({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return chn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function iJt(e,t){if(t!=null)return xT(e.absoluteFilePath,t)}function rwo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a}){let u=To.V1.PageId(iJt(e,t.absolutePath)),l=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??BE(t.title)});return{id:i.get(u),type:"page",pageId:u,title:t.title,slug:l.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var iwo=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;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){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=To.V1.ApiDefinitionId(r.id),this.#e=Dri.create(r,u),this.#u=s,this.#c=this.apiSection.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let o=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:o?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??BE(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(c=>this.#g(c)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=To.V1.followRedirects(this.#o),r=new B5r(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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#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?Dri.getSubpackageId(r):void 0;return t.map(a=>Ara(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:To.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(dg)}#f(t,r){return rwo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u})}#h(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(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=Dri.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??(rJt(a)?a.urlSlug:this.apiSection.slug??BE(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??(rJt(a)?a.displayName??Zwe(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#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??BE(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}:${BE(t.package)}`),type:"apiPackage",children:f,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#e.getSubpackageByIdOrLocator(o);return c!=null?Dri.getSubpackageId(c):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(dg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??BE(t.title),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#s(t.contents,void 0,f);return{id:a,type:"apiPackage",children:s,title:t.title,slug:f.get(),icon:t.icon,hidden: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}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=Dri.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=rJt(n)?n.urlSlug:"",f=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:rJt(n)?n.displayName??Zwe(n.name):this.apiSection.title,slug:f.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(g2.SubpackageId(r))?.endpoints.get(g2.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:To.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??tC(n.path.parts),slug:f.get(),icon:t.icon,hidden: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(g2.SubpackageId(r))?.webSockets.get(g2.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??tC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:To.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(g2.SubpackageId(r))?.webhooks.get(g2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(To.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??av("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return two({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>tC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return Mra({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??tC(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??tC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:To.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:To.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??Zwe(n.id),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=rJt(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:rJt(a)?a.displayName??Zwe(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return ewo(t)}mergeEndpointPairs(t){return chn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>tC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var nwo=class{api;#e={};#t={};#r={};#n={};constructor(t){this.api=t;for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${av(a.baseUrl,tC(i.path))}`]=i,this.#r[`${n} ${av(a.baseUrl,yxe(i.path))}`]=i;let u=kjo(a);u!=null&&(this.#r[`${n} ${av(u,tC(i.path))}`]=i,this.#r[`${n} ${av(u,yxe(i.path))}`]=i)}),this.#r[`${i.method} ${tC(i.path)}`]=i,this.#r[`${i.method} ${yxe(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 ${tC(i.path)}`]=i,this.#n[`STREAM ${yxe(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 p7s(e){let t=e.namespace?.map(r=>BE(r.toString()))??[];return t.push(BE(e.id.split(".").pop()??"")),e.operationId!=null?BE(e.operationId):av(t)}function _7s(e){return p7s(e)}function h7s(e){return p7s(e)}function y7s(e){return p7s(e)}var qra=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;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){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=f,this.#e=r,this.#t=new nwo(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=To.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?To.V1.PageId(iJt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let o=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:o?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??BE(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(c=>this.#m(c)),this.#O(this.#e,this.#u))}get(){let t=To.V1.followRedirects(this.#c),r=new B5r(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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0}),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=>Ara(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:To.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(dg)}#_(t,r){return rwo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?To.V1.PageId(iJt(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??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??Zwe(a.name),slug:f.get(),icon:t.icon,hidden: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??BE(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}:${BE(t.package)}`),type:"apiPackage",children:f,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#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?To.V1.PageId(iJt(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(dg);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??BE(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: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=BE(n.name),f=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??Zwe(n.name),slug:f.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#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):i.apply({urlSlug:_7s(n)});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??tC(n.path),slug:l.get(),icon:t.icon,hidden: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??tC(a.path),slug:(t.slug!=null?i.append(t.slug):i.apply({urlSlug:h7s(a)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:To.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??av("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply({urlSlug:y7s(u)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return two({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>tC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t){return Mra({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#P(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))return;let u=r.apply({urlSlug:BE(a.name)}),l={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:[],title:a.displayName??Zwe(a.name),slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#f.set(n,l),i.push(l)}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);if(this.#r.has(SA.EndpointId(n)))return;let u=r.apply({urlSlug:_7s(a)}),l={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"endpoint",method:a.method,endpointId:SA.EndpointId(n),apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(a.availability),isResponseStream:a.responses?.[0]?.body.type==="stream",title:a.displayName??tC(a.path),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let f=a.namespace[0];if(f!=null){let s=this.#f.get(f);if(s==null){this.taskContext.logger.error(`Subpackage ${f} not found in ${this.apiDefinitionId}`);return}let o=r.apply({urlSlug:BE(s.slug)});for(let c of a.namespace.slice(1)){let b=s.children.find(g=>g.type==="apiPackage"&&g.id===c.toString());o=o.append(BE(c)),b==null&&(b={id:To.V1.NodeId(`${this.apiDefinitionId}:${c}`),type:"apiPackage",children:[],title:Zwe(c),slug:o.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),b!=null&&b.type==="apiPackage"&&(s=b)}s.children.push(l)}}else i.push(l)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);if(this.#n.has(SA.WebSocketId(n)))return;let u={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webSocket",webSocketId:SA.WebSocketId(n),title:a.displayName??tC(a.path),slug:r.apply({urlSlug:h7s(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:To.V1.convertAvailability(a.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=a.namespace[0];if(l!=null){let f=this.#f.get(l);if(f==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:f.slug});for(let o of a.namespace.slice(1)){let c=f.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:To.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:Zwe(o),slug:s.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),c!=null&&c.type==="apiPackage"&&(f=c)}f.children.push(u)}}else i.push(u)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);if(this.#i.has(SA.WebhookId(n)))return;let u={id:To.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webhook",webhookId:SA.WebhookId(n),method:a.method,title:a.displayName??Zwe(a.id),slug:r.apply({urlSlug:y7s(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=a.namespace[0];if(l!=null){let f=this.#f.get(l);if(f==null)throw new Error(`Subpackage subpackage_${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:f.slug});for(let o of a.namespace.slice(1)){let c=f.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:To.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:o,slug:s.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}),c!=null&&c.type==="apiPackage"&&(f=c)}f.children.push(u)}}else i.push(u)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#D(t){let r=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t))),i=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([a,u])=>u.namespace!=null&&u.namespace[u.namespace.length-1]===SA.api.v1.SubpackageId(t)));return{id:SA.ApiDefinitionId(t),endpoints:r,websockets:i,webhooks:n,types:{},subpackages:{},auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#P(t,r){let i=t!=null?this.#D(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return ewo(t)}mergeEndpointPairs(t){return chn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>tC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var a2p=mi(require("crypto"),1);function l_D(e){return a2p.default.createHash("sha256").update(e).digest("hex")}var awo=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),l_D(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 To.V1.NodeId(this.#n(t))}};function owo(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0}}var uwo=mi(Oee(),1);var v7s=mi(Oee(),1);function o2p(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:v7s.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:v7s.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Zo(i)}}var WP=mi(Oee(),1);var Eri=mi(Oee(),1);function s2p(e){return e._visit({alias:t=>({type:"alias",value:sD(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:M3(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>Eri.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:Eri.FernRegistry.PropertyKey(r.name.wireValue),valueType:sD(r.valueType),availability:M3(r.availability)})),extraProperties:p_D(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:Eri.FernRegistry.PropertyKey(i.name.wireValue),valueType:sD(i.valueType),availability:M3(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?M3(i.availability):void 0,additionalProperties:Bc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[Eri.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:Eri.FernRegistry.PropertyKey(n.name.wireValue),valueType:sD(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:sD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function sD(e){return e._visit({container:t=>Bc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:sD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:sD(r),valueType:sD(i)}),optional:r=>({type:"optional",itemType:sD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:sD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:sD(r)}),literal:r=>Bc.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:Eri.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Bc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>d_D(t.v2),float:()=>u2p(t.v2),double:()=>u2p(t.v2),string:()=>f_D(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 f_D(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 d_D(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 u2p(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 p_D(e){return typeof e=="boolean"?e?S1.unknown():void 0:typeof e=="string"?{type:"id",value:Eri.FernRegistry.TypeId(e),default:void 0}:sD(e)}function g7s(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?h_D(r,t):[],webhooks:i!=null?__D(i):[],websockets:n!=null?[y_D(n,t)]:[],types:e.types.map(a=>WP.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>WP.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?WP.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function __D(e){return e.map(t=>({description:t.docs??void 0,id:WP.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??gUn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:sD(r.valueType),availability:M3(r.availability)})),payload:w_D(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function h_D(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>b7s({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(dg));else if(n!=null){let l=b7s({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Era({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let f=b7s({autogeneratedExample:l,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:M3(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:O_D(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?WP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?v_D({environmentsConfig:t.environments,endpoint:i}):void 0,id:WP.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??gUn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:WP.FernRegistry.PropertyKey(l.name.originalName),type:sD(l.valueType),availability:void 0})),parts:[...lhn(i.basePath),...lhn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:WP.FernRegistry.PropertyKey(l.name.originalName),type:sD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?lhn(t.basePath):[],...lhn(e.basePath),...lhn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:sD(l.valueType),availability:M3(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:sD(l.valueType),availability:M3(l.availability)})),request:i.requestBody!=null?m_D(i.requestBody):void 0,response:i.response!=null?P_D(i.response):void 0,errors:void 0,errorsV2:j_D(i.errors,t),examples:a};r.push(u)}return r}function y_D(e,t){return{auth:e.auth,availability:M3(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?WP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?b_D({environmentsConfig:t.environments,channel:e}):[],id:WP.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??gUn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:WP.FernRegistry.PropertyKey(r.name.originalName),type:sD(r.valueType),availability:void 0})),parts:lhn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:sD(r.valueType),description:r.docs,availability:M3(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:sD(r.valueType),availability:M3(r.availability)})),messages:e.messages.map(r=>({type:WP.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:S_D(r.body),description:r.docs,availability:M3(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[WP.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:WP.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function M3(e){if(e!=null)switch(e.status){case"DEPRECATED":return WP.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return WP.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return WP.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return WP.FernRegistry.Availability.Beta;default:Zo(e.status)}}function v_D({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:WP.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:WP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Zo(r)}}function b_D({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:WP.FernRegistry.EnvironmentId(i.id),baseUrl:g_D(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Zo(r)}}function g_D(e,t){return e.replace(/^[^:]+/,t)}function O_D(e){return Bc.http.HttpMethod._visit(e,{get:()=>WP.FernRegistry.HttpMethod.Get,post:()=>WP.FernRegistry.HttpMethod.Post,put:()=>WP.FernRegistry.HttpMethod.Put,patch:()=>WP.FernRegistry.HttpMethod.Patch,delete:()=>WP.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function lhn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:WP.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function m_D(e){let t=Bc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??oB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>WP.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:WP.FernRegistry.PropertyKey(i.name.wireValue),valueType:sD(i.valueType),availability:M3(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??oB.APPLICATION_JSON,shape:{type:"reference",value:sD(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:WP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:WP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:WP.FernRegistry.PropertyKey(n.name.wireValue),valueType:sD(n.valueType),contentType:n.contentType,description:n.docs,availability:M3(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(dg)},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 P_D(e){if(e.body==null)return;let t,r=Bc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:sD(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:sD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:sD(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 j_D(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:sD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:WP.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:WP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:sD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function b7s({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:Bc.ExampleTypeReferenceShape.primitive(Bc.ExamplePrimitive.string({original:f}))}}}).filter(dg),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[WP.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(Sj(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:F3t})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Bc.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=>awe._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(dg)}}function w_D(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>WP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:WP.FernRegistry.PropertyKey(t.name.wireValue),valueType:sD(t.valueType),availability:M3(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:sD(e.payloadType)},description:e.docs};default:Zo(e)}}function S_D(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>WP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:WP.FernRegistry.PropertyKey(t.name.wireValue),valueType:sD(t.valueType),availability:M3(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:sD(e.bodyType)};default:Zo(e)}}function kwe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:g7s(e.rootPackage,e),auth:o2p(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:M3(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:sD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[uwo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:s2p(a.shape),availability:M3(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[uwo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:uwo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...g7s(a,e)}}return i}var O7s=mi(Oee(),1);async function m7s({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=m2({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 b2(r,t)}),f=tji({token:i.value}),s=kwe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await f.api.v1.register.registerApiDefinition({orgId:O7s.FernRegistry.OrgId(e),apiId:O7s.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 D_D=new iEi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Tra(e,t,r){return ara(rra(kwe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),g2.ApiDefinitionId(t),D_D))}var S_={};Ro(S_,{AlgoliaSearchIndex:()=>c2p,ApiDefinitionId:()=>q2p,ApiId:()=>x2p,Availability:()=>K2p,DocsConfigId:()=>I2p,EndpointId:()=>R2p,EndpointPathLiteral:()=>Q2p,EnvironmentId:()=>z2p,FileId:()=>V2p,HttpMethod:()=>J2p,IndexSegmentId:()=>l2p,JqString:()=>H2p,OrgId:()=>C2p,PageId:()=>U2p,PayloadLocation:()=>P6p,PropertyKey:()=>$2p,PullRequestState:()=>v6p,RoleId:()=>G2p,TokenId:()=>B2p,TypeId:()=>L2p,Url:()=>W2p,VersionId:()=>T2p,WebSocketId:()=>N2p,WebhookId:()=>F2p,algolia:()=>P7s,api:()=>C7s,commons:()=>B7s,diff:()=>Y2p,docs:()=>V7s,generators:()=>H7s,git:()=>$7s,navigation:()=>J7s,sdks:()=>Y7s,snippets:()=>O6p,snippetsFactory:()=>m6p,templates:()=>X7s,tokens:()=>j6p});var P7s={};Ro(P7s,{AlgoliaSearchIndex:()=>c2p,IndexSegmentId:()=>l2p});function c2p(e){return e}function l2p(e){return e}var C7s={};Ro(C7s,{latest:()=>S7s,v1:()=>T7s});var S7s={};Ro(S7s,{AuthSchemeId:()=>f2p,WebhookHttpMethod:()=>h2p,auth:()=>j7s,commons:()=>d2p,endpoint:()=>p2p,type_:()=>_2p,webhook:()=>w7s,websocket:()=>y2p});var j7s={};Ro(j7s,{AuthSchemeId:()=>f2p});function f2p(e){return e}var d2p={};var p2p={};var _2p={};var w7s={};Ro(w7s,{WebhookHttpMethod:()=>h2p});var h2p={Get:"GET",Post:"POST"};var y2p={};var T7s={};Ro(T7s,{SubpackageId:()=>D2p,WebSocketMessageId:()=>E2p,WebSocketMessageOrigin:()=>A2p,WebhookHttpMethod:()=>M2p,commons:()=>q7s,db:()=>D7s,read:()=>A7s,register:()=>M7s});var D7s={};Ro(D7s,{endpoint:()=>v2p});var v2p={};var A7s={};Ro(A7s,{SupportedLanguage:()=>b2p,endpoint:()=>E7s,type_:()=>g2p,webhook:()=>O2p,websocket:()=>m2p});var E7s={};Ro(E7s,{SupportedLanguage:()=>b2p});var b2p={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby"};var g2p={};var O2p={};var m2p={};var M7s={};Ro(M7s,{SourceId:()=>E_D,endpoint:()=>P2p,type_:()=>j2p,webhook:()=>w2p,websocket:()=>S2p});var P2p={};var j2p={};var w2p={};var S2p={};function E_D(e){return e}var q7s={};Ro(q7s,{SubpackageId:()=>D2p,WebSocketMessageId:()=>E2p,WebSocketMessageOrigin:()=>A2p,WebhookHttpMethod:()=>M2p});function D2p(e){return e}function E2p(e){return e}var A2p={Client:"client",Server:"server"};var M2p={Get:"GET",Post:"POST"};var B7s={};Ro(B7s,{ApiDefinitionId:()=>q2p,ApiId:()=>x2p,Availability:()=>K2p,DocsConfigId:()=>I2p,EndpointId:()=>R2p,EndpointPathLiteral:()=>Q2p,EnvironmentId:()=>z2p,FileId:()=>V2p,HttpMethod:()=>J2p,JqString:()=>H2p,OrgId:()=>C2p,PageId:()=>U2p,PropertyKey:()=>$2p,RoleId:()=>G2p,TokenId:()=>B2p,TypeId:()=>L2p,Url:()=>W2p,VersionId:()=>T2p,WebSocketId:()=>N2p,WebhookId:()=>F2p});function q2p(e){return e}function T2p(e){return e}function C2p(e){return e}function B2p(e){return e}function x2p(e){return e}function I2p(e){return e}function z2p(e){return e}function R2p(e){return e}function N2p(e){return e}function F2p(e){return e}function L2p(e){return e}function U2p(e){return e}function V2p(e){return e}function W2p(e){return e}function H2p(e){return e}function $2p(e){return e}function G2p(e){return e}function Q2p(e){return e}var J2p={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var K2p={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var Y2p={};var V7s={};Ro(V7s,{latest:()=>z7s,v1:()=>L7s,v2:()=>U7s});var z7s={};Ro(z7s,{Layout:()=>Z2p,MdxEngine:()=>A_D,TwitterCardSetting:()=>k2p,commons:()=>X2p,frontmatter:()=>x7s,seo:()=>I7s});var A_D={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var X2p={};var x7s={};Ro(x7s,{Layout:()=>Z2p});var Z2p={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var I7s={};Ro(I7s,{TwitterCardSetting:()=>k2p});var k2p={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var L7s={};Ro(L7s,{commons:()=>F7s,db:()=>e6p,read:()=>t6p,write:()=>R7s});var e6p={};var t6p={};var R7s={};Ro(R7s,{DocsRegistrationId:()=>q_D,FilePath:()=>M_D});function M_D(e){return e}function q_D(e){return e}var F7s={};Ro(F7s,{ContentAlignment:()=>a6p,FontDisplay:()=>l6p,FontStyle:()=>c6p,HeaderPosition:()=>o6p,JsScriptStrategy:()=>s6p,ProgrammingLanguage:()=>r6p,SearchbarPlacement:()=>i6p,TabsPlacement:()=>n6p,TwitterCardSetting:()=>u6p,commons:()=>N7s});var N7s={};Ro(N7s,{ContentAlignment:()=>a6p,FontDisplay:()=>l6p,FontStyle:()=>c6p,HeaderPosition:()=>o6p,JsScriptStrategy:()=>s6p,ProgrammingLanguage:()=>r6p,SearchbarPlacement:()=>i6p,TabsPlacement:()=>n6p,TwitterCardSetting:()=>u6p});var r6p={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 i6p={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var n6p={Header:"HEADER",Sidebar:"SIDEBAR"};var a6p={Center:"CENTER",Left:"LEFT"};var o6p={Fixed:"FIXED",Absolute:"ABSOLUTE"};var u6p={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var s6p={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var c6p={Normal:"normal",Italic:"italic"};var l6p={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var U7s={};Ro(U7s,{read:()=>f6p,write:()=>d6p});var f6p={};var d6p={};var H7s={};Ro(H7s,{ChangelogEntryType:()=>_6p,GeneratorId:()=>T_D,GeneratorLanguage:()=>C_D,ReleaseType:()=>h6p,cli:()=>p6p,commons:()=>W7s,versions:()=>y6p});var p6p={};var W7s={};Ro(W7s,{ChangelogEntryType:()=>_6p,ReleaseType:()=>h6p});var _6p={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var h6p={Ga:"GA",Rc:"RC"};var y6p={};function T_D(e){return e}var C_D={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var $7s={};Ro($7s,{PullRequestState:()=>v6p});var v6p={Open:"open",Closed:"closed",Merged:"merged"};var J7s={};Ro(J7s,{latest:()=>G7s,v1:()=>Q7s});var G7s={};Ro(G7s,{NodeId:()=>I_D,ProductId:()=>z_D,Slug:()=>B_D,TabId:()=>x_D});function B_D(e){return e}function x_D(e){return e}function I_D(e){return e}function z_D(e){return e}var Q7s={};Ro(Q7s,{NavigationV1Availability:()=>U_D,NodeId:()=>F_D,ProductId:()=>L_D,Slug:()=>R_D,TabId:()=>N_D});function R_D(e){return e}function N_D(e){return e}function F_D(e){return e}function L_D(e){return e}var U_D={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Y7s={};Ro(Y7s,{Language:()=>b6p,VersionBump:()=>g6p,versions:()=>K7s});var K7s={};Ro(K7s,{Language:()=>b6p,VersionBump:()=>g6p});var b6p={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var g6p={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var O6p={};var m6p={};var X7s={};Ro(X7s,{PayloadLocation:()=>P6p});var P6p={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var j6p={};var fhn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Cd(e){return e!=null}var S6p=mi(OUn(),1);var w6p=["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 nJt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,S6p.default)(e,{special:w6p}).replace(/V\s(\d)/g,"V$1")}function swo({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];return i.namespace?.forEach(a=>{let u=a,l=[...n,u],f=S_.api.v1.SubpackageId(l.join("."));r[f]={id:f,name:l.join("/"),displayName:nJt(u)},n.push(u)})}),r}var cwo=class{errors=new fhn},dhn=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 D6p(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var lwo=class extends cwo{},Mp=class extends dhn{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 ${D6p(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})}}},ON=class extends Mp{},rre=class extends ON{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var E6p="x-fern-base-path",A6p="x-fern-availability",fwo="x-fern-sdk-group-name",M6p="x-fern-global-headers",q6p="x-fern-sdk-method-name";var T6p="x-fern-webhook",C6p="x-fern-access-token-locator",B6p="x-fern-basic",x6p="x-fern-username-variable-name",I6p="x-fern-password-variable-name",z6p="x-fern-bearer",R6p="x-fern-token-variable-name",N6p="x-fern-header",F6p="x-fern-header-variable-name",L6p="x-fern-server-name",U6p="x-fern-examples";var dwo=class extends Mp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[L6p]}convert(){if(this.serverName!=null)return this.serverName}};var pwo=class extends Mp{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 dwo({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:S_.EnvironmentId(t),baseUrl:this.url}}};function aJt(e,t,r,i){return[...e??[],...(t??[]).map((n,a)=>new pwo({input:n,context:r,accessPath:i,pathId:["servers",`${a}`]}))]}function q1(e){return typeof e=="object"&&Cd(e)&&"$ref"in e&&typeof e.$ref=="string"}function sU(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:(q1(n)&&(n=sU(n,t,r)),n)}function _wo(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return q1(r)?sU(r,t,void 0):r}var J6p=mi(eC());var hwo=class extends Mp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[B6p];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var ywo=class extends Mp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[I6p]}convert(){return this.passwordVariableName}};var vwo=class extends Mp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[x6p]}convert(){return this.usernameVariableName}};var bwo=class extends Mp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[z6p];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var gwo=class extends Mp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[R6p]}convert(){return this.tokenVariableName}};function V6p(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var W6p="x-bearer-format",H6p="x-code-samples",$6p="x-codeSamples";var Owo=class extends Mp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[W6p]}convert(){return this.bearerFormat}};var mwo=class extends Mp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[N6p];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Pwo=class extends Mp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[F6p]}convert(){return this.headerVariableName}};function G6p(e){return e.type==="apiKey"}var phn=class extends Mp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){G6p(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new mwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Pwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Owo({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 XE(e){if(e!=null)return Array.isArray(e)?e:[e]}function jwo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,isWebhook:a}){if(t==null)return;let u=r!=null&&t!=null?`${r}/${t}`:r??t;if(u!=null)return`${V_D(a)}${W_D(e)}.${H_D(i,n,u)}`}function V_D(e){return e?"webhook_":"endpoint_"}function W_D(e){return e!=null?XE(e)?.map(t=>p6t(t)).join("."):""}function H_D(e,t,r){return p6t(e??"")||t||p6t(r)}function Q6p(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var wwo=class extends Mp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[C6p],this.accessTokenLocator!=null&&(Q6p(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 Swo=class extends Mp{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 phn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new wwo({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=jwo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:S_.EndpointId(r),accessTokenLocator:S_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var _hn=class extends Mp{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 hwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new vwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new ywo({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 bwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new gwo({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":{V6p(this.input)?(this.authScheme="header",this.headerAuthNode=new phn({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 Swo({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 J6p.UnreachableCaseError(this.authScheme);return}}};var hhn=class extends Mp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=_wo(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 _hn({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(Cd))}};var Dwo=class extends Mp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[E6p],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 K6p(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Y6p(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function yhn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>XE(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!K6p(n))&&(u=Y6p(u,u.type==="enum"?u.default:void 0)),{key:S_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Cd)).filter(Cd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Ewo(e,t){return q1(e)?sU(e,t,void 0):e}function Ari(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function X6p(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 Z6p(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 k6p=mi(eC());var Z7s=["decimal","decimal128","double-int","double","float","sf-decimal"],k7s=["int16","int32","int64","int8","sf-integer","uint8"],e2s=["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"],t2s=["beta","pre-release","in-development","generally-available","deprecated"];function mN(e,t){return q1(e)?sU(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var vxe=class extends Mp{availability;constructor(t){super(t),this.safeParse()}parse(){if(mN(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[A6p];r!=null&&(t2s.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${t2s.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return S_.Availability.Beta;case"in-development":return S_.Availability.InDevelopment;case"generally-available":return S_.Availability.GenerallyAvailable;case"deprecated":return S_.Availability.Deprecated;case void 0:return;default:new k6p.UnreachableCaseError(this.availability);return}}};var Mwo=mi(eC());function e4p(e){return typeof e=="object"&&e!=null&&"language"in e}function t4p(e){return typeof e=="object"&&e!=null&&"sdk"in e}function r4p(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function i4p(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Awo(e){return typeof e=="object"&&e!=null&&"event"in e}function r2s(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Awo)}function Mri(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function n4p(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var qwo=class extends Mp{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[U6p]}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 Mri(u)?[n,{type:"filenameWithData",filename:u.filename,data:S_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>Mri(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:S_.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 Mwo.UnreachableCaseError(a.multipartType);return}}).filter(Cd))};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=n4p(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 Mwo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{r4p(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{r2s(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!r2s(r.response)&&i4p(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Mwo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{e4p(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})):t4p(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])=>[S_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[S_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[S_.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 Cra=class extends Mp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[fwo]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>S_.api.v1.SubpackageId(p6t(r)))}};var Two=class extends Mp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[q6p]}convert(){return this.sdkMethodName}};var Cwo=class extends Mp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[T6p]}convert(){return this.isWebhook}};var Bwo=class extends Mp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[H6p]??[],...this.input[$6p]??[]],this.codeSamples.forEach(t=>{[...Object.values(S_.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 _Ei=mi(eC());function i2s(e,t){return q1(e)?sU(e,t,void 0):e}function a4p(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 cU="",oJt=class extends Mp{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&&(Mri(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>Mri(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new _Ei.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=i2s(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=i2s(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 _Ei.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(Awo)){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 _Ei.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 Mri(n)?[r,{type:"filenameWithData",filename:n.filename,data:S_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>Mri(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:S_.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 _Ei.UnreachableCaseError(i.multipartType);return}}).filter(Cd))};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 _Ei.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 _Ei.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?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Cd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Cd));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:a4p(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?nJt(this.name):this.summary!=null?nJt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function o4p(e,t){return q1(e)?sU(e,t,void 0):e}var g4p=mi(eC());var u4p="#/components/schemas/";function vhn(e){if(e.$ref.startsWith(u4p))return e.$ref.replace(u4p,"")}function x5r(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function qri(e){return typeof e.type=="string"&&e.type==="array"}function s4p(e){return e.type==="boolean"}function c4p(e){return e.type==="integer"}function Tri(e){return!Array.isArray(e.type)&&!qri(e)}function l4p(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||Tri(t)||qri(t))}function f4p(e){return"nullable"in e&&typeof e.nullable=="boolean"}function d4p(e){return e.type==="null"}function p4p(e){return e.type==="number"}function n2s(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function _4p(e){return e.type==="string"}var xwo=class extends rre{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new _M({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 XE(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 Iwo=class extends ON{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 vxe({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 zwo=class extends rre{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 _M({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Cd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>XE(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Cd).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(x5r).filter(Cd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Rwo(e){return e!=null&&e.length>0?e:[void 0]}var bhn=class extends rre{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 _M({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 _M({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(q1(t))return vhn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new _M({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Cd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return yhn(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}}}]:XE(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(Cd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Rwo(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=>S_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=mN(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new _M({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 Nwo=class extends rre{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=>mN(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>mN(t,this.context.document)?.type!=="null"?new _M({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Cd);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=mN({$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 _M({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(Cd);return this.isNullable&&n!=null?n.map(x5r).filter(Cd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:S_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>XE(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??nJt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Cd)).filter(Cd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>XE(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?nJt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?nJt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Cd)).filter(Cd)}:void 0,i=this.isNullable?x5r(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 Fwo=class extends ON{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 Cri=class extends ON{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(q1(r)){let n=mN(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(Cd),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 h4p=mi(eC());function $_D(e){return k7s.includes(e)}var Lwo=class extends ON{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&&($_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${k7s.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 h4p.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 Uwo=class extends ON{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return x5r({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var y4p=mi(eC());function G_D(e){return Z7s.includes(e)}var Vwo=class extends ON{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&&(G_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Z7s.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 y4p.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 v4p=mi(eC());function Q_D(e){return e2s.includes(e)}var Wwo=class extends ON{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 v4p.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&&(Q_D(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${e2s.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new Cri({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 b4p=mi(eC());var Hwo=class extends ON{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,b4p.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var hEi=class extends rre{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=vhn(this.input);let t=mN(this.input,this.context.document);t?.enum!=null&&Tri(t)&&(this.maybeEnumConverterNode=new Cri({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:S_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=mN(this.input,this.context.document);if(r!=null)return new _M({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var _M=class e extends rre{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 vxe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),Tri(this.input)&&f4p(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),q1(this.input)){let t=vhn(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 hEi({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 Iwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(l4p(this.input))this.typeShapeNode=new zwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Tri(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new Nwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(n2s(this.input)&&this.input.allOf!=null)this.typeShapeNode=new bhn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Tri(this.input)&&this.input.enum!=null)this.typeShapeNode=new Cri({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string")switch(this.input.type){case"object":n2s(this.input)&&(this.typeShapeNode=new bhn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":qri(this.input)&&(this.typeShapeNode=new xwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":s4p(this.input)&&(this.typeShapeNode=new Fwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":c4p(this.input)&&(this.typeShapeNode=new Lwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":p4p(this.input)&&(this.typeShapeNode=new Vwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":_4p(this.input)&&(this.typeShapeNode=new Wwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":d4p(this.input)&&(this.typeShapeNode=new Uwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;default:new g4p.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 bhn({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 Hwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!q1(this.input)&&(!qri(this.input)&&this.input==null||qri(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=XE(t)?.map(i=>this.nullable?x5r(i):i).filter(Cd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function Bri(e){if(e!=null)return yhn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Cd))}var uJt=class extends ON{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;q1(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 vxe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new _M({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=o4p(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 O4p(e,t){return q1(e)?sU(e,t,void 0):e}var a2s=mi(eC());function $wo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[S_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var m4p=mi(C$u(),1),ghn=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=m4p.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 J_D(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var Ohn=class extends Mp{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 _M({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),J_D(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(q1(r)?n=_wo(r.$ref,this.context.document):n=r,n!=null)return[t,new _hn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Cd)))}convert(){if(this.typeSchemas!=null)return{auths:Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[S_.api.latest.AuthSchemeId(t),i]}).filter(Cd)),types:Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=XE(r.convert());return n==null?[t,void 0]:[S_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Cd(r)))}}};var Gwo=class extends _M{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=mN(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${q1(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=mN(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 Qwo=class extends Mp{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=mN(this.input.schema,this.context.document);this.availability=new vxe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=q1(this.input.schema)?new hEi({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=ghn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new _M({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 Gwo({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Cd))):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?{[cU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:XE(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=p6t([this.method,this.path,this.contentType,"request"].join("_"));return $wo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:S_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new a2s.UnreachableCaseError(n);return}}).filter(Cd)}convert(){if(this.schema instanceof hEi)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:S_.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:S_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=XE(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:S_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new a2s.UnreachableCaseError(n.multipartType),[]}}).filter(Cd).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 Jwo=class extends Mp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=O4p(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 Qwo({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])=>XE(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Cd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>XE(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Cd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var P4p={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 j4p(e,t){if(q1(e)){let r=sU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Kwo=mi(eC());var w4p="application/json";var S4p="application/octet-stream";function D4p(e,t){return e===t||t===cU||e===cU}var Bra=class extends Mp{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)D4p(l,a)&&(i.add(l),this.examples?.push(new oJt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,Ari(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 oJt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Ari(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[cU];if(a!=null)for(let u of a)this.examples?.push(new oJt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,Ari(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=ghn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=w4p,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 _M({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=S4p,this.contentSubtype=mN(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 _M({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=O2(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[cU]??=[],r[cU]=[{value:this.input.example}]);let i=mN(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=O2(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[cU]??=[],r[cU]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[cU]??=[],r[cU]?.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!==cU).map(([f,s])=>[l,f,s]));let u=Object.entries(r).filter(([l,f])=>!n.has(l)&&Cd(f)&&l!==cU);this.matchExamplesByIndex(a,u),!n.has(cU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return XE(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Kwo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return XE(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=p6t([this.method,this.path,this.statusCode,"response"].join("_"));return $wo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:S_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Kwo.UnreachableCaseError(i);return}}).filter(Cd)}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 Kwo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var xra=class extends Mp{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=j4p(this.input,this.context.document);if(r==null){this.context.errors.error({message:q1(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 uJt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new Bra({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 Bra({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(Cd)}};var Ywo=class extends Mp{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 xra({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 xra({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 Rwo(Bri(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(Cd))})))}).filter(Cd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=XE(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??P4p[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(Cd)})).filter(Cd)})).filter(Cd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var xri=class extends Mp{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 oJt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,Ari(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 vxe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=aJt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Cwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(q1(i)){let a=Ewo(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 uJt({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 uJt({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 uJt({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 Bwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Jwo({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 Ywo({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 hhn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new Cra({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 Cra({input:{[fwo]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Two({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>jwo({namespace:XE(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,isWebhook:this.isWebhook})).filter(Cd),this.xFernExamplesNode=new qwo({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(Cd)}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:S_.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(Cd),n=Z6p(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:X6p(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:S_.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:Bri(this.queryParameters)?.flat(),headers:Bri(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Cd)}}).filter(Cd);let a=this.servers?.map(o=>o.convert()).filter(Cd),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(Cd);return this.endpointIds.map((o,c)=>({id:S_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>S_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>S_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:Bri(this.pathParameters)?.flat(),queryParameters:Bri(this.queryParameters)?.flat(),requestHeaders:Bri(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 mhn=class extends Mp{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=aJt(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 xri({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 xri({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 xri({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 xri({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 xri({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(Cd)}};function Xwo(e){return"payloads"in e}var Zwo=class extends Mp{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 mhn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:aJt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Cd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Xwo(a)?r[S_.WebhookId(a.id)]=a:t[S_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var kwo=class extends Mp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[M6p]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Ewo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new uJt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return yhn(this.globalHeaders,this.requiredProperties)?.flat()}};function E4p(e,t){if(q1(e)){let r=sU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var e1o=class extends Mp{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=E4p(a,this.context.document);if(u!=null)return new mhn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Cd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Xwo(i)&&(t[S_.WebhookId(i.id)]=i)}),t),{})}};var t1o=class extends Mp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=aJt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new hhn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Dwo({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 Zwo({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 e1o({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 Ohn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new kwo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=tBe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=swo({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:S_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:u!=null?{...u,...this.context.generatedTypes}:{},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var Phn=class extends dhn{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 bxe(e){return typeof e=="object"&&Cd(e)&&"$ref"in e&&typeof e.$ref=="string"}function g6t(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:(bxe(n)&&(n=g6t(n,t,r)),n)}function A4p(e,t){return bxe(e)?g6t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var C4p=mi(eC());function I5r(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]=I5r(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>I5r(t)):[I5r(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 I5r(e.oneOf[0]);if(e.anyOf?.[0]!=null)return I5r(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,I5r(r));return t}}function Ira(e,t){return bxe(e)?g6t(e,t,{name:"",schema:{type:"object"}}):e}function M4p(e,t){return bxe(e)?g6t(e,t,void 0):e}function q4p(e,t){return bxe(e)?g6t(e,t,void 0):e}function T4p(e,t){return bxe(e)?g6t(e,t,void 0):e}var K_D={key:S_.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}}}},r1o=class extends Phn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Ira(this.method.result,this.context.openrpc):void 0,r=t?new _M({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=>Ira(l,this.context.openrpc)).filter(Cd)?.map(l=>{let f=new _M({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:S_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Cd),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=q4p(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=M4p(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Cd))}:void 0,responseStatusCode:200,responseBody:f.result?{type:"json",value:f.result}:void 0}}).filter(Cd)??[];if(u.length<=0){let l=I5r({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Ira(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:I5r(Ira(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:S_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:S_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[K_D],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Cd):[],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(Cd),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=T4p(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[S_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=XE(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 C4p.UnreachableCaseError(u);return}}).filter(Cd)[0];if(n)return{statusCode:200,body:n,description:r}}};var zra=class extends Phn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=aJt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=A4p(t,this.context.openrpc);r!=null&&this.methods.push(new r1o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new Ohn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=tBe(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Cd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=swo({endpoints:n});return{id:S_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var Rra=class extends lwo{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 Nra(e,t){if(e instanceof eri){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof l8))return;let r=new r6t(e.absoluteFilePath),i=await i6t({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 fhn,generatedTypes:{}},f=new t1o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=J$u(a,f.convert())}return a}var B4p=require("fs/promises");async function x4p(e,t){let r=await(0,B4p.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Rra({openrpc:i,logger:t.logger});return new zra({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function I4p(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 z4p({navigation:e,fernWorkspaces:t,visitor:r,context:i}){X_D(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await o2s({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await o2s({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function o2s({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await TUt(e,{alphabetized:Jo,api:Jo,apiName:Jo,audiences:Jo,displayErrors:Jo,snippets:Jo,summary:Jo,title:Jo,layout:Jo,icon:Jo,slug:Jo,hidden:Jo,skipSlug:Jo,paginated:Jo,playground:Jo,flattened:Jo,path:Jo,page:Jo,featureFlag:Jo,openrpc:Jo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await o2s({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:Jo,orphaned:Jo}),Y_D(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function Y_D(e){return e.api!=null}function X_D(e){return e[0]?.tab!=null}function e1e(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}R4p.default.extend(N4p.default);var Z_D=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),i1o=0,k_D=async({ir:e})=>(i1o++,`${e.apiName.snakeCase.unsafeName}-${i1o}`),ehD=async({api:e})=>(i1o++,`${e.id}-${i1o}`),O6t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=Z_D,f=k_D,s=ehD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=f,this.registerApiV2=s}#e=awo.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 qZu({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await z4p({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=xT(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,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[po.of(s)]=await VRs({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[po.of(s)]=await URs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=I4p(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=Xta(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[po.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[po.of(s)]=LRs(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=thD(this.editThisPage,s);u[d6t.PageId(s)]={markdown:o,editThisPageUrl:c?d6t.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=tO(this.docsWorkspace.absoluteFilePath,o);(await(0,n1o.stat)(c)).isDirectory()?(await rTe(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,n1o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:f}}resolveFilepath(t){if(t!=null)return tO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return xT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,u2s.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,u2s.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=To.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return To.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!To.isPage(a))return;let l=To.getPageId(a);if(l==null)return;let f=ku(this.docsWorkspace.absoluteFilePath,po.of(l));r[f]=av(t,u)}),r}getDocsBasePath(){return new URL(e1e(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?d6t.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:d6t.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:d6t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=To.V1.SlugGenerator.init(To.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=>To.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Len(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=To.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??BE(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??BE(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:To.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?rhD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let 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){return Len(r)._visit({page:async n=>this.toPageNode(n,i),apiSection:async n=>this.toApiSectionNode(n,i),section:async n=>this.toSectionNode(t,n,i),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toApiSectionNode(t,r){if(t.openrpc!=null){let s=tO(this.docsWorkspace.absoluteFilePath,po.of(t.openrpc));if(!await Nf(s))throw new Error(`OpenRPC file does not exist at path: ${s}`);let o=await x4p(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:o,apiName:t.apiName,snippetsConfig:owo(t.snippetsConfiguration)}),new qra(t,o,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let s=this.getOpenApiWorkspaceForApiSection(t),o=owo(t.snippetsConfiguration),c=await Nra(s,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:c,snippetsConfig:o,apiName:t.apiName}),new qra(t,c,r,s,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e).get()}let i=this.getFernWorkspaceForApiSection(t),n=owo(t.snippetsConfiguration),a=m2({workspace:i,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 b2(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),l=Tra(a,u,{oauth:t.playground?.oauth});return new iwo(t,l,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e).get()}async toChangelogNode(t,r){return new B5r(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:To.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=To.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??BE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?To.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),l=i.apply({urlSlug:r.slug??BE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:l.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(f=>this.toNavigationChild(u,f,l))),authed:void 0,pointsTo:void 0,noindex:void 0,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Len(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 B5r(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:To.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??BE(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):d6t.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(dg),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:d6t.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 Len(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:d6t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function thD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${e1e(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function rhD(e){switch(e){case"beta":return To.V1.NavigationV1Availability.Beta;case"deprecated":return To.V1.NavigationV1Availability.Deprecated;case"ga":return To.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return To.V1.NavigationV1Availability.Stable;default:Zo(e)}}async function ire(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof l8?t:null))).filter(dg)}var i6s=mi(MHu(),1),ILp=mi(q1o(),1),fJt=require("fs/promises"),Q1o=require("os"),n6s=mi(require("path"),1),zLp=mi(Kk(),1),RLp=mi(xLp(),1);var QvD="etag",a6s="preview",JvD="bundle",o6s=".fern";function KvD(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s))}function J1o(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s),po.of(JvD))}function YvD(){return ku(Ul.of((0,Q1o.homedir)()),po.of(o6s),po.of(a6s),po.of(QvD))}async function NLp({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,i6s.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new RLp.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],f=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=YvD();if(r){let M=await Nf(s),q;if(M&&(t.debug("Reading existing ETag"),q=(await(0,fJt.readFile)(s)).toString()),q!=null&&q===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await zLp.default.dir({prefix:"fern"}),c=Ul.of(o.path);t.debug(`Downloading docs preview bundle from ${n6s.default.join(e,f)}`);let b=await(0,i6s.fetcher)({url:`${n6s.default.join(e,f)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!b.ok){let M;return b.error.reason==="status-code"?M=`Failed to download docs preview bundle. Status code: ${b.error.statusCode}`:b.error.reason==="unknown"?M=`Failed to download docs preview bundle. Error: ${b.error.errorMessage}`:M=`Failed to download docs preview bundle. Error: ${b.error.reason}`,t.error(M),{type:"failure"}}let g=ku(c,po.of("output.zip")),O=b.body;if(O==null)return{type:"failure"};let m=Buffer.from(O);await(0,fJt.writeFile)(g,new Uint8Array(m)),t.debug(`Wrote output.zip to ${g}`);let w=KvD();await Nf(w)&&await(0,fJt.rm)(w,{recursive:!0}),await(0,fJt.mkdir)(w,{recursive:!0}),t.debug(`rm -rf ${w}`);let A=J1o();return await(0,fJt.mkdir)(A,{recursive:!0}),await(0,ILp.default)(g,A),await(0,fJt.writeFile)(s,l),t.debug(`Downloaded bundle to ${A}`),{type:"success"}}var JLp=require("fs/promises");var s6s=mi(wGt(),1);var LLp=require("path");var Ihn=mi(Oee(),1);var ULp=`['"]([^'"]+)['"]`,FLp=new RegExp(`^${ULp}$`),XvD=new RegExp(`src={?${ULp}(?! \\+)}?`,"g"),ZvD=["img","video","audio","source","embed"];function VLp(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||WLp(e)||HLp(e)?void 0:tO(e.startsWith("/")?t:dp(r),po.of(e.replace(/^\//,"")))}function WLp(e){return/^(https?:)?\/\//.test(e)}function HLp(e){return e.startsWith("data:")}function $Lp({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=VLp(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 c6s(e,t,r,i,n){let{content:a,data:u}=(0,s6s.default)(e,{}),l=a,f=yri(a,{extensions:[FPo()],mdastExtensions:[A8r()]}),s=0;function o(c){if(c==null||WLp(c)||HLp(c))return;if((0,LLp.isAbsolute)(c)){let g=Ul.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=VLp(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return ebD(u,["image","og:image","og:logo","twitter:image"],o),rbD(u,o),xf(f,c=>{if(c.position==null)return;let{start:b,length:g}=kvD(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(M){let q=o(M);M&&q&&(m=m.replace(M,q))}function A(M){let q=$Lp({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&q!=null&&q.type==="replace"&&(m=m.replace(M,q.slug))}if(c.type==="image"){let M=Lri(c.url);w(M)}if(c.type==="mdxJsxFlowElement"||c.type==="mdxJsxTextElement")if(c.name&&ZvD.includes(c.name)){let M=c.attributes.find(q=>q.type==="mdxJsxAttribute"&&q.name==="src");if(M?.value){let q=M.value;if(typeof q!="string"){let C=q.value.match(FLp);C?.[1]&&(q=C[1])}let D=Lri(q);w(D)}}else c.attributes.forEach(M=>{if(M.type==="mdxJsxAttribute"&&M.value&&typeof M.value!="string"){let q=XvD.exec(M.value.value);if(q?.[1]){let D=Lri(q[1]);w(D)}}});if(c.type==="html"||c.type==="text"||c.type==="mdxTextExpression"){let M=/src={?['"]([^'"]+)['"](?! \+)}?/g,q;for(;(q=M.exec(c.value))!=null;){let D=Lri(q[1]);w(D)}}if(c.type==="link"&&A(Lri(c.url)),(c.type==="mdxJsxFlowElement"||c.type==="mdxJsxTextElement")&&c.name==="a"){let M=c.attributes.find(q=>q.type==="mdxJsxAttribute"&&q.name==="href");if(M?.value){let q=M.value;if(typeof q!="string"){let D=q.value.match(FLp);D?.[1]&&(q=D[1])}A(Lri(q))}}if(c.type==="html"||c.type==="text"||c.type==="mdxTextExpression"){let M=/href={?['"]([^'"]+)['"](?! \+)}?/g,q;for(;(q=M.exec(c.value))!=null;){let D=Lri(q[1]);A(D)}}m!==O&&(l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g)}),s6s.default.stringify(l,u)}function kvD(e,t){let r=e.split(`
1965
1965
  `),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 Lri(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function ebD(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:Ihn.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:Ihn.FernRegistry.FileId(a)}:{type:"url",value:Ihn.FernRegistry.Url(n)}}}}}var tbD=xs.union([xs.string(),xs.object({light:xs.string().optional(),dark:xs.string().optional()})]);function u6s(e,t){let r=t(e);return r?{type:"fileId",value:Ihn.FernRegistry.FileId(r)}:{type:"url",value:Ihn.FernRegistry.Url(e)}}function rbD(e,t){let r=tbD.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=u6s(i,t):(i.light!=null&&(e.logo.light=u6s(i.light,t)),i.dark!=null&&(e.logo.dark=u6s(i.dark,t)))}var GLp=require("fs/promises"),QLp=mi(wGt(),1);async function ibD(e){let{content:t}=(0,QLp.default)(await(0,GLp.readFile)(e));return t}async function l6s({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=ibD}){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=tO(o.startsWith("/")?t:dp(r),po.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
1966
1966
  `).map(g=>s+g).join(`
1967
1967
  `),u=u.replace(f,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}async function KLp({domain:e,project:t,context:r,previousDocsDefinition:i,editedAbsoluteFilepaths:n}){let a=t.docsWorkspaces,u=t.apiWorkspaces;if(a==null)throw new Error("No docs workspace found in project");if(n!=null&&i!=null){let w=n.every(A=>A.endsWith(".mdx")||A.endsWith(".md"));for(let A of n){let M=xT(a.absoluteFilePath,A),q=(await(0,JLp.readFile)(A)).toString(),D=await l6s({markdown:q,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:A,context:r}),C=i.pages[SA.PageId(M)];if(C==null)continue;let F=new Map(Object.entries(i.filesV2??{}).map(([I,U])=>{let H="/"+U.url.replace("/_local/","");return[Ul.of(H),I]})),$=c6s(D,F,{},{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:A},r);i.pages[SA.PageId(M)]={markdown:$,editThisPageUrl:C.editThisPageUrl}}if(w)return i}let l=await Promise.all(u.map(async w=>await w.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),f=await ire(t),s=new f6s(r),o=new d6s(r),c={},g=await new O6t(e,a,f,l,r,void 0,async w=>w.map(A=>{let M=tBe();return c[M]={type:"url",url:To.Url(`/_local${xJu(A.absoluteFilePath)}`)},{absoluteFilePath:A.absoluteFilePath,relativeFilePath:A.relativeFilePath,fileId:M}}),async w=>s.addReferencedAPI(w),async w=>o.addReferencedAPI(w)).resolve(),O=u3s({writeShape:g,files:{}}),m=c3s({dbShape:O.config});return{apis:s.getAPIsForDefinition(),apisV2:o.getAPIsForDefinition(),config:m,files:{},filesV2:c,pages:O.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var f6s=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=tBe(),a=rra(kwe({ir:t,snippetsConfig:r,playgroundConfig:i}),SA.ApiDefinitionId(n),new iEi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=ara(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},d6s=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t,snippetsConfig:r}){try{return t.snippetsConfiguration=r,this.apis[t.id]=t,t.id}catch(i){let n=i;throw this.context.logger.debug(`Failed to read referenced API: ${n?.message} ${n?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),n.stack!=null&&this.context.logger.error(n?.stack),i}}getAPIsForDefinition(){return this.apis}};var nbD={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function _6s({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let $="https://prod-local-preview-bundle2.s3.amazonaws.com/";if($==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await NLp({bucketUrl:$,logger:i.logger,preferCached:!0})}catch($){let I=J1o();if($ instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${$.message}`),await Nf(I))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=dp(e.config._absolutePath),l=(0,p6s.default)(),f=XLp.default.createServer(l),s=new ERs.default({server:f}),o=new Set;function c($){for(let I of o)I.send(JSON.stringify($))}s.on("connection",function(I){o.add(I),I.on("close",function(){o.delete(I)})}),l.use((0,YLp.default)());let b=new URL(e1e(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),g=e,O,m=null,w=!1,A=1e3,M=async $=>{i.logger.info("Reloading docs...");let I=Date.now();try{g=await t(),i.logger.info("Validating docs..."),await r(g);let U=await KLp({domain:`${b.host}${b.pathname}`,project:g,context:i,previousDocsDefinition:O,editedAbsoluteFilepaths:$});return i.logger.info(`Reload completed in ${Date.now()-I}ms`),U}catch(U){return O==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),U instanceof Error&&(i.logger.error(U.message),U instanceof Error&&U.stack&&i.logger.debug(`Stack Trace:
@@ -1973,7 +1973,7 @@ ${U.stack}`)),O}};O=await M();let q=g.apiWorkspaces.flatMap($=>$.getAbsoluteFile
1973
1973
  `);u.push({severity:"fatal",message:A})}}}}}}),u}}}}};function dUp(e,t){let r={};for(let i of e){let n=r[t(i)]??0;r[t(i)]=n+1}return Object.entries(r).reduce((i,[n,a])=>(a>1&&i.push(n),i),[])}var B6s={name:"no-error-status-code-conflict",create:({workspace:e})=>{if(e.definition.rootApiFile.contents["error-discrimination"]?.strategy!=="status-code")return{};let t=ObD(e);return{definitionFile:{httpEndpoint:({endpoint:r})=>{if(r.errors==null)return[];let i={};for(let a of r.errors){let u=typeof a=="string"?a:a.error,l=t[u];if(l==null)continue;let f=l["status-code"];f in i?i[f]?.push(u):i[f]=[u]}let n=[];for(let[a,u]of Object.entries(i))u.length>1&&n.push({severity:"fatal",message:`Multiple errors have status-code ${a}: ${u.join(", ")}`});return n}}}}};function ObD(e){let t={};return dN(e,(r,i)=>{pU(i,{typeName:F3t,errorDeclaration:({errorName:n,declaration:a})=>{t[n]=a},httpService:F3t})}),t}var x6s={name:"no-extensions-with-file-upload",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>e.request==null?[]:MPi(e.request)?.extends==null?[]:[{severity:"fatal",message:"Request body extensions are not supported for file-upload requests."}]}})};var I6s={name:"no-get-request-body",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>e.method==="GET"&&ots(e)!=null?[{severity:"fatal",message:"Endpoint is a GET, so it cannot have a request body."}]:[]}})};var z6s={name:"no-missing-auth",create:e=>{let t=e.workspace.definition.rootApiFile.contents.auth!=null;return{definitionFile:{httpService:r=>r.auth&&!t?[{severity:"fatal",message:"Service requires auth, but no auth is defined."}]:[],httpEndpoint:({endpoint:r})=>r.auth!=null&&r.auth&&!t?[{severity:"fatal",message:"Endpoint requires auth, but no auth is defined."}]:[]}}}};var R6s={name:"no-missing-error-discriminant",create:({workspace:e})=>mbD(e)?{rootApiFile:{errorDiscrimination:t=>t!=null?[]:[{severity:"fatal",message:"error-discrimination is required because this API has declared errors."}]}}:{}};function mbD(e){for(let t of Object.values(Pti(e.definition)))if(t.contents.errors!=null&&!H$u(t.contents.errors))return!0;return!1}var N6s={name:"no-missing-request-name",create:()=>({definitionFile:{httpEndpoint:({endpoint:e,service:t})=>{if(typeof e.request!="string"&&e.request?.name!=null)return[];if(e.request!=null&&typeof e.request!="string"){if(e.request.body!=null&&oT(e.request.body))return[{severity:"fatal",message:"Request name is required because request body is defined inline"}];if(e.request["query-parameters"]!=null&&DJ(e.request["query-parameters"])>0)return[{severity:"fatal",message:"Request name is required because request has query parameters"}];if(DJ(e.request.headers)>0)return[{severity:"fatal",message:"Request name is required because request has headers"}]}return DJ(t.headers)>0?[{severity:"fatal",message:"Request name is required because service has headers"}]:[]}}})};var F6s={name:"no-object-single-property-key",create:({workspace:e})=>{let t=new Bw(e);return{definitionFile:{typeDeclaration:({declaration:r},{relativeFilepath:i,contents:n})=>{let a=[];if(!PXr(r))return a;let u=({discriminantValue:l,singleUnionType:f})=>{let s=typeof f!="string"&&f.key!=null,o=typeof f=="string"?f:f.type;return typeof o!="string"||s?typeof o!="string"&&s?[{severity:"fatal",message:`Union variant ${l} has no type, so "key" cannot be defined`}]:[]:t.resolveType({type:o,file:Ab({relativeFilepath:i,definitionFile:n,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents})})==null?[]:[]};for(let[l,f]of Object.entries(r.union))a.push(...u({discriminantValue:l,singleUnionType:f}));return a}}}}};var L6s={name:"no-response-property",create:({workspace:e})=>{let t=new Bw(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{let{response:a}=r;if(a==null)return[];let u=typeof a=="string"?a:a.type;if(u==null)return[];if(FTe(u)!=null)return[];if(sHn(u)!=null)return[];let l=typeof a!="string"?a.property:void 0;if(l==null)return[];let f=Ab({relativeFilepath:i,definitionFile:n,rootApiFile:e.definition.rootApiFile.contents,casingsGenerator:T1}),s=typeof a!="string"?a.type:a;if(s==null)return[];let o=t.resolveTypeOrThrow({type:s,file:f}),c=pUp(o,l,f,t);return PbD(c,l)}}}}},dJt;(function(e){e[e.ContainsProperty=0]="ContainsProperty",e[e.DoesNotContainProperty=1]="DoesNotContainProperty",e[e.IsNotObject=2]="IsNotObject"})(dJt||(dJt={}));function PbD(e,t){switch(e){case dJt.ContainsProperty:return[];case dJt.DoesNotContainProperty:return[{severity:"fatal",message:`Response does not have a property named ${t}.`}];case dJt.IsNotObject:return[{severity:"fatal",message:"Response must be an object in order to return a property as a response."}]}}function pUp(e,t,r,i){switch(e._type){case"container":return e.container._type!=="optional"&&e.container._type!=="nullable"?dJt.IsNotObject:pUp(e.container.itemType,t,r,i);case"named":return hUp(e.declaration)?jbD(e.declaration,t,r,i)?dJt.ContainsProperty:dJt.DoesNotContainProperty:dJt.IsNotObject;case"primitive":case"unknown":return dJt.IsNotObject;default:Zo(e)}}function jbD(e,t,r,i){return _Up(e,r,i).has(t)}function _Up(e,t,r){let i=[];typeof e.extends=="string"?i=[e.extends]:Array.isArray(e.extends)&&(i=e.extends);let n=new Set;for(let a of i)for(let u of wbD(a,t,r))n.add(u);for(let a of Object.keys(e.properties??{}))n.add(a);return n}function wbD(e,t,r){let i=r.resolveNamedTypeOrThrow({referenceToNamedType:e,file:t});return i._type==="named"&&hUp(i.declaration)?_Up(i.declaration,t,r):new Set}function hUp(e){return e.extends!=null||e.properties!=null}var U6s={name:"no-undefined-error-reference",create:({workspace:e})=>{let t=SbD(e);function r(n,a){let u=t[a];return u==null?!1:u.has(n)}let i=(n,a,u)=>{let l=Kwe({reference:n,referencedIn:a,imports:ld(u.imports??{},po.of)});return l!=null&&r(l.typeName,l.relativeFilepath)?[]:[{severity:"fatal",message:"Error is not defined."}]};return{rootApiFile:{errorReference:(n,{relativeFilepath:a,contents:u})=>i(n,a,u)},definitionFile:{errorReference:(n,{relativeFilepath:a,contents:u})=>i(n,a,u)}}}};function SbD(e){let t={};return dN(e,(r,i)=>{let n=new Set;t[r]=n,pU(i,{errorDeclaration:({errorName:a})=>{n.add(a)}})}),t}var V6s={name:"no-undefined-example-reference",create:({workspace:e})=>{let t=new Xwe(new Bw(e));return{definitionFile:{exampleTypeReference:(r,{relativeFilepath:i,contents:n})=>t.parseExampleReference(r)==null?[{severity:"fatal",message:`Example ${Su.bold(r)} is malformed. Examples should be formatted like ${Su.bold("$YourType.ExampleName")}`}]:t.resolveExample({example:r,file:Ab({relativeFilepath:i,definitionFile:n,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents})})!=null?[]:[{severity:"fatal",message:`Example ${Su.bold(r)} is not defined.`}]}}}};var H6s={name:"no-undefined-path-parameters",create:()=>({rootApiFile:{file:e=>e["base-path"]==null?[]:W6s({path:e["base-path"],pathParameters:e["path-parameters"]??{},pathType:"file"})},definitionFile:{httpService:e=>W6s({path:e["base-path"],pathParameters:e["path-parameters"]??{},pathType:"service"}),httpEndpoint:({endpoint:e})=>W6s({path:e["base-path"]!=null?av(e["base-path"],e.path):e.path,pathParameters:y6t(e),pathType:"endpoint"})}})};function W6s({path:e,pathParameters:t,pathType:r}){let i=[],n=new Set;pxe(e).parts.forEach(s=>{n.has(s.pathParameter)&&i.push({severity:"fatal",message:`${dUn(r)} has duplicate path parameter: ${Su.bold(s.pathParameter)}.`}),n.add(s.pathParameter)});let u=new Set(Object.keys(t));return yUp(n,u).forEach(s=>{i.push({severity:"fatal",message:`${dUn(r)} has missing path-parameter: ${Su.bold(s)}.`})}),yUp(u,n).forEach(s=>{i.push({severity:"fatal",message:`Path parameter is unreferenced in ${r}: ${Su.bold(s)}.`})}),i}function yUp(e,t){return new Set([...e].filter(r=>!t.has(r)))}var $6s={name:"no-undefined-type-reference",create:({workspace:e})=>{let t=DbD(e);function r(n){if(n.parsed==null)return!1;let a=t[n.parsed.relativeFilepath];if(a==null)return!1;let u=aI(n.parsed.typeName);return u!=null?u.name?a.has(u.name):!1:a.has(n.parsed.typeName)}function i(n,a){if(a!=null){let u=[...a];for(;u.length>0;){let l=u.pop(),f=l?typeof l=="string"?aI(l):aI(l.key):void 0;if(f!=null)return n.parsed?.typeName&&f.arguments?.includes(n.parsed?.typeName)}}return!1}return{definitionFile:{typeReference:({typeReference:n,location:a,nodePath:u},{relativeFilepath:l,contents:f})=>{let s=FTe(n);if(s!=null){if(a===dU.InlinedRequestProperty)return[];if(a===dU.Response)return s.isOptional?[{severity:"fatal",message:"File response cannot be optional"}]:[]}return GWt(n)!=null?a===dU.RequestReference?[]:[{severity:"fatal",message:"The bytes type can only be used as a request"}]:Cin(n)?a===dU.StreamingResponse?[]:a===dU.Response?[]:[{severity:"fatal",message:"The text type can only be used as a response or response-stream."}]:EbD({type:n,relativeFilepath:l,imports:ld(f.imports??{},po.of)}).reduce((b,g)=>(g.parsed?.typeName!=null&&FTe(g.parsed.typeName)!=null?b.push({severity:"fatal",message:"The file type can only be used as properties in inlined requests."}):g.parsed?.typeName!=null&&Cin(g.parsed.typeName)?b.push({severity:"fatal",message:"The text type can only be used as a response-stream or response."}):!r(g)&&!i(g,u)&&b.push({severity:"fatal",message:`Type ${Su.bold(g.parsed?.typeName??g.fullyQualifiedName)} is not defined.`}),b),[])}}}}};function DbD(e){let t={};return dN(e,(r,i)=>{let n=new Set;t[r]=n,pU(i,{typeDeclaration:({typeName:a})=>{if(!a.isInlined){let u=aI(a.name);u!=null&&u.name&&n.add(u.name),n.add(a.name)}}})}),t}function EbD({type:e,relativeFilepath:t,imports:r}){return vL({type:e,_default:void 0,validation:void 0,visitor:{primitive:()=>[],unknown:()=>[],map:({keyType:i,valueType:n})=>[...i,...n],list:i=>i,set:i=>i,optional:i=>i,nullable:i=>i,literal:()=>[],named:i=>{let n=Kwe({reference:i,referencedIn:t,imports:r});return[{fullyQualifiedName:i,parsed:n!=null?{typeName:n.typeName,relativeFilepath:n.relativeFilepath}:void 0}]}}})}var G6s={name:"no-undefined-variable-reference",create:({workspace:e})=>{let t=new b6t,r=(i,n)=>i.startsWith(b6t.VARIABLE_PREFIX)?t.getDeclaration(i,n)?[]:[{severity:"fatal",message:`Variable ${i} is not defined.`}]:[{severity:"fatal",message:`Variable reference must start with ${b6t.VARIABLE_PREFIX}`}];return{rootApiFile:{variableReference:i=>r(i,T5r({casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}))},definitionFile:{variableReference:(i,{relativeFilepath:n,contents:a})=>r(i,Ab({casingsGenerator:T1,relativeFilepath:n,definitionFile:a,rootApiFile:e.definition.rootApiFile.contents}))}}}};var Q6s={name:"no-unused-generic",create:({workspace:e})=>{let t=new Set;return dN(e,(r,i)=>{pU(i,{typeDeclaration:n=>{KR(n.declaration,{alias:a=>{let u=aI(typeof a=="string"?a:a.type);if(u!=null&&u.name){let[l,f,...s]=u.name.split("."),o=f??l;o&&t.add(o)}},enum:()=>{},object:()=>{},discriminatedUnion:()=>{},undiscriminatedUnion:()=>{}})}})}),{definitionFile:{typeName:r=>{let i=aI(r);return i==null?[]:i.name&&t.has(i.name)?[]:[{severity:"fatal",message:`Generic "${r}" is declared but never used.`}]}}}}};var J6s={name:"only-object-extensions",create:({workspace:e})=>{let t=new Bw(e);return{definitionFile:{extension:(r,{relativeFilepath:i,contents:n})=>{let a=t.resolveNamedType({referenceToNamedType:r,file:Ab({relativeFilepath:i,definitionFile:n,rootApiFile:e.definition.rootApiFile.contents,casingsGenerator:T1})});return a==null?[]:a._type==="named"&&D1(a.declaration)?[]:[{severity:"fatal",message:`Objects can only extend other objects, and ${r} is not an object.`}]}}}}};var K6s={name:"valid-base-path",create:()=>({rootApiFile:{file:e=>e["base-path"]!=null?vUp(e["base-path"]):[]},definitionFile:{httpService:e=>vUp(e["base-path"])}})};function vUp(e){if(e==="/"||e.length===0)return[];let t=[];return e.startsWith("/")||t.push({severity:"fatal",message:"base-path must be empty or start with a slash."}),t}var Y6s={name:"valid-default-environment",create:({workspace:e})=>{let t=e.definition.rootApiFile.contents.environments;return{rootApiFile:{defaultEnvironment:r=>r!=null&&(t==null||!Object.keys(t).includes(r))?[{severity:"fatal",message:`The default-environment ${r} is not listed as an environment`}]:[]}}}};var X6s={name:"valid-endpoint-path",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.path==="")return[];let t=[];return e.path.startsWith("/")||t.push({severity:"fatal",message:"Path must start with a slash."}),t}}})};function eSo({allDeclarations:e={},examples:t,parameterDisplayName:r,typeResolver:i,exampleResolver:n,workspace:a,getRawType:u,breadcrumbs:l}){let f=[],s=Object.entries(e).reduce((o,[c,b])=>{let g=u(b);if(g!=null){let O=i.resolveType({type:g.rawType,file:g.file});O!=null&&O._type==="container"&&(O.container._type==="optional"||O.container._type==="nullable")||O?._type==="unknown"||o.push(c)}return o},[]);for(let o of s)t?.[o]==null&&f.push({severity:"fatal",message:`Example is missing required ${r} "${o}"`});if(t!=null)for(let[o,c]of Object.entries(t)){let b=e[o];if(b==null)f.push({severity:"fatal",message:`Unexpected ${r} "${o}"`});else{let g=u(b);g!=null&&f.push(...n$.validateTypeReferenceExample({rawTypeReference:g.rawType,example:c,file:g.file,workspace:a,typeResolver:i,exampleResolver:n,breadcrumbs:l,depth:0}).map(O=>({severity:"fatal",message:O.message})))}}return f}function bUp({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[],l=typeof t.request!="string"?t.request?.body:t.request;return l==null?e!=null&&u.push({severity:"fatal",message:"Unexpected request in example."}):oT(l)?u.push(...n$.validateObjectExample({typeName:void 0,typeNameForBreadcrumb:"<Inlined Request>",rawObject:{"extra-properties":l["extra-properties"],extends:l.extends,properties:l.properties??{}},file:n,typeResolver:r,exampleResolver:i,workspace:a,example:e,breadcrumbs:["request"],depth:0}).map(f=>({severity:"fatal",message:f.message}))):u.push(...n$.validateTypeReferenceExample({rawTypeReference:typeof l=="string"?l:l.type,example:e,file:n,workspace:a,typeResolver:r,exampleResolver:i,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:"fatal",message:f.message}))),u}function OUp({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:u}){return e==null?gUp({example:{},endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:u}):qPi(t,e,{body:l=>gUp({example:l,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:u}),stream:l=>AbD({example:l,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}),events:l=>MbD({example:l,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a})})}function gUp({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:u}){let l=[];if(e.error==null)if(t.response!=null){let f=typeof t.response!="string"?t.response.type:t.response;if(f==null)return l;l.push(...n$.validateTypeReferenceExample({rawTypeReference:f,example:e.body,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(s=>({severity:"fatal",message:s.message})))}else e.body!=null&&l.push({severity:"fatal",message:`Unexpected response in example. If you're adding an example of an error response, set the "error" property to the error's name`});else{let f=u.getDeclaration(e.error,n);f!=null&&(t.errors!=null&&t.errors.some(o=>(typeof o!="string"?o.error:o)===e.error)||l.push({severity:"fatal",message:`${Su.bold(e.error)} is not specified as an allowed error for this endpoint. Add ${Su.bold(e.error)} to the endpoint's "errors" list.`}),f.declaration.type!=null?l.push(...n$.validateTypeReferenceExample({rawTypeReference:f.declaration.type,example:e.body,typeResolver:r,exampleResolver:i,file:f.file,workspace:a,breadcrumbs:["response","body"],depth:0}).map(o=>({severity:"fatal",message:o.message}))):e.body!=null&&l.push({severity:"fatal",message:`Unexpected response in example. ${Su.bold(e.error)} does not have a body.`}))}return l}function AbD({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t["response-stream"]==null)u.push({severity:"fatal",message:"Unexpected streaming response in example. Endpoint's schema is missing `response-stream` key."});else if(typeof t["response-stream"]=="string"||t["response-stream"].format==null||t["response-stream"].format==="json")for(let l of e.stream)u.push(...n$.validateTypeReferenceExample({rawTypeReference:typeof t["response-stream"]!="string"?t["response-stream"].type:t["response-stream"],example:l,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:"fatal",message:f.message})));else u.push({severity:"fatal",message:"Endpoint response expects server-sent events (`response-stream.format: sse`), but the provided example is a regular stream. Use the `events` key to provide an list of server-sent event examples."});return u}function MbD({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t["response-stream"]==null)u.push({severity:"fatal",message:"Unexpected streaming response in example. Endpoint's schema is missing `response-stream` key."});else if(typeof t["response-stream"]!="string"&&t["response-stream"].format==="sse")for(let l of e.stream)u.push(...n$.validateTypeReferenceExample({rawTypeReference:typeof t["response-stream"]!="string"?t["response-stream"].type:t["response-stream"],example:l.data,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:"fatal",message:f.message})));else u.push({severity:"fatal",message:"Endpoint response expects a regular stream, but the provided example is a server-sent event. Use the `stream` key to provide a list of stream examples."});return u}var Z6s={name:"valid-example-endpoint-call",create:({workspace:e})=>{let t=new Bw(e),r=new pEi(e),i=new Xwe(t),n=new b6t;return{definitionFile:{exampleHeaders:({service:a,endpoint:u,examples:l},{relativeFilepath:f,contents:s})=>eSo({allDeclarations:{...a.headers,...typeof u.request!="string"?u.request?.headers:void 0},examples:l,parameterDisplayName:"header",typeResolver:t,exampleResolver:i,workspace:e,getRawType:o=>({file:Ab({relativeFilepath:f,definitionFile:s,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),rawType:typeof o=="string"?o:o.type}),breadcrumbs:["headers"]}),examplePathParameters:({service:a,endpoint:u,examples:l},{relativeFilepath:f,contents:s})=>eSo({allDeclarations:qbD({workspace:e,service:a,endpoint:u}),examples:l,parameterDisplayName:"path parameter",typeResolver:t,exampleResolver:i,workspace:e,getRawType:o=>Wjo({parameter:o,variableResolver:n,file:Ab({relativeFilepath:f,definitionFile:s,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents})}),breadcrumbs:["path-parameters"]}),exampleQueryParameters:({endpoint:a,examples:u},{relativeFilepath:l,contents:f})=>eSo({allDeclarations:typeof a.request!="string"?a.request?.["query-parameters"]:void 0,examples:u,parameterDisplayName:"query parameter",typeResolver:t,exampleResolver:i,workspace:e,getRawType:s=>({file:Ab({relativeFilepath:l,definitionFile:f,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),rawType:typeof s=="string"?s:s.type}),breadcrumbs:["query-parameters"]}),exampleRequest:({endpoint:a,example:u},{relativeFilepath:l,contents:f})=>bUp({example:u,endpoint:a,typeResolver:t,exampleResolver:i,file:Ab({relativeFilepath:l,definitionFile:f,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),workspace:e}),exampleResponse:({endpoint:a,example:u},{relativeFilepath:l,contents:f})=>OUp({example:u,endpoint:a,typeResolver:t,exampleResolver:i,file:Ab({relativeFilepath:l,definitionFile:f,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),workspace:e,errorResolver:r})}}}};function qbD({workspace:e,service:t,endpoint:r}){let i=y6t(r);return r["base-path"]!=null?{...i}:{...e.definition.rootApiFile.contents["path-parameters"],...t["path-parameters"],...i}}var k6s={name:"valid-example-error",create:({workspace:e})=>{let t=new Bw(e),r=new Xwe(t);return{definitionFile:{exampleError:({errorName:i,declaration:n,example:a},{relativeFilepath:u,contents:l})=>n.type==null?[]:n$.validateTypeReferenceExample({rawTypeReference:n.type,example:a.value,file:Ab({relativeFilepath:u,definitionFile:l,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),workspace:e,typeResolver:t,exampleResolver:r,breadcrumbs:["response","body"],depth:0}).map(s=>({severity:"fatal",message:s.message}))}}}};var e4s={name:"valid-example-type",create:({workspace:e})=>{let t=new Bw(e),r=new Xwe(t);return{definitionFile:{exampleType:({typeName:i,typeDeclaration:n,example:a},{relativeFilepath:u,contents:l})=>n$.validateTypeExample({typeName:i,typeDeclaration:n,example:a.value,file:Ab({relativeFilepath:u,definitionFile:l,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),typeResolver:t,exampleResolver:r,workspace:e,breadcrumbs:[],depth:0}).map(s=>({severity:"fatal",message:s.message}))}}}};function mUp(e){let t=[];return e.enum.forEach(r=>{let i=nhn(r);Y1o.test(i.name)||(i.wasExplicitlySet?t.push({severity:"fatal",message:`Enum name ${Su.bold(i.name)} is not suitable for code generation. It must start with a letter and only contain letters, numbers, and underscores.`}):t.push({severity:"fatal",message:`Enum value ${Su.bold(i.name)} is not suitable for code generation. Add a "name" property that starts with a letter and contains only letters, numbers, and underscores.`}))}),t}function PUp(e){let t=[],r=Sri(e);return Y1o.test(r.name)||(r.wasExplicitlySet?t.push({severity:"fatal",message:`Discriminant name ${Su.bold(r.name)} is not suitable for code generation. It must start with a letter and only contain letters, numbers, and underscores.`}):t.push({severity:"fatal",message:`Discriminant value ${Su.bold(r.name)} is not suitable for code generation. Add a "name" property that starts with a letter and contains only letters, numbers, and underscores.`})),t}var t4s={name:"valid-field-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>KR(e,{alias:()=>[],enum:mUp,object:()=>[],undiscriminatedUnion:()=>[],discriminatedUnion:PUp})}})};var r4s={name:"valid-generic",create:({workspace:e})=>{let t=TbD(e),r={object:[],discriminatedUnion:[]};return{definitionFile:{typeDeclaration:({typeName:i,declaration:n,nodePath:a})=>{let u=[];return i.isInlined||aI(i.name)!=null&&(KR(n,{alias:()=>!1,enum:()=>!1,object:()=>!0,discriminatedUnion:()=>!1,undiscriminatedUnion:()=>!1})||u.push({severity:"fatal",message:"Generics are only supported for object declarations"})),KR(n,{alias:l=>{let f=typeof l=="string"?l:l.type,s=aI(f);if(s!=null){let[o,c,...b]=s.name.split("."),g=c??o;g&&g in t&&t[g]!==s.arguments.length&&u.push({severity:"fatal",message:`Generic ${g} expects ${t[g]} arguments, but received ${s.arguments.length} <${s.arguments.join(",")}>`})}else f in t&&u.push({severity:"fatal",message:`Generic ${f} expects ${t[f]} arguments, but received none`})},enum:l=>{typeof l!="string"&&l.enum.forEach(f=>{let s=typeof f=="string"?f:f.value;qTe(s)&&u.push({severity:"fatal",message:`Cannot reference generic ${s} from enum`})})},object:l=>{Object.entries(l?.properties??{}).forEach(([f,s])=>{qTe(typeof s=="string"?s:s.type)&&(a?(r.object??=[]).push({key:f,nodePath:a}):u.push({severity:"fatal",message:`Cannot reference generic ${s} from object property ${f}`}))})},discriminatedUnion:l=>{Object.entries(l.union).forEach(([f,s])=>{let o=typeof s=="string"?s:typeof s.type=="string"?s.type:void 0;o&&qTe(o)&&(a?(r.discriminatedUnion??=[]).push({key:f,nodePath:a}):u.push({severity:"fatal",message:`Cannot reference generic ${s} from union property ${f}`}))})},undiscriminatedUnion:l=>{l.union.forEach(f=>{let s=typeof f=="string"?f:f.type;qTe(s)&&u.push({severity:"fatal",message:`Cannot reference generic ${s} from union`})})}}),u},typeReference:({typeReference:i,nodePath:n})=>{let a=[];if(n)for(let u of Object.keys(r))for(let{key:l,nodePath:f}of r[u])f.length>0&&n.join(",").startsWith(f.join(","))&&n.includes(l)&&a.push({severity:"fatal",message:`Cannot reference generic ${i} from ${u.toLowerCase().includes("union")?"union":u}`});return a}}}}};function TbD(e){let t={};return dN(e,(r,i)=>{pU(i,{typeDeclaration:({typeName:n,declaration:a})=>{if(!n.isInlined){let u=aI(n.name);u!=null&&KR(a,{alias:()=>{},enum:()=>{},object:()=>{u.name&&u.arguments&&(t[u.name]=u.arguments.length)},discriminatedUnion:()=>{},undiscriminatedUnion:()=>{}})}}})}),t}var jUp=mi(require("path"),1);var i4s={name:"valid-navigation",create:({workspace:e})=>{let t=N3t(r5r(e.definition)),i=N3t(Pti(e.definition)).reduce((n,a)=>((n[dp(a)]??=new Set).add(jUp.default.basename(a)),n),{});return{packageMarker:{navigation:(n,{relativeFilepath:a})=>{if(n==null)return[];if(typeof n=="string"){let s=xT(e.definition.absoluteFilePath,ku(e.definition.absoluteFilePath,dp(a),po.of(n)));return t.some(o=>o.startsWith(s))?[]:[{severity:"fatal",message:`${n} does not exist.`}]}let u=i[dp(a)];if(u==null)throw new Error(`Could not find expected contents of ${a}`);let l=[],f=new Set;for(let s of n)s===m1?l.push({severity:"fatal",message:`${m1} cannot be specified in navigation.`}):u.has(s)?f.has(s)&&l.push({severity:"fatal",message:`${s} is specified more than once.`}):l.push({severity:"fatal",message:`Unexpected item: ${s}`}),f.add(s);for(let s of u)f.has(s)||l.push({severity:"fatal",message:`Missing ${s}`});return l}}}}};var sia="$request.",n4s="$response.";function zhn({typeResolver:e,file:t,endpoint:r,propertyComponents:i,validate:n}){if(r.request==null)return!1;if(typeof r.request=="string"){let a=e.resolveType({type:r.request,file:t});return P6t({typeResolver:e,file:v8(a)??t,resolvedType:a,propertyComponents:i,validate:n})}return CbD({typeResolver:e,file:t,requestType:r.request,propertyComponents:i,validate:n})}function CbD({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}){if(BbD({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}))return!0;if(r.body==null)return!1;if(typeof r.body=="string"){let u=e.resolveType({type:r.body,file:t});return P6t({typeResolver:e,file:v8(u)??t,resolvedType:u,propertyComponents:i,validate:n})}if(oT(r.body))return wUp({typeResolver:e,file:t,objectSchema:r.body,propertyComponents:i,validate:n});let a=e.resolveType({type:r.body.type,file:t});return P6t({typeResolver:e,file:v8(a)??t,resolvedType:e.resolveType({type:r.body.type,file:t}),propertyComponents:i,validate:n})}function BbD({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}){if(i.length!==1||typeof r=="string"||r["query-parameters"]==null)return!1;let a=r["query-parameters"][i[0]??""];if(a==null)return!1;let u=e.resolveType({type:typeof a!="string"?a.type:a,file:t});return n({resolvedType:u})}function P6t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:n}){if(i.length===0)return n({resolvedType:r});let a=DUp(r);return a==null?!1:wUp({typeResolver:e,file:t,objectSchema:a,propertyComponents:i,validate:n})}function Uri({endpoint:e,typeResolver:t,file:r}){let i=typeof e.response!="string"?e.response?.type:e.response;if(i!=null)return t.resolveType({type:i,file:r})}function j6t(e){if(e?._type==="primitive")return e.primitive.v1;if(e?._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return j6t(e.container.itemType)}function v8(e){if(e!=null){if(e._type==="named")return e.file;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return v8(e.container.itemType)}}function Rhn(e){return EUp(e,sia)?.split(".")}function tSo(e){return EUp(e,n4s)?.split(".")}function wUp({typeResolver:e,file:t,objectSchema:r,propertyComponents:i,validate:n}){let a=xbD({typeResolver:e,file:t,objectSchema:r,property:i[0]??""});if(a==null)return!1;let u=e.resolveType({type:a,file:t});return P6t({typeResolver:e,file:v8(u)??t,resolvedType:u,propertyComponents:i.slice(1),validate:n})}function xbD({typeResolver:e,file:t,objectSchema:r,property:i}){return SUp({typeResolver:e,file:t,objectSchema:r})[i]}function SUp({typeResolver:e,file:t,objectSchema:r}){let i=[];typeof r.extends=="string"?i=[r.extends]:Array.isArray(r.extends)&&(i=r.extends);let n={};for(let a of i){let u=IbD({typeResolver:e,file:t,extendedType:a});Object.entries(u).map(([l,f])=>{n[l]=f})}return r.properties!=null&&Object.entries(r.properties).map(([a,u])=>{n[a]=typeof u=="string"?u:u.type}),n}function IbD({typeResolver:e,file:t,extendedType:r}){let i=e.resolveNamedTypeOrThrow({referenceToNamedType:r,file:t});return i._type==="named"&&D1(i.declaration)?SUp({typeResolver:e,file:v8(i)??t,objectSchema:i.declaration}):{}}function DUp(e){if(e!=null){if(e._type==="named"&&D1(e.declaration))return e.declaration;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return DUp(e.container.itemType)}}function EUp(e,t){return e.startsWith(t)?e.substring(t.length):null}var a4s=`${sia}client_id`,o4s=`${sia}client_secret`,Nhn=`${n4s}access_token`,u4s=`${sia}refresh_token`;function s4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:n}){return nSo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"client-id",validate:cia}})}function c4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:n}){return nSo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"client-secret",validate:cia}})}function AUp({endpointId:e,endpoint:t,typeResolver:r,file:i,scopesProperty:n}){return nSo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"scopes",validate:cia}})}function l4s({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:n}){return nSo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"refresh-token",validate:cia}})}function Fhn({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,accessTokenProperty:n}){return f4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"access-token",validate:MUp}})}function rSo({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,refreshTokenProperty:n}){return f4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"refresh-token",validate:MUp}})}function iSo({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,expiresInProperty:n}){return f4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"expires-in",validate:zbD}})}function zbD({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return P6t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:RbD})}function MUp({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return P6t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:cia})}function nSo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:a}){let u=[],l=Rhn(n);return l==null?(u.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $request (e.g. $request.${a.propertyID}).`}),u):l.length>1?(u.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} cannot reference nested $request properties like '${n}'; expected '$request.${a.propertyID}' instead.`}),u):(zhn({typeResolver:r,file:i,endpoint:t,propertyComponents:l,validate:a.validate})||u.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),u)}function f4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:a}){let u=[],l=tSo(n);return l==null&&u.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $response (e.g. $response.${a.propertyID}).`}),l!=null&&!a.validate({typeResolver:t,file:r,resolvedType:i,propertyComponents:l})&&u.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),u}function RbD({resolvedType:e}){return j6t(e)==="INTEGER"}function cia({resolvedType:e}){return j6t(e)==="STRING"}function qUp({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshEndpoint:n}){let a=[],u=n["request-properties"]?.["refresh-token"];u!=null?a.push(...l4s({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:u})):l4s({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:u4s}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} is missing a valid refresh-token, such as '${u4s}'.`});let l=Uri({endpoint:t,typeResolver:r,file:i});if(l==null)return a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} must define a response type.`}),a;let f=n["response-properties"]?.["access-token"];f!=null?a.push(...Fhn({endpointId:e,typeResolver:r,file:i,resolvedResponseType:l,accessTokenProperty:f})):Fhn({endpointId:e,typeResolver:r,file:i,resolvedResponseType:l,accessTokenProperty:Nhn}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} is missing a valid access-token, such as '${Nhn}'.`});let s=n?.["response-properties"]?.["expires-in"];s!=null&&a.push(...iSo({endpointId:e,typeResolver:r,file:v8(l)??i,resolvedResponseType:l,expiresInProperty:s}));let o=n?.["response-properties"]?.["refresh-token"];return o!=null&&a.push(...rSo({endpointId:e,typeResolver:r,file:v8(l)??i,resolvedResponseType:l,refreshTokenProperty:o})),a}function TUp({endpointId:e,endpoint:t,typeResolver:r,file:i,tokenEndpoint:n}){let a=[],u=n["request-properties"]?.["client-id"];u!=null?a.push(...s4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:u})):s4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:a4s}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} is missing a valid client-id, such as '${a4s}'.`});let l=n["request-properties"]?.["client-secret"];l!=null?a.push(...c4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:l})):c4s({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:o4s}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} is missing a valid client-secret, such as '${o4s}'.`});let f=n?.["request-properties"]?.scopes;f!=null&&a.push(...AUp({endpointId:e,endpoint:t,typeResolver:r,file:i,scopesProperty:f}));let s=Uri({endpoint:t,typeResolver:r,file:i});if(s==null)return a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} must define a response type.`}),a;let o=n["response-properties"]?.["access-token"];o!=null?a.push(...Fhn({endpointId:e,typeResolver:r,file:i,resolvedResponseType:s,accessTokenProperty:o})):Fhn({endpointId:e,typeResolver:r,file:i,resolvedResponseType:s,accessTokenProperty:Nhn}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Su.bold(e)} is missing a valid access-token, such as '${Nhn}'.`});let c=n?.["response-properties"]?.["expires-in"];c!=null&&a.push(...iSo({endpointId:e,typeResolver:r,file:v8(s)??i,resolvedResponseType:s,expiresInProperty:c}));let b=n?.["response-properties"]?.["refresh-token"];return b!=null&&a.push(...rSo({endpointId:e,typeResolver:r,file:v8(s)??i,resolvedResponseType:s,refreshTokenProperty:b})),a}var d4s={name:"valid-oauth",create:({workspace:e})=>{let t=new Bw(e),r=new dEi(e),i=T5r({casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents});return{rootApiFile:{oauth:({name:n,oauth:a},{relativeFilepath:u})=>{let l=[],f=a["get-token"].endpoint,s=r.resolveEndpoint({endpoint:f,file:i});s==null?l.push({severity:"fatal",message:`Failed to resolve endpoint ${f}`}):l.push(...TUp({endpointId:s.endpointId,endpoint:s.endpoint,typeResolver:t,file:s.file,tokenEndpoint:a["get-token"]}));let o=a["refresh-token"]?.endpoint;if(a["refresh-token"]!=null&&o!=null){let c=r.resolveEndpoint({endpoint:o,file:i});c==null?l.push({severity:"fatal",message:`Failed to resolve endpoint ${f}`}):l.push(...qUp({endpointId:c.endpointId,endpoint:c.endpoint,typeResolver:t,file:c.file,refreshEndpoint:a["refresh-token"]}))}return l}}}}};function aSo({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,resultsProperty:n}){return p4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"results",validate:NbD}})}function lia({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:a}){let u=[],l=Rhn(n);return l==null?(u.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $request (e.g. $request.${a.propertyID}).`}),u):(zhn({typeResolver:r,file:i,endpoint:t,propertyComponents:l,validate:a.validate})||u.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),u)}function p4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:a}){let u=[],l=tSo(n);return l==null&&u.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $response (e.g. $response.${a.propertyID}).`}),l!=null&&!a.validate({typeResolver:t,file:r,resolvedType:i,propertyComponents:l})&&u.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),u}function NbD({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return P6t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:FbD})}function FbD({resolvedType:e}){return!0}function CUp({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}){let a=[];a.push(...LbD({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}));let u=Uri({endpoint:t,typeResolver:r,file:i});return u==null?(a.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} must define a response type.`}),a):(a.push(...UbD({endpointId:e,typeResolver:r,file:v8(u)??i,resolvedResponseType:u,nextProperty:n.next_cursor})),a.push(...aSo({endpointId:e,typeResolver:r,file:v8(u)??i,resolvedResponseType:u,resultsProperty:n.results})),a)}function LbD({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}){return lia({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.cursor,propertyValidator:{propertyID:"cursor",validate:BUp}})}function UbD({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,nextProperty:n}){return p4s({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"next_cursor",validate:VbD}})}function VbD({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return P6t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:BUp})}function BUp({resolvedType:e}){let t=j6t(e);return t==null?!1:t!=="BOOLEAN"}function xUp(e){return e.split(".").slice(1)}function IUp({path:e,typeResolver:t,file:r,resolvedType:i,validate:n}){let a=i;for(let u of e){if(a==null)return n({resolvedType:void 0});let l=NUp(a);if(l==null)return n({resolvedType:void 0});let s=zUp({typeResolver:t,file:r,objectSchema:l})[u];if(s==null)return n({resolvedType:void 0});a=t.resolveType({type:s,file:r})}return n({resolvedType:a})}function zUp({typeResolver:e,file:t,objectSchema:r}){let i=[];typeof r.extends=="string"?i=[r.extends]:Array.isArray(r.extends)&&(i=r.extends);let n={};for(let a of i){let u=WbD({typeResolver:e,file:t,extendedType:a});Object.entries(u).map(([l,f])=>{n[l]=f})}return r.properties!=null&&Object.entries(r.properties).map(([a,u])=>{n[a]=typeof u=="string"?u:u.type}),n}function WbD({typeResolver:e,file:t,extendedType:r}){let i=e.resolveNamedTypeOrThrow({referenceToNamedType:r,file:t});return i._type==="named"&&D1(i.declaration)?zUp({typeResolver:e,file:RUp(i)??t,objectSchema:i.declaration}):{}}function RUp(e){if(e!=null){if(e._type==="named")return e.file;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return RUp(e.container.itemType)}}function NUp(e){if(e!=null){if(e._type==="named"&&D1(e.declaration))return e.declaration;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return NUp(e.container.itemType)}}function FUp({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){let a=[];a.push(...HbD({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n})),a.push(...$bD({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}));let u=Uri({endpoint:t,typeResolver:r,file:i});return u==null?(a.push({severity:"fatal",message:`Pagination configuration for endpoint ${Su.bold(e)} must define a response type.`}),a):(a.push(...aSo({endpointId:e,typeResolver:r,file:v8(u)??i,resolvedResponseType:u,resultsProperty:n.results})),a.push(...GbD({endpointId:e,resolvedResponseType:u,typeResolver:r,file:v8(u)??i,offsetPagination:n})),a)}function HbD({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){return lia({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.offset,propertyValidator:{propertyID:"offset",validate:LUp}})}function $bD({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){return n.step==null?[]:lia({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.step,propertyValidator:{propertyID:"step",validate:LUp}})}function LUp({resolvedType:e}){let t=j6t(e);return t==null?!1:t==="INTEGER"||t==="LONG"||t==="DOUBLE"}function GbD({resolvedResponseType:e,typeResolver:t,file:r,offsetPagination:i}){return i["has-next-page"]==null?[]:IUp({typeResolver:t,file:r,path:xUp(i["has-next-page"]),resolvedType:e,validate:({resolvedType:n})=>j6t(n)!=="BOOLEAN"?[{message:`"has-next-page" selector, ${i["has-next-page"]}, does not point to a boolean property`,severity:"fatal"}]:[]})}var _4s={name:"valid-pagination",create:({workspace:e})=>{let t=new Bw(e),r=e.definition.rootApiFile.contents.pagination;return{definitionFile:{httpEndpoint:({endpointId:i,endpoint:n},{relativeFilepath:a,contents:u})=>{let l=typeof n.pagination=="boolean"?r:n.pagination;if(!l)return[];let f=Ab({relativeFilepath:a,definitionFile:u,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents});return QbD(l)?CUp({endpointId:i,endpoint:n,typeResolver:t,file:f,cursorPagination:l}):FUp({endpointId:i,endpoint:n,typeResolver:t,file:f,offsetPagination:l})}}}}};function QbD(e){return e.cursor!=null&&e.next_cursor!=null&&e.results!=null}var h4s={name:"valid-path-parameters-configuration",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>e["path-parameters"]!=null&&typeof e.request!="string"&&e?.request?.["path-parameters"]!=null?[{severity:"fatal",message:"path-parameters cannot be defined in both endpoint and request."}]:[]}})};var y4s={name:"valid-service-urls",create:({workspace:e})=>{let t=X1o(e),r=i=>t.includes(i)?[]:t.length===0&&e.definition.rootApiFile.contents?.["default-url"]!=null?[]:t.length===0?[{severity:"fatal",message:`"url" cannot be configured unless you specify multiple URLs for each environment in ${WF}`}]:[{severity:"fatal",message:[`URL ${Su.bold(i)} is not recognized. Please add it to your environments in ${WF} or specify one of the configured environment URLs:`,...t.map(n=>` - ${n}`)].join(`
1974
1974
  `)}];return{definitionFile:{serviceBaseUrl:i=>i==null?[]:r(i),endpointBaseUrl:({baseUrl:i,service:n})=>e.definition.rootApiFile.contents?.["default-url"]?[]:i==null?t.length===0||n.url!=null?[]:[{severity:"fatal",message:['"url" is missing. Please specify one of the configured environment URLs:',...t.map(a=>` - ${a}`)].join(`
1975
1975
  `)}]:r(i)}}}};var v4s={name:"valid-stream-condition",create:({workspace:e})=>({definitionFile:{streamCondition:({endpoint:t,streamCondition:r},{relativeFilepath:i,contents:n})=>{let a=new Bw(e),u=Ab({relativeFilepath:i,definitionFile:n,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents});return t.response==null||t["response-stream"]==null?r==null?[]:[{severity:"fatal",message:"stream-condition can only be used if both response and response-stream are specified."}]:r==null?[{severity:"fatal",message:"stream-condition must be specified when both response and response-stream are specified."}]:KbD({endpoint:t,typeResolver:a,file:u,requestProperty:r,propertyValidator:{propertyID:"stream-condition",validate:JbD}})}}})};function JbD({resolvedType:e}){let t=j6t(e);return t==null?!1:t==="BOOLEAN"}function KbD({endpoint:e,typeResolver:t,file:r,requestProperty:i,propertyValidator:n}){let a=[],u=Rhn(i);return u==null?[{severity:"fatal",message:"Please specify path to a valid property (e.g. $request.stream)"}]:zhn({typeResolver:t,file:r,endpoint:e,propertyComponents:u,validate:n.validate})?a:[{severity:"fatal",message:`Property "${i}" does not exist on the request.`}]}var YbD=/^[a-z]/i,b4s={name:"valid-type-name",create:()=>({definitionFile:{typeDeclaration:({typeName:e})=>!e.isInlined&&!YbD.test(e.name)?[{severity:"fatal",message:"Type name must begin with a letter"}]:[]}})};var O4s={name:"valid-type-reference-with-default-and-validation",create:({workspace:e})=>{let t=new Bw(e);return{definitionFile:{typeDeclaration:({declaration:r})=>{if(!T7t(r))return[];let i=new Set(r.enum.map(n=>typeof n=="string"?n:n.value));return r.default!=null&&!i.has(r.default)?[{message:`Default value '${r.default}' is not a valid enum value`,severity:"fatal"}]:[]},typeReference:({typeReference:r,_default:i,validation:n,location:a},{relativeFilepath:u,contents:l})=>{let f=Ab({relativeFilepath:u,definitionFile:l,casingsGenerator:T1,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:r,file:f});return s==null?[]:UUp({resolvedType:s,_default:i,validation:n})}}}}};function UUp({resolvedType:e,_default:t,validation:r}){let i=[];if(t==null&&r==null)return[];if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return UUp({resolvedType:e.container.itemType,_default:t,validation:r});let n=e._type;if(e._type==="primitive")switch(e.primitive.v1){case"STRING":return ZbD({_default:t,validation:r});case"DOUBLE":return kbD({_default:t,validation:r});case"INTEGER":return e0D({_default:t,validation:r});case"BOOLEAN":return t0D({_default:t,validation:r});case"LONG":return r0D({_default:t,validation:r});case"BIG_INTEGER":return i0D({_default:t,validation:r});case"DATE_TIME":n="datetime";break;case"UUID":n="uuid";break;case"BASE_64":n="base64";break;case"UINT":n="uint";break;case"UINT_64":n="uint64";break}return e._type==="named"&&T7t(e.declaration)?XbD({declaration:e.declaration,_default:t}):(t!=null&&i.push({message:`Default values are not supported for the ${n} type`,severity:"fatal"}),r!=null&&i.push({message:`Validation rules are not supported for the ${n} type`,severity:"fatal"}),i)}function XbD({declaration:e,_default:t}){if(t==null)return[];let r=new Set(e.enum.map(n=>typeof n=="string"?n:n.value)),i=[];return r.has(t)||i.push({message:`Default value '${t}' is not a valid enum value`,severity:"fatal"}),i}function ZbD({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="string"&&r.push({message:`Default value '${e}' is not a valid string`,severity:"fatal"}),t!=null&&!n0D(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the string type`,severity:"fatal"}),r}function kbD({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid double`,severity:"fatal"}),t!=null&&!VUp(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the double type`,severity:"fatal"}),r}function e0D({_default:e,validation:t}){let r=[];return e!=null&&!Number.isInteger(e)&&r.push({message:`Default value '${e}' is not a valid integer`,severity:"fatal"}),t!=null&&(VUp(t)?r.push(...g4s({name:"min",value:t.min}),...g4s({name:"max",value:t.max}),...g4s({name:"multipleOf",value:t.multipleOf})):r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the integer type`,severity:"fatal"})),r}function t0D({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="boolean"&&r.push({message:`Default value '${e}' is not a valid boolean`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the boolean type`,severity:"fatal"}),r}function r0D({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid long`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the long type`,severity:"fatal"}),r}function i0D({_default:e,validation:t}){let r=[];if(e!=null)if(typeof e!="string")r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"});else try{BigInt(e)}catch{r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"})}return t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the bigint type`,severity:"fatal"}),r}function g4s({name:e,value:t}){return t!=null&&!Number.isInteger(t)?[{message:`Validation for '${e}' must be an integer, but found '${t}'`,severity:"fatal"}]:[]}function VUp(e){let t=e;return t.min!=null||t.max!=null||t.exclusiveMin!=null||t.exclusiveMax!=null||t.multipleOf!=null}function n0D(e){let t=e;return t.minLength!=null||t.maxLength!=null||t.pattern!=null||t.format!=null}var m4s={name:"valid-version",create:({workspace:e})=>{let t=new Bw(e);return{rootApiFile:{file:r=>a0D({root:r,typeResolver:t})}}}};function a0D({root:e,typeResolver:t}){let r=[];return e.version==null||e.version.default==null?[]:(new Set(e.version.values.map(n=>typeof n=="string"?n:n.value)).has(e.version.default)||r.push({severity:"fatal",message:`Default version "${e.version.default}" not found in version values`}),r)}function o0D(){return[$6s,q6s,H6s,O6s,M6s,U6s,P6s,t4s,C6s,F6s,I6s,j6s,Y6s,R6s,e4s,B6s,z6s,N6s,w6s,E6s,Z6s,T6s,V6s,m6s,y4s,K6s,X6s,D6s,b4s,x6s,i4s,G6s,J6s,L6s,d4s,_4s,k6s,O4s,v4s,m4s,Q6s,r4s,b6s,h4s,g6s]}function WUp(){return o0D().filter(({DISABLE_RULE:e=!1})=>!e)}function P4s(e,t){return u0D({workspace:e,rules:WUp(),logger:t})}function u0D({workspace:e,rules:t,logger:r}){let i=[],n=t.map(u=>u.create({workspace:e,logger:r})),a=c0D({contents:e.definition.rootApiFile.contents,allRuleVisitors:n});return i.push(...a),dN(e,(u,l)=>{let f=s0D({relativeFilepath:u,contents:l,allRuleVisitors:n});i.push(...f)}),KSi(e,(u,l)=>{let f=l0D({relativeFilepath:u,contents:l,allRuleVisitors:n});i.push(...f)}),i}function s0D({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=oUp({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return pU(t,n),i}function c0D({contents:e,allRuleVisitors:t}){let r=[],i=sUp({relativeFilepath:po.of(WF),contents:e,allRuleVisitors:t,addViolations:n=>{r.push(...n)}});return v6s(e,i),r}function l0D({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=uUp({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return y6s(t,n),i}async function HUp({groups:e,visitor:t,nodePath:r,cliVersion:i}){if(e!=null)for(let[n,a]of Object.entries(e))await f0D({group:a,visitor:t,nodePath:[...r,n],cliVersion:i})}async function f0D({group:e,visitor:t,nodePath:r,cliVersion:i}){await Promise.all(e.generators.map(async(n,a)=>await t.generatorInvocation?.({invocation:n,cliVersion:i},[...r,"generators",a.toString(),n.name])))}async function $Up(e,t,r){await r.file?.(e,[]),await TUt(e,{"auth-schemes":Jo,api:Jo,whitelabel:Jo,metadata:Jo,readme:Jo,"default-group":Jo,reviewers:Jo,openapi:Jo,"openapi-overrides":Jo,"spec-origin":Jo,"async-api":Jo,"api-settings":Jo,groups:async i=>{await HUp({groups:i,visitor:r,nodePath:["groups"],cliVersion:t})}})}function GUp({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=async(l,f)=>{for(let s of r){let o=s.generatorsYml?.[a];if(o!=null){let c=await o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("generatorInvocation")}}function d0D(e,t,r){if(!Bte(r,t))return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function p0D(e){return Number(e.replace("v",""))}async function _0D(e){let t=GYa({token:void 0}),r=await t.generators.getGeneratorByImage({dockerImage:e.name});if(!r.ok||r.body==null)return;let i=await t.generators.versions.getGeneratorRelease(r.body.id,e.version);if(i.ok)return i.body.irVersion}var j4s={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=GYa({token:void 0});if(t==null)return[];let i=await r.generators.cli.getCliRelease(t);if(!i.ok)return[];let n=i.body.irVersion,a;if(e["ir-version"]!=null)a=p0D(e["ir-version"]);else{let l=await _0D(e);if(l==null)return[];a=l}if(a<=n)return[];let u=await r.generators.cli.getMinCliForIr(a);return u.ok?d0D(e.name,u.body.version,t)??[]:[]}}})};function QUp(){return[j4s]}async function w4s(e,t){return h0D({workspace:e,rules:QUp(),logger:t})}async function h0D({workspace:e,rules:t,logger:r}){let i=[],n=await Promise.all(t.map(a=>a.create({workspace:e,logger:r})));if(e.generatorsConfiguration?.rawConfiguration){let a=await y0D({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:n,cliVersion:e.cliVersion});i.push(...a)}return i}async function y0D({contents:e,allRuleVisitors:t,cliVersion:r}){let i=[],n=GUp({relativeFilepath:po.of(IR),contents:e,allRuleVisitors:t,addViolations:a=>{i.push(...a)}});return await $Up(e,r,n),i}function Vri({context:e,violations:t,logWarnings:r,logSummary:i=!0}){let n=P0D(t);i&&m0D({context:e,stats:n,logWarnings:r});let a=v0D(t);for(let[u,l]of a){let f=l[0]?.relativeFilepath??"";b0D({logWarnings:r,relativeFilepath:f,nodePath:u,violations:l,context:e})}return{hasErrors:n.numFatal>0}}function v0D(e){let t=new Map;for(let r of e)t.set(r.nodePath,[...t.get(r.nodePath)??[],r]);return t}function b0D({logWarnings:e,relativeFilepath:t,nodePath:r,violations:i,context:n}){let a=g0D(i);if(a==="warning"&&!e)return;let u=i.map(l=>l.severity==="warning"&&!e?null:l.message).filter(l=>l!=null).join(`
1976
- `);n.logger.log(O0D(a),VBe({breadcrumbs:[t,...r.map(l=>{let f=typeof l=="string"?l:l.key;return typeof l!="string"&&l.arrayIndex!=null&&(f+=`[${l.arrayIndex}]`),f})],title:u}))}function g0D(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function O0D(e){switch(e){case"fatal":return eg.Error;case"error":return eg.Warn;case"warning":return eg.Warn;default:Zo(e)}}function m0D({stats:e,context:t,logWarnings:r}){let{numFatal:i,numErrors:n,numWarnings:a}=e,u=`Found ${i} errors and ${n+a} warnings.`;!r&&a>0&&(u+=" Run fern check --warnings to print out the warnings not shown."),i>0?t.logger.error(u):n+a>0?t.logger.warn(u):t.logger.info(Su.green("\u2713 All checks passed"))}function P0D(e){let t=0,r=0,i=0;for(let n of e)switch(n.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":i+=1;continue;default:Zo(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function S4s({workspace:e,context:t,logWarnings:r,logSummary:i=!0}){let n=P4s(e,t.logger),a=await w4s(e,t.logger),u=[...n,...a],{hasErrors:l}=Vri({violations:u,context:t,logWarnings:r,logSummary:i});return{hasErrors:l}}async function pJt({workspace:e,context:t,logWarnings:r}){(0,JUp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:i}=await S4s({workspace:e,context:t,logWarnings:r});i&&t.failAndThrow()}var D4s={};Ro(D4s,{additionalProperties:()=>D0D,default:()=>A0D,definitions:()=>E0D,properties:()=>w0D,required:()=>S0D,type:()=>j0D});var j0D="object",w0D={tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{$ref:"#/definitions/docs.NavigationConfig"}},S0D=["navigation"],D0D=!1,E0D={"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]}},A0D={type:j0D,properties:w0D,required:S0D,additionalProperties:D0D,definitions:E0D};async function oSo({value:e}){let t=l6r(e,D4s);if(t.success)return{type:"success",contents:K3t.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(e)};let r=t.error?.instancePath?` at ${t?.error.instancePath}`:"";return{type:"failure",message:`${t.error?.message??"Failed to parse because JSON schema validation failed"}${r}`}}var fia=class{constructor(){this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:t=>this.replacement=t}}replace(t,r,i,n){t&&r&&(i!=null?t[r][i]=n:t[r]=n)}remove(t,r,i){t&&r&&(i!=null?t[r].splice(i,1):delete t[r])}};var uSo=class extends fia{constructor(t,r){super(),this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:i=>this.replacement=i},this.enter=t,this.leave=r}visit(t,r,i,n){if(t){if(this.enter){let u=this.should_skip,l=this.should_remove,f=this.replacement;this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.enter.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let s=this.should_skip,o=this.should_remove;if(this.should_skip=u,this.should_remove=l,this.replacement=f,s)return t;if(o)return null}let a;for(a in t){let u=t[a];if(u&&typeof u=="object")if(Array.isArray(u)){let l=u;for(let f=0;f<l.length;f+=1){let s=l[f];KUp(s)&&(this.visit(s,t,a,f)||f--)}}else KUp(u)&&this.visit(u,t,a,null)}if(this.leave){let u=this.replacement,l=this.should_remove;this.replacement=null,this.should_remove=!1,this.leave.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let f=this.should_remove;if(this.replacement=u,this.should_remove=l,f)return null}}return t}};function KUp(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function YUp(e,{enter:t,leave:r}){return new uSo(t,r).visit(e,null)}function XUp(e,t){let r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function ZUp(e,t){let r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
1976
+ `);n.logger.log(O0D(a),VBe({breadcrumbs:[t,...r.map(l=>{let f=typeof l=="string"?l:l.key;return typeof l!="string"&&l.arrayIndex!=null&&(f+=`[${l.arrayIndex}]`),f})],title:u}))}function g0D(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function O0D(e){switch(e){case"fatal":return eg.Error;case"error":return eg.Warn;case"warning":return eg.Warn;default:Zo(e)}}function m0D({stats:e,context:t,logWarnings:r}){let{numFatal:i,numErrors:n,numWarnings:a}=e,u=`Found ${i} errors and ${n+a} warnings.`;!r&&a>0&&(u+=" Run fern check --warnings to print out the warnings not shown."),i>0?t.logger.error(u):n+a>0?t.logger.warn(u):t.logger.info(Su.green("\u2713 All checks passed"))}function P0D(e){let t=0,r=0,i=0;for(let n of e)switch(n.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":i+=1;continue;default:Zo(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function S4s({workspace:e,context:t,logWarnings:r,logSummary:i=!0}){let n=P4s(e,t.logger),a=await w4s(e,t.logger),u=[...n,...a],{hasErrors:l}=Vri({violations:u,context:t,logWarnings:r,logSummary:i});return{hasErrors:l}}async function pJt({workspace:e,context:t,logWarnings:r}){(0,JUp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:i}=await S4s({workspace:e,context:t,logWarnings:r});i&&t.failAndThrow()}var D4s={};Ro(D4s,{additionalProperties:()=>D0D,default:()=>A0D,definitions:()=>E0D,properties:()=>w0D,required:()=>S0D,type:()=>j0D});var j0D="object",w0D={tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{$ref:"#/definitions/docs.NavigationConfig"}},S0D=["navigation"],D0D=!1,E0D={"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]}},A0D={type:j0D,properties:w0D,required:S0D,additionalProperties:D0D,definitions:E0D};async function oSo({value:e}){let t=l6r(e,D4s);if(t.success)return{type:"success",contents:K3t.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(e)};let r=t.error?.instancePath?` at ${t?.error.instancePath}`:"";return{type:"failure",message:`${t.error?.message??"Failed to parse because JSON schema validation failed"}${r}`}}var fia=class{constructor(){this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:t=>this.replacement=t}}replace(t,r,i,n){t&&r&&(i!=null?t[r][i]=n:t[r]=n)}remove(t,r,i){t&&r&&(i!=null?t[r].splice(i,1):delete t[r])}};var uSo=class extends fia{constructor(t,r){super(),this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:i=>this.replacement=i},this.enter=t,this.leave=r}visit(t,r,i,n){if(t){if(this.enter){let u=this.should_skip,l=this.should_remove,f=this.replacement;this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.enter.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let s=this.should_skip,o=this.should_remove;if(this.should_skip=u,this.should_remove=l,this.replacement=f,s)return t;if(o)return null}let a;for(a in t){let u=t[a];if(u&&typeof u=="object")if(Array.isArray(u)){let l=u;for(let f=0;f<l.length;f+=1){let s=l[f];KUp(s)&&(this.visit(s,t,a,f)||f--)}}else KUp(u)&&this.visit(u,t,a,null)}if(this.leave){let u=this.replacement,l=this.should_remove;this.replacement=null,this.should_remove=!1,this.leave.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let f=this.should_remove;if(this.replacement=u,this.should_remove=l,f)return null}}return t}};function KUp(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function YUp(e,{enter:t,leave:r}){return new uSo(t,r).visit(e,null)}function XUp(e,t){let r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function ZUp(e,t){let r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
1977
1977
  `}]}function kUp(e,t){let r=t.value?t.value+`
1978
1978
  `:"",i={};t.lang&&(i.className=["language-"+t.lang]);let n={type:"element",tagName:"code",properties:i,children:[{type:"text",value:r}]};return t.meta&&(n.data={meta:t.meta}),e.patch(t,n),n=e.applyData(t,n),n={type:"element",tagName:"pre",properties:{},children:[n]},e.patch(t,n),n}function eVp(e,t){let r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function tVp(e,t){let r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function rVp(e,t){let r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),n=DBe(i.toLowerCase()),a=e.footnoteOrder.indexOf(i),u,l=e.footnoteCounts.get(i);l===void 0?(l=0,e.footnoteOrder.push(i),u=e.footnoteOrder.length):u=a+1,l+=1,e.footnoteCounts.set(i,l);let f={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+n,id:r+"fnref-"+n+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(u)}]};e.patch(t,f);let s={type:"element",tagName:"sup",properties:{},children:[f]};return e.patch(t,s),e.applyData(t,s)}function iVp(e,t){let r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function nVp(e,t){if(e.options.allowDangerousHtml){let r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function sSo(e,t){let r=t.referenceType,i="]";if(r==="collapsed"?i+="[]":r==="full"&&(i+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+i}];let n=e.all(t),a=n[0];a&&a.type==="text"?a.value="["+a.value:n.unshift({type:"text",value:"["});let u=n[n.length-1];return u&&u.type==="text"?u.value+=i:n.push({type:"text",value:i}),n}function aVp(e,t){let r=String(t.identifier).toUpperCase(),i=e.definitionById.get(r);if(!i)return sSo(e,t);let n={src:DBe(i.url||""),alt:t.alt};i.title!==null&&i.title!==void 0&&(n.title=i.title);let a={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,a),e.applyData(t,a)}function oVp(e,t){let r={src:DBe(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);let i={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,i),e.applyData(t,i)}function uVp(e,t){let r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);let i={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,i),e.applyData(t,i)}function sVp(e,t){let r=String(t.identifier).toUpperCase(),i=e.definitionById.get(r);if(!i)return sSo(e,t);let n={href:DBe(i.url||"")};i.title!==null&&i.title!==void 0&&(n.title=i.title);let a={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function cVp(e,t){let r={href:DBe(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);let i={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function lVp(e,t,r){let i=e.all(t),n=r?M0D(r):fVp(t),a={},u=[];if(typeof t.checked=="boolean"){let o=i[0],c;o&&o.type==="element"&&o.tagName==="p"?c=o:(c={type:"element",tagName:"p",properties:{},children:[]},i.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),a.className=["task-list-item"]}let l=-1;for(;++l<i.length;){let o=i[l];(n||l!==0||o.type!=="element"||o.tagName!=="p")&&u.push({type:"text",value:`
1979
1979
  `}),o.type==="element"&&o.tagName==="p"&&!n?u.push(...o.children):u.push(o)}let f=i[i.length-1];f&&(n||f.type!=="element"||f.tagName!=="p")&&u.push({type:"text",value:`