fern-api 0.46.8 → 0.46.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1786,7 +1786,7 @@ ${l.indent}`:""}${xhl(o)}:${f.indent?" ":""}`;return u=!1,c=!0,f.objectItem=void
1786
1786
  `}),r.replaceAll(/\n$/g,"")}function Kow(e){return e?Ic.green(WUr.radioOn):WUr.radioOff}var uMa=bo(oSe(),1);function vIf(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var ADn=class extends b5{_run(t){this.done=t;let r=mH(this.rl),i=r.line.pipe((0,uMa.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,uMa.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=`
1787
1787
  `+Ic.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Ic.cyan(vIf(t,this.opt.mask)):Ic.italic.dim("[hidden]"):this.opt.mask?vIf(t,this.opt.mask):Ic.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 Vzf=bo(ZEu(),1),Wzf=bo(oSe(),1);var FDn=class extends b5{_run(t){this.done=t,this.editorResult=new Wzf.Subject;let r=mH(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"?Ic.dim("Received"):Ic.dim("Press <enter> to launch your preferred editor."),t&&(r=Ic.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,Vzf.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 Xzf=bo(Qzf(),1);var Kzf=bo(require("readline"),1),Yzf=bo($zf(),1),mli=class{constructor(t){this.rl||=Kzf.default.createInterface(Ruw(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 Ruw(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 Yzf.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var RDn=class extends mli{constructor(t={}){super(t),this.log=(0,Xzf.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return mDn(this.rl,this.bottomBar.split(`
1788
1788
  `).length),this}updateBottomBar(t){return mDn(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+`
1789
- `}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&&iMa(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var uNf=bo(eNf(),1),sNf=bo(tSu(),1),cNf=bo(aNf(),1),mC=bo(oSe(),1),lNf=bo(A1n(),1);var EMa=bo(oSe(),1),oNf=bo(A1n(),1),AMa=function(e,t,r){return typeof e[t]!="function"?(0,EMa.of)(e):(0,EMa.from)((0,oNf.default)(e[t])(r).then(i=>(e[t]=i,e)))};var LDn={isPlainObject:uNf.default,set:cNf.default,get:sNf.default},$9i=class extends mli{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=LDn.isPlainObject(r)?{...r}:{},LDn.isPlainObject(t)&&(t=Object.values(t).every(n=>LDn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,mC.from)(t):t;return this.process=i.pipe((0,mC.concatMap)(this.processQuestion.bind(this)),(0,mC.publish)()),this.process.connect(),this.process.pipe((0,mC.reduce)((n,a)=>(LDn.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,mC.defer)(()=>(0,mC.of)(t).pipe((0,mC.concatMap)(this.setDefaultType.bind(this)),(0,mC.concatMap)(this.filterIfRunnable.bind(this)),(0,mC.concatMap)(()=>AMa(t,"message",this.answers)),(0,mC.concatMap)(()=>AMa(t,"default",this.answers)),(0,mC.concatMap)(()=>AMa(t,"choices",this.answers)),(0,mC.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,mC.defer)(()=>(0,mC.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,mC.defer)(()=>(0,mC.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&LDn.get(this.answers,t.name)!==void 0)return(0,mC.empty)();if(t.when===!1)return(0,mC.empty)();if(typeof t.when!="function")return(0,mC.of)(t);let{answers:r}=this;return(0,mC.defer)(()=>(0,mC.from)((0,lNf.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,mC.filter)(i=>i!=null)))}};function fNf(e){let t=function(r,i){let n;try{n=new $9i(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",PDn),this.registerPrompt("input",dli),this.registerPrompt("number",jDn),this.registerPrompt("confirm",wDn),this.registerPrompt("rawlist",DDn),this.registerPrompt("expand",SDn),this.registerPrompt("checkbox",EDn),this.registerPrompt("password",ADn),this.registerPrompt("editor",FDn)},t.restoreDefaultPrompts(),t}var tAu=fNf();function isw(e,t){tAu.registerPrompt(e,t)}function nsw(){tAu.restoreDefaultPrompts()}var asw={prompt:tAu,ui:{BottomBar:RDn,Prompt:$9i},createPromptModule:fNf,registerPrompt:isw,restoreDefaultPrompts:nsw,Separator:Gne},MMa=asw;var O7f=bo(dNf()),Mlw="4.2.1",t3t;(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"})(t3t||(t3t={}));function Tlw(e,t){if(!e)throw new Error(t)}function qlw(e){return e?.replace(/\/+$/,"")}async function Clw(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 xlw(){return new Date().getTime()}function p7f(){return new Date().toISOString()}function P7f(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var XDn=String.fromCharCode,_7f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",VMa={};function Blw(e,t){if(!VMa[e]){VMa[e]={};for(let r=0;r<e.length;r++)VMa[e][e.charAt(r)]=r}return VMa[e][t]}var ZDn={compressToBase64:function(e){if(e==null)return"";let t=ZDn._compress(e,6,function(r){return _7f.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:ZDn._decompress(e.length,32,function(t){return Blw(_7f,e.charAt(t))})},compress:function(e){return ZDn._compress(e,16,function(t){return XDn(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,f,p="",c="",o="",l=2,m=3,O=2,j=0,A=0,T;for(T=0;T<e.length;T+=1)if(p=e.charAt(T),Object.prototype.hasOwnProperty.call(i,p)||(i[p]=m++,n[p]=!0),c=o+p,Object.prototype.hasOwnProperty.call(i,c))o=c;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)j=j<<1,A==t-1?(A=0,a.push(r(j)),j=0):A++;for(f=o.charCodeAt(0),u=0;u<8;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}else{for(f=1,u=0;u<O;u++)j=j<<1|f,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete n[o]}else for(f=i[o],u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),i[c]=m++,o=String(p)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)j=j<<1,A==t-1?(A=0,a.push(r(j)),j=0):A++;for(f=o.charCodeAt(0),u=0;u<8;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}else{for(f=1,u=0;u<O;u++)j=j<<1|f,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete n[o]}else for(f=i[o],u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;for(;;)if(j=j<<1,A==t-1){a.push(r(j));break}else A++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:ZDn._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,f=4,p=3,c="",o,l,m,O,j,A,T;for(o=0;o<3;o+=1)i[o]=o;for(m=0,j=Math.pow(2,2),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;switch(m){case 0:for(m=0,j=Math.pow(2,8),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;T=XDn(m);break;case 1:for(m=0,j=Math.pow(2,16),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;T=XDn(m);break;case 2:return""}for(i[3]=T,l=T,n.push(T);;){if(a.index>e)return"";for(m=0,j=Math.pow(2,p),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;switch(T=m){case 0:for(m=0,j=Math.pow(2,8),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;i[f++]=XDn(m),T=f-1,u--;break;case 1:for(m=0,j=Math.pow(2,16),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;i[f++]=XDn(m),T=f-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,p),p++),i[T])c=i[T];else if(T===f)c=l+l.charAt(0);else return null;n.push(c),i[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,p),p++)}}},VAu=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 WMa="0123456789abcdef",HMa=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+=WMa.charAt(this.bytes[r]>>>4),t+=WMa.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+=WMa.charAt(this.bytes[r]>>>4),t+=WMa.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}},WAu=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Ilw()}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 HMa.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,HMa.ofInner(t)}},Ilw=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),h7f,y7f=()=>zlw().toString(),zlw=()=>(h7f||(h7f=new WAu)).generate(),JMa=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},kDn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function v7f(e){return typeof e=="object"&&(e instanceof JMa||e instanceof kDn)}var HAu=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new VAu,this._isInitialized=!1,Tlw(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=qlw(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:v7f},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(t3t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(t3t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(t3t.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=y7f();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 f=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",f,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,f={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,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).catch(p=>{this._events.emit("error",p)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let f=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!f)return;let p=f[t];return p===void 0&&(p=!1),p}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let f=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!f)return;let p=f[t];return p===void 0?null:p}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 f=await this.getDecide(t,r,i,n,u),p=f?.featureFlags,c=f?.featureFlagPayloads,o=c;return c&&(o=Object.fromEntries(Object.entries(c).map(([l,m])=>[l,this._parsePayload(m)]))),{flags:p,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:p7f(),uuid:i?.uuid?i.uuid:y7f()};(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(t3t.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(t3t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P7f(()=>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(t3t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(c=>c.message),n=()=>{let c=this.getPersistedProperty(t3t.Queue)||[];this.setPersistedProperty(t3t.Queue,c.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:p7f()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),f=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${xlw()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,p=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ZDn.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(f,p)}catch(c){throw c instanceof kDn||n(),this._events.emit("error",c),c}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(f){let p=new AbortController;return setTimeout(()=>p.abort(),f),p.signal}),await Clw(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(p){throw new kDn(p)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new JMa(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(t3t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!v7f(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},JAu=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},QAu=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!QAu){let e=d7f();QAu=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 j7f=QAu,Nlw=1152921504606847e3,Flw=["is_not"],QMa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},g5=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},GAu=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...f}){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=f.fetch||j7f,this.onError=f.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,f;if(!this.loadedSuccessfullyOnce)return u;for(let p of this.featureFlags)if(t===p.key){f=p;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(p){p instanceof g5?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${p}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${p}`))}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={},f=this.featureFlags.length==0;return this.featureFlags.map(async p=>{try{let c=this.computeFlagLocally(p,t,r,i,n);a[p.key]=c;let o=await this.computeFeatureFlagPayloadLocally(p.key,c);o&&(u[p.key]=o)}catch(c){c instanceof g5||c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${p.key}: ${c}`)),f=!0}}),{response:a,payloads:u,fallbackToDecide:f}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new g5("Flag has experience continuity enabled");if(!t.active)return!1;let f=(t.filters||{}).aggregation_group_type_index;if(f!=null){let p=this.groupTypeMapping[String(f)];if(!p)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${f} for feature flag ${t.key}`)),new g5("Flag has unknown group type index");if(!(p in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let c=a[p];return this.matchFeatureFlagProperties(t,i[p],c)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,f,p=[...a].sort((c,o)=>{let l=!!c.variant,m=!!o.variant;return l&&m?0:l?-1:m?1:0});for(let c of p)try{if(this.isConditionMatch(t,r,c,i)){let o=c.variant,l=n.multivariate?.variants||[];o&&l.some(m=>m.key===o)?f=o:f=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof g5)u=!0;else throw o}if(f!==void 0)return f;if(u)throw new g5("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=f=>{this.logMsgIfDebug(()=>console.warn(f))};if((i.properties||[]).length>0){for(let f of i.properties){let p=f.type,c=!1;if(p==="cohort"?c=D7f(f,n,this.cohorts,this.debugMode):c=w7f(f,n,u),!c)return!1}if(a==null)return!0}return!(a!=null&&b7f(t.key,r)>a/100)}getMatchingVariant(t,r){let i=b7f(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(f=>{n=i+f.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:f.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 QMa("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 QMa&&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=P7f(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function b7f(e,t,r=""){let i=(0,O7f.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/Nlw}function w7f(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 g5("Operator is_not_set is not supported")}else throw new g5(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!Flw.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function f(c,o){return Array.isArray(c)?c.map(l=>String(l).toLowerCase()).includes(String(o).toLowerCase()):String(c).toLowerCase()===String(o).toLowerCase()}function p(c,o,l){if(l==="gt")return c>o;if(l==="gte")return c>=o;if(l==="lt")return c<o;if(l==="lte")return c<=o;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return f(n,u);case"is_not":return!f(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 g7f(String(n))&&String(u).match(String(n))!==null;case"not_regex":return g7f(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof n=="number"?n:null;if(typeof n=="string")try{c=parseFloat(n)}catch{}return c!=null&&u!=null?typeof u=="string"?p(u,String(n),a):p(u,c,a):p(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let c=Rlw(String(n));if(c==null&&(c=m7f(n)),c==null)throw new g5(`Invalid date: ${n}`);let o=m7f(u);return["is_date_before"].includes(a)?o<c:o>c}default:throw new g5(`Unknown operator: ${a}`)}}function D7f(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new g5("can't match cohort without a given cohort property value");let a=r[n];return S7f(a,t,r,i)}function S7f(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 f of a)try{let p=S7f(f,t,r,i);if(n==="AND"){if(!p)return!1}else if(p)return!0}catch(p){if(p instanceof g5)i&&console.debug(`Failed to compute property ${f} locally: ${p}`),u=!0;else throw p}if(u)throw new g5("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let f of a)try{let p;f.type==="cohort"?p=D7f(f,t,r,i):p=w7f(f,t);let c=f.negation||!1;if(n==="AND"){if(!p&&!c||p&&c)return!1}else if(p&&!c||!p&&c)return!0}catch(p){if(p instanceof g5)i&&console.debug(`Failed to compute property ${f} locally: ${p}`),u=!0;else throw p}if(u)throw new g5("can't match cohort without a given cohort property value");return n==="AND"}}function g7f(e){try{return new RegExp(e),!0}catch{return!1}}function m7f(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 g5(`${e} is in an invalid date format`)}else throw new g5(`The date provided ${e} must be a string, number, or date object`)}function Rlw(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 Llw=30*1e3,Ulw=50*1e3,tLi=class extends HAu{constructor(t,r={}){super(t,r),this._memoryStorage=new JAu,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new GAu({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:Llw,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||Ulw}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):j7f(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return Mlw}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:f,uuid:p}){let c=m=>{super.captureStateless(t,r,m,{timestamp:u,disableGeoip:f,uuid:p})},o=(m,O,j)=>super.getFeatureFlagsStateless(m,O,void 0,void 0,j),l=Promise.resolve().then(async()=>{if(a)return await o(t,n,f);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let m={};for(let[O,j]of Object.entries(n||{}))m[O]=String(j);return await this.getAllFlags(t,{groups:m,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(m=>{let O={};if(m)for(let[A,T]of Object.entries(m))O[`$feature/${A}`]=T;let j=Object.keys(m||{}).filter(A=>m?.[A]!==!1);return j.length>0&&(O.$active_feature_flags=j),O}).catch(()=>({})).then(m=>{c({...m,...i,$groups:n})});this.addPendingPromise(l)}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:f,personProperties:p,groupProperties:c}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,p,c);p=o.allPersonProperties,c=o.allGroupProperties,u==null&&(u=!1),f==null&&(f=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,p,c),m=l!==void 0;!m&&!u&&(l=await super.getFeatureFlagStateless(t,r,n,p,c,a));let O=`${t}_${l}`;return f&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(O))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(O):this.distinctIdHasSentFlagCalls[r]=[O],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,locally_evaluated:m,[`$feature/${t}`]:l},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:f,sendFeatureFlagEvents:p,personProperties:c,groupProperties:o}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,c,o);c=l.allPersonProperties,o=l.allGroupProperties;let m;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(m=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),f==null&&(f=!1),p==null&&(p=!0),f==null&&(f=!1),!(m!==void 0)&&!f&&(m=await super.getFeatureFlagPayloadStateless(t,r,a,c,o,u)),m}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:f}=r||{},p=this.addLocalPersonAndGroupProperties(t,i,u,f);u=p.allPersonProperties,f=p.allGroupProperties,a==null&&(a=!1);let c=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,f),o={},l={},m=!0;if(c&&(o=c.response,l=c.payloads,m=c.fallbackToDecide),m&&!a){let O=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,f,n);o={...o,...O.flags||{}},l={...l,...O.payloads||{}}}return{featureFlags:o,featureFlagPayloads:l}}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 f of Object.keys(r))u[f]={$group_key:r[f],...n?.[f]||{}};return{allPersonProperties:a,allGroupProperties:u}}},$Au=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},f=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&f!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${f}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};$Au.POSTHOG_ID_TAG="posthog_distinct_id";var GMa=class{posthog;constructor({posthogApiKey:t}){this.posthog=new tLi(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.46.8",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var eSn=class{async sendEvent(){}async identify(){}async flush(){}};var rLi=require("fs/promises"),T7f=require("os"),q7f=require("path");var E7f=bo(require("crypto")),KMa=new Uint8Array(256),$Ma=KMa.length;function KAu(){return $Ma>KMa.length-16&&(E7f.default.randomFillSync(KMa),$Ma=0),KMa.slice($Ma,$Ma+=16)}var jH=[];for(let e=0;e<256;++e)jH.push((e+256).toString(16).slice(1));function A7f(e,t=0){return jH[e[t+0]]+jH[e[t+1]]+jH[e[t+2]]+jH[e[t+3]]+"-"+jH[e[t+4]]+jH[e[t+5]]+"-"+jH[e[t+6]]+jH[e[t+7]]+"-"+jH[e[t+8]]+jH[e[t+9]]+"-"+jH[e[t+10]]+jH[e[t+11]]+jH[e[t+12]]+jH[e[t+13]]+jH[e[t+14]]+jH[e[t+15]]}var M7f=bo(require("crypto")),YAu={randomUUID:M7f.default.randomUUID};function Vlw(e,t,r){if(YAu.randomUUID&&!t&&!e)return YAu.randomUUID();e=e||{};let i=e.random||(e.rng||KAu)();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 A7f(i)}var pHt=Vlw;var Wlw="id",Hlw=".fern",tSn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new tLi(r),this.userId=t==null?void 0:cPu(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.46.8",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Sf(f_.of((0,T7f.homedir)()),Pc.of(Hlw),Pc.of(Wlw));await _h(t)||(await(0,rLi.mkdir)((0,q7f.dirname)(t),{recursive:!0}),await(0,rLi.writeFile)(t,pHt())),this.persistedDistinctId=(await(0,rLi.readFile)(t)).toString()}return this.persistedDistinctId}};var XAu;async function iLi(){return XAu==null&&(XAu=await Jlw()),XAu}async function Jlw(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new eSn;let r=await Qja();return r!=null?new tSn({token:r,posthogApiKey:e}):await Jja()!=null?new GMa({posthogApiKey:e}):new tSn({token:void 0,posthogApiKey:e})}catch{return new eSn}}function rSn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Qlw}=Object.prototype,{getPrototypeOf:eMu}=Object,XMa=(e=>t=>{let r=Qlw.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),r3t=e=>(e=e.toLowerCase(),t=>XMa(t)===e),ZMa=e=>t=>typeof t===e,{isArray:nLi}=Array,iSn=ZMa("undefined");function Glw(e){return e!==null&&!iSn(e)&&e.constructor!==null&&!iSn(e.constructor)&&sSe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var B7f=r3t("ArrayBuffer");function $lw(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&B7f(e.buffer),t}var Klw=ZMa("string"),sSe=ZMa("function"),I7f=ZMa("number"),kMa=e=>e!==null&&typeof e=="object",Ylw=e=>e===!0||e===!1,YMa=e=>{if(XMa(e)!=="object")return!1;let t=eMu(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Xlw=r3t("Date"),Zlw=r3t("File"),klw=r3t("Blob"),efw=r3t("FileList"),tfw=e=>kMa(e)&&sSe(e.pipe),rfw=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||sSe(e.append)&&((t=XMa(e))==="formdata"||t==="object"&&sSe(e.toString)&&e.toString()==="[object FormData]"))},ifw=r3t("URLSearchParams"),[nfw,afw,ofw,ufw]=["ReadableStream","Request","Response","Headers"].map(r3t),sfw=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function nSn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),nLi(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,f;for(i=0;i<u;i++)f=a[i],t.call(null,e[f],f,e)}}function z7f(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 wli=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,N7f=e=>!iSn(e)&&e!==wli;function kAu(){let{caseless:e}=N7f(this)&&this||{},t={},r=(i,n)=>{let a=e&&z7f(t,n)||n;YMa(t[a])&&YMa(i)?t[a]=kAu(t[a],i):YMa(i)?t[a]=kAu({},i):nLi(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&nSn(arguments[i],r);return t}var cfw=(e,t,r,{allOwnKeys:i}={})=>(nSn(t,(n,a)=>{r&&sSe(n)?e[a]=rSn(n,r):e[a]=n},{allOwnKeys:i}),e),lfw=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ffw=(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)},dfw=(e,t,r,i)=>{let n,a,u,f={};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))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&eMu(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},pfw=(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},_fw=e=>{if(!e)return null;if(nLi(e))return e;let t=e.length;if(!I7f(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},hfw=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&eMu(Uint8Array)),yfw=(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])}},vfw=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},bfw=r3t("HTMLFormElement"),gfw=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),C7f=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),mfw=r3t("RegExp"),F7f=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};nSn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},Ofw=e=>{F7f(e,(t,r)=>{if(sSe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(sSe(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+"'")})}})},Pfw=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return nLi(e)?i(e):i(String(e).split(t)),r},jfw=()=>{},wfw=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,ZAu="abcdefghijklmnopqrstuvwxyz",x7f="0123456789",R7f={DIGIT:x7f,ALPHA:ZAu,ALPHA_DIGIT:ZAu+ZAu.toUpperCase()+x7f},Dfw=(e=16,t=R7f.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function Sfw(e){return!!(e&&sSe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var Efw=e=>{let t=new Array(10),r=(i,n)=>{if(kMa(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=nLi(i)?[]:{};return nSn(i,(u,f)=>{let p=r(u,n+1);!iSn(p)&&(a[f]=p)}),t[n]=void 0,a}}return i};return r(e,0)},Afw=r3t("AsyncFunction"),Mfw=e=>e&&(kMa(e)||sSe(e))&&sSe(e.then)&&sSe(e.catch),L7f=((e,t)=>e?setImmediate:t?((r,i)=>(wli.addEventListener("message",({source:n,data:a})=>{n===wli&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),wli.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",sSe(wli.postMessage)),Tfw=typeof queueMicrotask<"u"?queueMicrotask.bind(wli):typeof process<"u"&&process.nextTick||L7f,jl={isArray:nLi,isArrayBuffer:B7f,isBuffer:Glw,isFormData:rfw,isArrayBufferView:$lw,isString:Klw,isNumber:I7f,isBoolean:Ylw,isObject:kMa,isPlainObject:YMa,isReadableStream:nfw,isRequest:afw,isResponse:ofw,isHeaders:ufw,isUndefined:iSn,isDate:Xlw,isFile:Zlw,isBlob:klw,isRegExp:mfw,isFunction:sSe,isStream:tfw,isURLSearchParams:ifw,isTypedArray:hfw,isFileList:efw,forEach:nSn,merge:kAu,extend:cfw,trim:sfw,stripBOM:lfw,inherits:ffw,toFlatObject:dfw,kindOf:XMa,kindOfTest:r3t,endsWith:pfw,toArray:_fw,forEachEntry:yfw,matchAll:vfw,isHTMLForm:bfw,hasOwnProperty:C7f,hasOwnProp:C7f,reduceDescriptors:F7f,freezeMethods:Ofw,toObjectSet:Pfw,toCamelCase:gfw,noop:jfw,toFiniteNumber:wfw,findKey:z7f,global:wli,isContextDefined:N7f,ALPHABET:R7f,generateString:Dfw,isSpecCompliantForm:Sfw,toJSONObject:Efw,isAsyncFn:Afw,isThenable:Mfw,setImmediate:L7f,asap:Tfw};function aLi(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)}jl.inherits(aLi,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:jl.toJSONObject(this.config),code:this.code,status:this.status}}});var U7f=aLi.prototype,V7f={};["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=>{V7f[e]={value:e}});Object.defineProperties(aLi,V7f);Object.defineProperty(U7f,"isAxiosError",{value:!0});aLi.from=(e,t,r,i,n,a)=>{let u=Object.create(U7f);return jl.toFlatObject(e,u,function(p){return p!==Error.prototype},f=>f!=="isAxiosError"),aLi.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var hy=aLi;var W7f=bo(ELr(),1),eTa=W7f.default;function tMu(e){return jl.isPlainObject(e)||jl.isArray(e)}function J7f(e){return jl.endsWith(e,"[]")?e.slice(0,-2):e}function H7f(e,t,r){return e?e.concat(t).map(function(n,a){return n=J7f(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function qfw(e){return jl.isArray(e)&&!e.some(tMu)}var Cfw=jl.toFlatObject(jl,{},null,function(t){return/^is[A-Z]/.test(t)});function xfw(e,t,r){if(!jl.isObject(e))throw new TypeError("target must be an object");t=t||new(eTa||FormData),r=jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,T){return!jl.isUndefined(T[A])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,p=(r.Blob||typeof Blob<"u"&&Blob)&&jl.isSpecCompliantForm(t);if(!jl.isFunction(n))throw new TypeError("visitor must be a function");function c(j){if(j===null)return"";if(jl.isDate(j))return j.toISOString();if(!p&&jl.isBlob(j))throw new hy("Blob is not supported. Use a Buffer instead.");return jl.isArrayBuffer(j)||jl.isTypedArray(j)?p&&typeof Blob=="function"?new Blob([j]):Buffer.from(j):j}function o(j,A,T){let B=j;if(j&&!T&&typeof j=="object"){if(jl.endsWith(A,"{}"))A=i?A:A.slice(0,-2),j=JSON.stringify(j);else if(jl.isArray(j)&&qfw(j)||(jl.isFileList(j)||jl.endsWith(A,"[]"))&&(B=jl.toArray(j)))return A=J7f(A),B.forEach(function(C,N){!(jl.isUndefined(C)||C===null)&&t.append(u===!0?H7f([A],N,a):u===null?A:A+"[]",c(C))}),!1}return tMu(j)?!0:(t.append(H7f(T,A,a),c(j)),!1)}let l=[],m=Object.assign(Cfw,{defaultVisitor:o,convertValue:c,isVisitable:tMu});function O(j,A){if(!jl.isUndefined(j)){if(l.indexOf(j)!==-1)throw Error("Circular reference detected in "+A.join("."));l.push(j),jl.forEach(j,function(B,z){(!(jl.isUndefined(B)||B===null)&&n.call(t,B,jl.isString(z)?z.trim():z,A,m))===!0&&O(B,A?A.concat(z):[z])}),l.pop()}}if(!jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var TVr=xfw;function Q7f(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function G7f(e,t){this._pairs=[],e&&TVr(e,this,t)}var $7f=G7f.prototype;$7f.append=function(t,r){this._pairs.push([t,r])};$7f.toString=function(t){let r=t?function(i){return t.call(this,i,Q7f)}:Q7f;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var K7f=G7f;function Bfw(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Dli(e,t,r){if(!t)return e;let i=r&&r.encode||Bfw,n=r&&r.serialize,a;if(n?a=n(t,r):a=jl.isURLSearchParams(t)?t.toString():new K7f(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var rMu=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){jl.forEach(this.handlers,function(i){i!==null&&t(i)})}},iMu=rMu;var oLi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Y7f=bo(require("url"),1),X7f=Y7f.default.URLSearchParams;var Z7f={isNode:!0,classes:{URLSearchParams:X7f,FormData:eTa,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var oMu={};Gs(oMu,{hasBrowserEnv:()=>aMu,hasStandardBrowserEnv:()=>Ifw,hasStandardBrowserWebWorkerEnv:()=>zfw,navigator:()=>nMu,origin:()=>Nfw});var aMu=typeof window<"u"&&typeof document<"u",nMu=typeof navigator=="object"&&navigator||void 0,Ifw=aMu&&(!nMu||["ReactNative","NativeScript","NS"].indexOf(nMu.product)<0),zfw=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Nfw=aMu&&window.location.href||"http://localhost";var kB={...oMu,...Z7f};function uMu(e,t){return TVr(e,new kB.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return kB.isNode&&jl.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function Ffw(e){return jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Rfw(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 Lfw(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),p=a>=r.length;return u=!u&&jl.isArray(n)?n.length:u,p?(jl.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!f):((!n[u]||!jl.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&jl.isArray(n[u])&&(n[u]=Rfw(n[u])),!f)}if(jl.isFormData(e)&&jl.isFunction(e.entries)){let r={};return jl.forEachEntry(e,(i,n)=>{t(Ffw(i),n,r,0)}),r}return null}var tTa=Lfw;function Ufw(e,t,r){if(jl.isString(e))try{return(t||JSON.parse)(e),jl.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var sMu={transitional:oLi,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=jl.isObject(t);if(a&&jl.isHTMLForm(t)&&(t=new FormData(t)),jl.isFormData(t))return n?JSON.stringify(tTa(t)):t;if(jl.isArrayBuffer(t)||jl.isBuffer(t)||jl.isStream(t)||jl.isFile(t)||jl.isBlob(t)||jl.isReadableStream(t))return t;if(jl.isArrayBufferView(t))return t.buffer;if(jl.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let f;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return uMu(t,this.formSerializer).toString();if((f=jl.isFileList(t))||i.indexOf("multipart/form-data")>-1){let p=this.env&&this.env.FormData;return TVr(f?{"files[]":t}:t,p&&new p,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),Ufw(t)):t}],transformResponse:[function(t){let r=this.transitional||sMu.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(jl.isResponse(t)||jl.isReadableStream(t))return t;if(t&&jl.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?hy.from(f,hy.ERR_BAD_RESPONSE,this,null,this.response):f}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:kB.classes.FormData,Blob:kB.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};jl.forEach(["delete","get","head","post","put","patch"],e=>{sMu.headers[e]={}});var uLi=sMu;var Vfw=jl.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"]),k7f=e=>{let t={},r,i,n;return e&&e.split(`
1789
+ `}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&&iMa(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var uNf=bo(eNf(),1),sNf=bo(tSu(),1),cNf=bo(aNf(),1),mC=bo(oSe(),1),lNf=bo(A1n(),1);var EMa=bo(oSe(),1),oNf=bo(A1n(),1),AMa=function(e,t,r){return typeof e[t]!="function"?(0,EMa.of)(e):(0,EMa.from)((0,oNf.default)(e[t])(r).then(i=>(e[t]=i,e)))};var LDn={isPlainObject:uNf.default,set:cNf.default,get:sNf.default},$9i=class extends mli{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=LDn.isPlainObject(r)?{...r}:{},LDn.isPlainObject(t)&&(t=Object.values(t).every(n=>LDn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,mC.from)(t):t;return this.process=i.pipe((0,mC.concatMap)(this.processQuestion.bind(this)),(0,mC.publish)()),this.process.connect(),this.process.pipe((0,mC.reduce)((n,a)=>(LDn.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,mC.defer)(()=>(0,mC.of)(t).pipe((0,mC.concatMap)(this.setDefaultType.bind(this)),(0,mC.concatMap)(this.filterIfRunnable.bind(this)),(0,mC.concatMap)(()=>AMa(t,"message",this.answers)),(0,mC.concatMap)(()=>AMa(t,"default",this.answers)),(0,mC.concatMap)(()=>AMa(t,"choices",this.answers)),(0,mC.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,mC.defer)(()=>(0,mC.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,mC.defer)(()=>(0,mC.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&LDn.get(this.answers,t.name)!==void 0)return(0,mC.empty)();if(t.when===!1)return(0,mC.empty)();if(typeof t.when!="function")return(0,mC.of)(t);let{answers:r}=this;return(0,mC.defer)(()=>(0,mC.from)((0,lNf.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,mC.filter)(i=>i!=null)))}};function fNf(e){let t=function(r,i){let n;try{n=new $9i(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",PDn),this.registerPrompt("input",dli),this.registerPrompt("number",jDn),this.registerPrompt("confirm",wDn),this.registerPrompt("rawlist",DDn),this.registerPrompt("expand",SDn),this.registerPrompt("checkbox",EDn),this.registerPrompt("password",ADn),this.registerPrompt("editor",FDn)},t.restoreDefaultPrompts(),t}var tAu=fNf();function isw(e,t){tAu.registerPrompt(e,t)}function nsw(){tAu.restoreDefaultPrompts()}var asw={prompt:tAu,ui:{BottomBar:RDn,Prompt:$9i},createPromptModule:fNf,registerPrompt:isw,restoreDefaultPrompts:nsw,Separator:Gne},MMa=asw;var O7f=bo(dNf()),Mlw="4.2.1",t3t;(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"})(t3t||(t3t={}));function Tlw(e,t){if(!e)throw new Error(t)}function qlw(e){return e?.replace(/\/+$/,"")}async function Clw(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 xlw(){return new Date().getTime()}function p7f(){return new Date().toISOString()}function P7f(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var XDn=String.fromCharCode,_7f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",VMa={};function Blw(e,t){if(!VMa[e]){VMa[e]={};for(let r=0;r<e.length;r++)VMa[e][e.charAt(r)]=r}return VMa[e][t]}var ZDn={compressToBase64:function(e){if(e==null)return"";let t=ZDn._compress(e,6,function(r){return _7f.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:ZDn._decompress(e.length,32,function(t){return Blw(_7f,e.charAt(t))})},compress:function(e){return ZDn._compress(e,16,function(t){return XDn(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,f,p="",c="",o="",l=2,m=3,O=2,j=0,A=0,T;for(T=0;T<e.length;T+=1)if(p=e.charAt(T),Object.prototype.hasOwnProperty.call(i,p)||(i[p]=m++,n[p]=!0),c=o+p,Object.prototype.hasOwnProperty.call(i,c))o=c;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)j=j<<1,A==t-1?(A=0,a.push(r(j)),j=0):A++;for(f=o.charCodeAt(0),u=0;u<8;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}else{for(f=1,u=0;u<O;u++)j=j<<1|f,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete n[o]}else for(f=i[o],u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),i[c]=m++,o=String(p)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)j=j<<1,A==t-1?(A=0,a.push(r(j)),j=0):A++;for(f=o.charCodeAt(0),u=0;u<8;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}else{for(f=1,u=0;u<O;u++)j=j<<1|f,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete n[o]}else for(f=i[o],u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)j=j<<1|f&1,A==t-1?(A=0,a.push(r(j)),j=0):A++,f=f>>1;for(;;)if(j=j<<1,A==t-1){a.push(r(j));break}else A++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:ZDn._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,f=4,p=3,c="",o,l,m,O,j,A,T;for(o=0;o<3;o+=1)i[o]=o;for(m=0,j=Math.pow(2,2),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;switch(m){case 0:for(m=0,j=Math.pow(2,8),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;T=XDn(m);break;case 1:for(m=0,j=Math.pow(2,16),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;T=XDn(m);break;case 2:return""}for(i[3]=T,l=T,n.push(T);;){if(a.index>e)return"";for(m=0,j=Math.pow(2,p),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;switch(T=m){case 0:for(m=0,j=Math.pow(2,8),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;i[f++]=XDn(m),T=f-1,u--;break;case 1:for(m=0,j=Math.pow(2,16),A=1;A!=j;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(O>0?1:0)*A,A<<=1;i[f++]=XDn(m),T=f-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,p),p++),i[T])c=i[T];else if(T===f)c=l+l.charAt(0);else return null;n.push(c),i[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,p),p++)}}},VAu=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 WMa="0123456789abcdef",HMa=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+=WMa.charAt(this.bytes[r]>>>4),t+=WMa.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+=WMa.charAt(this.bytes[r]>>>4),t+=WMa.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}},WAu=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Ilw()}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 HMa.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,HMa.ofInner(t)}},Ilw=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),h7f,y7f=()=>zlw().toString(),zlw=()=>(h7f||(h7f=new WAu)).generate(),JMa=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},kDn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function v7f(e){return typeof e=="object"&&(e instanceof JMa||e instanceof kDn)}var HAu=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new VAu,this._isInitialized=!1,Tlw(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=qlw(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:v7f},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(t3t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(t3t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(t3t.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=y7f();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 f=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",f,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,f={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,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).catch(p=>{this._events.emit("error",p)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let f=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!f)return;let p=f[t];return p===void 0&&(p=!1),p}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let f=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!f)return;let p=f[t];return p===void 0?null:p}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 f=await this.getDecide(t,r,i,n,u),p=f?.featureFlags,c=f?.featureFlagPayloads,o=c;return c&&(o=Object.fromEntries(Object.entries(c).map(([l,m])=>[l,this._parsePayload(m)]))),{flags:p,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:p7f(),uuid:i?.uuid?i.uuid:y7f()};(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(t3t.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(t3t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P7f(()=>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(t3t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(c=>c.message),n=()=>{let c=this.getPersistedProperty(t3t.Queue)||[];this.setPersistedProperty(t3t.Queue,c.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:p7f()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),f=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${xlw()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,p=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ZDn.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(f,p)}catch(c){throw c instanceof kDn||n(),this._events.emit("error",c),c}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(f){let p=new AbortController;return setTimeout(()=>p.abort(),f),p.signal}),await Clw(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(p){throw new kDn(p)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new JMa(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(t3t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!v7f(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},JAu=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},QAu=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!QAu){let e=d7f();QAu=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 j7f=QAu,Nlw=1152921504606847e3,Flw=["is_not"],QMa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},g5=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},GAu=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...f}){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=f.fetch||j7f,this.onError=f.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,f;if(!this.loadedSuccessfullyOnce)return u;for(let p of this.featureFlags)if(t===p.key){f=p;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(p){p instanceof g5?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${p}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${p}`))}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={},f=this.featureFlags.length==0;return this.featureFlags.map(async p=>{try{let c=this.computeFlagLocally(p,t,r,i,n);a[p.key]=c;let o=await this.computeFeatureFlagPayloadLocally(p.key,c);o&&(u[p.key]=o)}catch(c){c instanceof g5||c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${p.key}: ${c}`)),f=!0}}),{response:a,payloads:u,fallbackToDecide:f}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new g5("Flag has experience continuity enabled");if(!t.active)return!1;let f=(t.filters||{}).aggregation_group_type_index;if(f!=null){let p=this.groupTypeMapping[String(f)];if(!p)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${f} for feature flag ${t.key}`)),new g5("Flag has unknown group type index");if(!(p in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let c=a[p];return this.matchFeatureFlagProperties(t,i[p],c)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,f,p=[...a].sort((c,o)=>{let l=!!c.variant,m=!!o.variant;return l&&m?0:l?-1:m?1:0});for(let c of p)try{if(this.isConditionMatch(t,r,c,i)){let o=c.variant,l=n.multivariate?.variants||[];o&&l.some(m=>m.key===o)?f=o:f=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof g5)u=!0;else throw o}if(f!==void 0)return f;if(u)throw new g5("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=f=>{this.logMsgIfDebug(()=>console.warn(f))};if((i.properties||[]).length>0){for(let f of i.properties){let p=f.type,c=!1;if(p==="cohort"?c=D7f(f,n,this.cohorts,this.debugMode):c=w7f(f,n,u),!c)return!1}if(a==null)return!0}return!(a!=null&&b7f(t.key,r)>a/100)}getMatchingVariant(t,r){let i=b7f(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(f=>{n=i+f.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:f.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 QMa("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 QMa&&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=P7f(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function b7f(e,t,r=""){let i=(0,O7f.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/Nlw}function w7f(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 g5("Operator is_not_set is not supported")}else throw new g5(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!Flw.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function f(c,o){return Array.isArray(c)?c.map(l=>String(l).toLowerCase()).includes(String(o).toLowerCase()):String(c).toLowerCase()===String(o).toLowerCase()}function p(c,o,l){if(l==="gt")return c>o;if(l==="gte")return c>=o;if(l==="lt")return c<o;if(l==="lte")return c<=o;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return f(n,u);case"is_not":return!f(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 g7f(String(n))&&String(u).match(String(n))!==null;case"not_regex":return g7f(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof n=="number"?n:null;if(typeof n=="string")try{c=parseFloat(n)}catch{}return c!=null&&u!=null?typeof u=="string"?p(u,String(n),a):p(u,c,a):p(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let c=Rlw(String(n));if(c==null&&(c=m7f(n)),c==null)throw new g5(`Invalid date: ${n}`);let o=m7f(u);return["is_date_before"].includes(a)?o<c:o>c}default:throw new g5(`Unknown operator: ${a}`)}}function D7f(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new g5("can't match cohort without a given cohort property value");let a=r[n];return S7f(a,t,r,i)}function S7f(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 f of a)try{let p=S7f(f,t,r,i);if(n==="AND"){if(!p)return!1}else if(p)return!0}catch(p){if(p instanceof g5)i&&console.debug(`Failed to compute property ${f} locally: ${p}`),u=!0;else throw p}if(u)throw new g5("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let f of a)try{let p;f.type==="cohort"?p=D7f(f,t,r,i):p=w7f(f,t);let c=f.negation||!1;if(n==="AND"){if(!p&&!c||p&&c)return!1}else if(p&&!c||!p&&c)return!0}catch(p){if(p instanceof g5)i&&console.debug(`Failed to compute property ${f} locally: ${p}`),u=!0;else throw p}if(u)throw new g5("can't match cohort without a given cohort property value");return n==="AND"}}function g7f(e){try{return new RegExp(e),!0}catch{return!1}}function m7f(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 g5(`${e} is in an invalid date format`)}else throw new g5(`The date provided ${e} must be a string, number, or date object`)}function Rlw(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 Llw=30*1e3,Ulw=50*1e3,tLi=class extends HAu{constructor(t,r={}){super(t,r),this._memoryStorage=new JAu,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new GAu({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:Llw,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||Ulw}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):j7f(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return Mlw}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:f,uuid:p}){let c=m=>{super.captureStateless(t,r,m,{timestamp:u,disableGeoip:f,uuid:p})},o=(m,O,j)=>super.getFeatureFlagsStateless(m,O,void 0,void 0,j),l=Promise.resolve().then(async()=>{if(a)return await o(t,n,f);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let m={};for(let[O,j]of Object.entries(n||{}))m[O]=String(j);return await this.getAllFlags(t,{groups:m,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(m=>{let O={};if(m)for(let[A,T]of Object.entries(m))O[`$feature/${A}`]=T;let j=Object.keys(m||{}).filter(A=>m?.[A]!==!1);return j.length>0&&(O.$active_feature_flags=j),O}).catch(()=>({})).then(m=>{c({...m,...i,$groups:n})});this.addPendingPromise(l)}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:f,personProperties:p,groupProperties:c}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,p,c);p=o.allPersonProperties,c=o.allGroupProperties,u==null&&(u=!1),f==null&&(f=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,p,c),m=l!==void 0;!m&&!u&&(l=await super.getFeatureFlagStateless(t,r,n,p,c,a));let O=`${t}_${l}`;return f&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(O))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(O):this.distinctIdHasSentFlagCalls[r]=[O],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,locally_evaluated:m,[`$feature/${t}`]:l},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:f,sendFeatureFlagEvents:p,personProperties:c,groupProperties:o}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,c,o);c=l.allPersonProperties,o=l.allGroupProperties;let m;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(m=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),f==null&&(f=!1),p==null&&(p=!0),f==null&&(f=!1),!(m!==void 0)&&!f&&(m=await super.getFeatureFlagPayloadStateless(t,r,a,c,o,u)),m}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:f}=r||{},p=this.addLocalPersonAndGroupProperties(t,i,u,f);u=p.allPersonProperties,f=p.allGroupProperties,a==null&&(a=!1);let c=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,f),o={},l={},m=!0;if(c&&(o=c.response,l=c.payloads,m=c.fallbackToDecide),m&&!a){let O=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,f,n);o={...o,...O.flags||{}},l={...l,...O.payloads||{}}}return{featureFlags:o,featureFlagPayloads:l}}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 f of Object.keys(r))u[f]={$group_key:r[f],...n?.[f]||{}};return{allPersonProperties:a,allGroupProperties:u}}},$Au=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},f=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&f!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${f}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};$Au.POSTHOG_ID_TAG="posthog_distinct_id";var GMa=class{posthog;constructor({posthogApiKey:t}){this.posthog=new tLi(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.46.10",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var eSn=class{async sendEvent(){}async identify(){}async flush(){}};var rLi=require("fs/promises"),T7f=require("os"),q7f=require("path");var E7f=bo(require("crypto")),KMa=new Uint8Array(256),$Ma=KMa.length;function KAu(){return $Ma>KMa.length-16&&(E7f.default.randomFillSync(KMa),$Ma=0),KMa.slice($Ma,$Ma+=16)}var jH=[];for(let e=0;e<256;++e)jH.push((e+256).toString(16).slice(1));function A7f(e,t=0){return jH[e[t+0]]+jH[e[t+1]]+jH[e[t+2]]+jH[e[t+3]]+"-"+jH[e[t+4]]+jH[e[t+5]]+"-"+jH[e[t+6]]+jH[e[t+7]]+"-"+jH[e[t+8]]+jH[e[t+9]]+"-"+jH[e[t+10]]+jH[e[t+11]]+jH[e[t+12]]+jH[e[t+13]]+jH[e[t+14]]+jH[e[t+15]]}var M7f=bo(require("crypto")),YAu={randomUUID:M7f.default.randomUUID};function Vlw(e,t,r){if(YAu.randomUUID&&!t&&!e)return YAu.randomUUID();e=e||{};let i=e.random||(e.rng||KAu)();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 A7f(i)}var pHt=Vlw;var Wlw="id",Hlw=".fern",tSn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new tLi(r),this.userId=t==null?void 0:cPu(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.46.10",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Sf(f_.of((0,T7f.homedir)()),Pc.of(Hlw),Pc.of(Wlw));await _h(t)||(await(0,rLi.mkdir)((0,q7f.dirname)(t),{recursive:!0}),await(0,rLi.writeFile)(t,pHt())),this.persistedDistinctId=(await(0,rLi.readFile)(t)).toString()}return this.persistedDistinctId}};var XAu;async function iLi(){return XAu==null&&(XAu=await Jlw()),XAu}async function Jlw(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new eSn;let r=await Qja();return r!=null?new tSn({token:r,posthogApiKey:e}):await Jja()!=null?new GMa({posthogApiKey:e}):new tSn({token:void 0,posthogApiKey:e})}catch{return new eSn}}function rSn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Qlw}=Object.prototype,{getPrototypeOf:eMu}=Object,XMa=(e=>t=>{let r=Qlw.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),r3t=e=>(e=e.toLowerCase(),t=>XMa(t)===e),ZMa=e=>t=>typeof t===e,{isArray:nLi}=Array,iSn=ZMa("undefined");function Glw(e){return e!==null&&!iSn(e)&&e.constructor!==null&&!iSn(e.constructor)&&sSe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var B7f=r3t("ArrayBuffer");function $lw(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&B7f(e.buffer),t}var Klw=ZMa("string"),sSe=ZMa("function"),I7f=ZMa("number"),kMa=e=>e!==null&&typeof e=="object",Ylw=e=>e===!0||e===!1,YMa=e=>{if(XMa(e)!=="object")return!1;let t=eMu(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Xlw=r3t("Date"),Zlw=r3t("File"),klw=r3t("Blob"),efw=r3t("FileList"),tfw=e=>kMa(e)&&sSe(e.pipe),rfw=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||sSe(e.append)&&((t=XMa(e))==="formdata"||t==="object"&&sSe(e.toString)&&e.toString()==="[object FormData]"))},ifw=r3t("URLSearchParams"),[nfw,afw,ofw,ufw]=["ReadableStream","Request","Response","Headers"].map(r3t),sfw=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function nSn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),nLi(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,f;for(i=0;i<u;i++)f=a[i],t.call(null,e[f],f,e)}}function z7f(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 wli=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,N7f=e=>!iSn(e)&&e!==wli;function kAu(){let{caseless:e}=N7f(this)&&this||{},t={},r=(i,n)=>{let a=e&&z7f(t,n)||n;YMa(t[a])&&YMa(i)?t[a]=kAu(t[a],i):YMa(i)?t[a]=kAu({},i):nLi(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&nSn(arguments[i],r);return t}var cfw=(e,t,r,{allOwnKeys:i}={})=>(nSn(t,(n,a)=>{r&&sSe(n)?e[a]=rSn(n,r):e[a]=n},{allOwnKeys:i}),e),lfw=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ffw=(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)},dfw=(e,t,r,i)=>{let n,a,u,f={};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))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&eMu(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},pfw=(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},_fw=e=>{if(!e)return null;if(nLi(e))return e;let t=e.length;if(!I7f(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},hfw=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&eMu(Uint8Array)),yfw=(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])}},vfw=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},bfw=r3t("HTMLFormElement"),gfw=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),C7f=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),mfw=r3t("RegExp"),F7f=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};nSn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},Ofw=e=>{F7f(e,(t,r)=>{if(sSe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(sSe(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+"'")})}})},Pfw=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return nLi(e)?i(e):i(String(e).split(t)),r},jfw=()=>{},wfw=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,ZAu="abcdefghijklmnopqrstuvwxyz",x7f="0123456789",R7f={DIGIT:x7f,ALPHA:ZAu,ALPHA_DIGIT:ZAu+ZAu.toUpperCase()+x7f},Dfw=(e=16,t=R7f.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function Sfw(e){return!!(e&&sSe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var Efw=e=>{let t=new Array(10),r=(i,n)=>{if(kMa(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=nLi(i)?[]:{};return nSn(i,(u,f)=>{let p=r(u,n+1);!iSn(p)&&(a[f]=p)}),t[n]=void 0,a}}return i};return r(e,0)},Afw=r3t("AsyncFunction"),Mfw=e=>e&&(kMa(e)||sSe(e))&&sSe(e.then)&&sSe(e.catch),L7f=((e,t)=>e?setImmediate:t?((r,i)=>(wli.addEventListener("message",({source:n,data:a})=>{n===wli&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),wli.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",sSe(wli.postMessage)),Tfw=typeof queueMicrotask<"u"?queueMicrotask.bind(wli):typeof process<"u"&&process.nextTick||L7f,jl={isArray:nLi,isArrayBuffer:B7f,isBuffer:Glw,isFormData:rfw,isArrayBufferView:$lw,isString:Klw,isNumber:I7f,isBoolean:Ylw,isObject:kMa,isPlainObject:YMa,isReadableStream:nfw,isRequest:afw,isResponse:ofw,isHeaders:ufw,isUndefined:iSn,isDate:Xlw,isFile:Zlw,isBlob:klw,isRegExp:mfw,isFunction:sSe,isStream:tfw,isURLSearchParams:ifw,isTypedArray:hfw,isFileList:efw,forEach:nSn,merge:kAu,extend:cfw,trim:sfw,stripBOM:lfw,inherits:ffw,toFlatObject:dfw,kindOf:XMa,kindOfTest:r3t,endsWith:pfw,toArray:_fw,forEachEntry:yfw,matchAll:vfw,isHTMLForm:bfw,hasOwnProperty:C7f,hasOwnProp:C7f,reduceDescriptors:F7f,freezeMethods:Ofw,toObjectSet:Pfw,toCamelCase:gfw,noop:jfw,toFiniteNumber:wfw,findKey:z7f,global:wli,isContextDefined:N7f,ALPHABET:R7f,generateString:Dfw,isSpecCompliantForm:Sfw,toJSONObject:Efw,isAsyncFn:Afw,isThenable:Mfw,setImmediate:L7f,asap:Tfw};function aLi(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)}jl.inherits(aLi,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:jl.toJSONObject(this.config),code:this.code,status:this.status}}});var U7f=aLi.prototype,V7f={};["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=>{V7f[e]={value:e}});Object.defineProperties(aLi,V7f);Object.defineProperty(U7f,"isAxiosError",{value:!0});aLi.from=(e,t,r,i,n,a)=>{let u=Object.create(U7f);return jl.toFlatObject(e,u,function(p){return p!==Error.prototype},f=>f!=="isAxiosError"),aLi.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var hy=aLi;var W7f=bo(ELr(),1),eTa=W7f.default;function tMu(e){return jl.isPlainObject(e)||jl.isArray(e)}function J7f(e){return jl.endsWith(e,"[]")?e.slice(0,-2):e}function H7f(e,t,r){return e?e.concat(t).map(function(n,a){return n=J7f(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function qfw(e){return jl.isArray(e)&&!e.some(tMu)}var Cfw=jl.toFlatObject(jl,{},null,function(t){return/^is[A-Z]/.test(t)});function xfw(e,t,r){if(!jl.isObject(e))throw new TypeError("target must be an object");t=t||new(eTa||FormData),r=jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,T){return!jl.isUndefined(T[A])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,p=(r.Blob||typeof Blob<"u"&&Blob)&&jl.isSpecCompliantForm(t);if(!jl.isFunction(n))throw new TypeError("visitor must be a function");function c(j){if(j===null)return"";if(jl.isDate(j))return j.toISOString();if(!p&&jl.isBlob(j))throw new hy("Blob is not supported. Use a Buffer instead.");return jl.isArrayBuffer(j)||jl.isTypedArray(j)?p&&typeof Blob=="function"?new Blob([j]):Buffer.from(j):j}function o(j,A,T){let B=j;if(j&&!T&&typeof j=="object"){if(jl.endsWith(A,"{}"))A=i?A:A.slice(0,-2),j=JSON.stringify(j);else if(jl.isArray(j)&&qfw(j)||(jl.isFileList(j)||jl.endsWith(A,"[]"))&&(B=jl.toArray(j)))return A=J7f(A),B.forEach(function(C,N){!(jl.isUndefined(C)||C===null)&&t.append(u===!0?H7f([A],N,a):u===null?A:A+"[]",c(C))}),!1}return tMu(j)?!0:(t.append(H7f(T,A,a),c(j)),!1)}let l=[],m=Object.assign(Cfw,{defaultVisitor:o,convertValue:c,isVisitable:tMu});function O(j,A){if(!jl.isUndefined(j)){if(l.indexOf(j)!==-1)throw Error("Circular reference detected in "+A.join("."));l.push(j),jl.forEach(j,function(B,z){(!(jl.isUndefined(B)||B===null)&&n.call(t,B,jl.isString(z)?z.trim():z,A,m))===!0&&O(B,A?A.concat(z):[z])}),l.pop()}}if(!jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var TVr=xfw;function Q7f(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function G7f(e,t){this._pairs=[],e&&TVr(e,this,t)}var $7f=G7f.prototype;$7f.append=function(t,r){this._pairs.push([t,r])};$7f.toString=function(t){let r=t?function(i){return t.call(this,i,Q7f)}:Q7f;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var K7f=G7f;function Bfw(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Dli(e,t,r){if(!t)return e;let i=r&&r.encode||Bfw,n=r&&r.serialize,a;if(n?a=n(t,r):a=jl.isURLSearchParams(t)?t.toString():new K7f(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var rMu=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){jl.forEach(this.handlers,function(i){i!==null&&t(i)})}},iMu=rMu;var oLi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Y7f=bo(require("url"),1),X7f=Y7f.default.URLSearchParams;var Z7f={isNode:!0,classes:{URLSearchParams:X7f,FormData:eTa,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var oMu={};Gs(oMu,{hasBrowserEnv:()=>aMu,hasStandardBrowserEnv:()=>Ifw,hasStandardBrowserWebWorkerEnv:()=>zfw,navigator:()=>nMu,origin:()=>Nfw});var aMu=typeof window<"u"&&typeof document<"u",nMu=typeof navigator=="object"&&navigator||void 0,Ifw=aMu&&(!nMu||["ReactNative","NativeScript","NS"].indexOf(nMu.product)<0),zfw=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Nfw=aMu&&window.location.href||"http://localhost";var kB={...oMu,...Z7f};function uMu(e,t){return TVr(e,new kB.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return kB.isNode&&jl.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function Ffw(e){return jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Rfw(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 Lfw(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),p=a>=r.length;return u=!u&&jl.isArray(n)?n.length:u,p?(jl.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!f):((!n[u]||!jl.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&jl.isArray(n[u])&&(n[u]=Rfw(n[u])),!f)}if(jl.isFormData(e)&&jl.isFunction(e.entries)){let r={};return jl.forEachEntry(e,(i,n)=>{t(Ffw(i),n,r,0)}),r}return null}var tTa=Lfw;function Ufw(e,t,r){if(jl.isString(e))try{return(t||JSON.parse)(e),jl.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var sMu={transitional:oLi,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=jl.isObject(t);if(a&&jl.isHTMLForm(t)&&(t=new FormData(t)),jl.isFormData(t))return n?JSON.stringify(tTa(t)):t;if(jl.isArrayBuffer(t)||jl.isBuffer(t)||jl.isStream(t)||jl.isFile(t)||jl.isBlob(t)||jl.isReadableStream(t))return t;if(jl.isArrayBufferView(t))return t.buffer;if(jl.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let f;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return uMu(t,this.formSerializer).toString();if((f=jl.isFileList(t))||i.indexOf("multipart/form-data")>-1){let p=this.env&&this.env.FormData;return TVr(f?{"files[]":t}:t,p&&new p,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),Ufw(t)):t}],transformResponse:[function(t){let r=this.transitional||sMu.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(jl.isResponse(t)||jl.isReadableStream(t))return t;if(t&&jl.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?hy.from(f,hy.ERR_BAD_RESPONSE,this,null,this.response):f}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:kB.classes.FormData,Blob:kB.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};jl.forEach(["delete","get","head","post","put","patch"],e=>{sMu.headers[e]={}});var uLi=sMu;var Vfw=jl.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"]),k7f=e=>{let t={},r,i,n;return e&&e.split(`
1790
1790
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&Vfw[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var e6f=Symbol("internals");function aSn(e){return e&&String(e).trim().toLowerCase()}function rTa(e){return e===!1||e==null?e:jl.isArray(e)?e.map(rTa):String(e)}function Wfw(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 Hfw=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function cMu(e,t,r,i,n){if(jl.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!jl.isString(t)){if(jl.isString(i))return t.indexOf(i)!==-1;if(jl.isRegExp(i))return i.test(t)}}function Jfw(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function Qfw(e,t){let r=jl.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 sLi=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(f,p,c){let o=aSn(p);if(!o)throw new Error("header name must be a non-empty string");let l=jl.findKey(n,o);(!l||n[l]===void 0||c===!0||c===void 0&&n[l]!==!1)&&(n[l||p]=rTa(f))}let u=(f,p)=>jl.forEach(f,(c,o)=>a(c,o,p));if(jl.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(jl.isString(t)&&(t=t.trim())&&!Hfw(t))u(k7f(t),r);else if(jl.isHeaders(t))for(let[f,p]of t.entries())a(p,f,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=aSn(t),t){let i=jl.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return Wfw(n);if(jl.isFunction(r))return r.call(this,n,i);if(jl.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=aSn(t),t){let i=jl.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||cMu(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=aSn(u),u){let f=jl.findKey(i,u);f&&(!r||cMu(i,i[f],f,r))&&(delete i[f],n=!0)}}return jl.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||cMu(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return jl.forEach(this,(n,a)=>{let u=jl.findKey(i,a);if(u){r[u]=rTa(n),delete r[a];return}let f=t?Jfw(a):String(a).trim();f!==a&&delete r[a],r[f]=rTa(n),i[f]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return jl.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&jl.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(`
1791
1791
  `)}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[e6f]=this[e6f]={accessors:{}}).accessors,n=this.prototype;function a(u){let f=aSn(u);i[f]||(Qfw(n,u),i[f]=!0)}return jl.isArray(t)?t.forEach(a):a(t),this}};sLi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);jl.reduceDescriptors(sLi.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});jl.freezeMethods(sLi);var a7=sLi;function oSn(e,t){let r=this||uLi,i=t||r,n=a7.from(i.headers),a=i.data;return jl.forEach(e,function(f){a=f.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function uSn(e){return!!(e&&e.__CANCEL__)}function t6f(e,t,r){hy.call(this,e??"canceled",hy.ERR_CANCELED,t,r),this.name="CanceledError"}jl.inherits(t6f,hy,{__CANCEL__:!0});var cSe=t6f;function _Ht(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new hy("Request failed with status code "+r.status,[hy.ERR_BAD_REQUEST,hy.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function lMu(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function fMu(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Sli(e,t){return e&&!lMu(t)?fMu(e,t):t}var v6f=bo(iAu(),1),b6f=bo(require("http"),1),g6f=bo(require("https"),1),m6f=bo(require("util"),1),O6f=bo(yAu(),1),N2r=bo(require("zlib"),1);var Eli="1.7.7";function sSn(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var Gfw=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function dMu(e,t,r){let i=r&&r.Blob||kB.classes.Blob,n=sSn(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=Gfw.exec(e);if(!a)throw new hy("Invalid URL",hy.ERR_INVALID_URL);let u=a[1],f=a[2],p=a[3],c=Buffer.from(decodeURIComponent(p),f?"base64":"utf8");if(t){if(!i)throw new hy("Blob is not supported",hy.ERR_NOT_SUPPORT);return new i([c],{type:u})}return c}throw new hy("Unsupported protocol "+n,hy.ERR_NOT_SUPPORT)}var Ali=bo(require("stream"),1);var r6f=bo(require("stream"),1);var pMu=Symbol("internals"),_Mu=class extends r6f.default.Transform{constructor(t){t=jl.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!jl.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[pMu]={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[pMu];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[pMu],a=n.maxRate,u=this.readableHighWaterMark,f=n.timeWindow,p=1e3/f,c=a/p,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,c*.01):0,l=(O,j)=>{let A=Buffer.byteLength(O);n.bytesSeen+=A,n.bytes+=A,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(O)?process.nextTick(j):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(j)}},m=(O,j)=>{let A=Buffer.byteLength(O),T=null,B=u,z,C=0;if(a){let N=Date.now();(!n.ts||(C=N-n.ts)>=f)&&(n.ts=N,z=c-n.bytes,n.bytes=z<0?-z:0,C=0),z=c-n.bytes}if(a){if(z<=0)return setTimeout(()=>{j(null,O)},f-C);z<B&&(B=z)}B&&A>B&&A-B>o&&(T=O.subarray(B),O=O.subarray(0,B)),l(O,T?()=>{process.nextTick(j,null,T)}:j)};m(t,function O(j,A){if(j)return i(j);A?m(A,O):i(null)})}},hMu=_Mu;var P6f=require("events");var n6f=require("util"),a6f=require("stream");var{asyncIterator:i6f}=Symbol,$fw=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[i6f]?yield*e[i6f]():yield e},iTa=$fw;var Kfw=jl.ALPHABET.ALPHA_DIGIT+"-_",cSn=new n6f.TextEncoder,qVr=`\r
1792
1792
  `,Yfw=cSn.encode(qVr),Xfw=2,yMu=class{constructor(t,r){let{escapeName:i}=this.constructor,n=jl.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${qVr}`;n?r=cSn.encode(String(r).replace(/\r?\n|\r\n?/g,qVr)):a+=`Content-Type: ${r.type||"application/octet-stream"}${qVr}`,this.headers=cSn.encode(a+qVr),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+Xfw,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;jl.isTypedArray(t)?yield t:yield*iTa(t),yield Yfw}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},Zfw=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+jl.generateString(n,Kfw)}=r||{};if(!jl.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=cSn.encode("--"+a+qVr),f=cSn.encode("--"+a+"--"+qVr+qVr),p=f.byteLength,c=Array.from(e.entries()).map(([l,m])=>{let O=new yMu(l,m);return p+=O.size,O});p+=u.byteLength*c.length,p=jl.toFiniteNumber(p);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(p)&&(o["Content-Length"]=p),t&&t(o),a6f.Readable.from(async function*(){for(let l of c)yield u,yield*l.encode();yield f}())},o6f=Zfw;var u6f=bo(require("stream"),1),vMu=class extends u6f.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)}},s6f=vMu;var kfw=(e,t)=>jl.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,c6f=kfw;function edw(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(p){let c=Date.now(),o=i[a];u||(u=c),r[n]=p,i[n]=c;let l=a,m=0;for(;l!==n;)m+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),c-u<t)return;let O=o&&c-o;return O?Math.round(m*1e3/O):void 0}}var l6f=edw;function tdw(e,t){let r=0,i=1e3/t,n,a,u=(c,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,c)};return[(...c)=>{let o=Date.now(),l=o-r;l>=i?u(c,o):(n=c,a||(a=setTimeout(()=>{a=null,u(n)},i-l)))},()=>n&&u(n)]}var f6f=tdw;var z2r=(e,t,r=3)=>{let i=0,n=l6f(50,250);return f6f(a=>{let u=a.loaded,f=a.lengthComputable?a.total:void 0,p=u-i,c=n(p),o=u<=f;i=u;let l={loaded:u,total:f,progress:f?u/f:void 0,bytes:p,rate:c||void 0,estimated:c&&f&&o?(f-u)/c:void 0,event:a,lengthComputable:f!=null,[t?"download":"upload"]:!0};e(l)},r)},cLi=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},lLi=e=>(...t)=>jl.asap(()=>e(...t));var d6f={flush:N2r.default.constants.Z_SYNC_FLUSH,finishFlush:N2r.default.constants.Z_SYNC_FLUSH},rdw={flush:N2r.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:N2r.default.constants.BROTLI_OPERATION_FLUSH},p6f=jl.isFunction(N2r.default.createBrotliDecompress),{http:idw,https:ndw}=O6f.default,adw=/https:?/,_6f=kB.protocols.map(e=>e+":"),h6f=(e,[t,r])=>(e.on("end",r).on("error",r),t);function odw(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function j6f(e,t,r){let i=t;if(!i&&i!==!1){let n=(0,v6f.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){j6f(a,t,a.href)}}var udw=typeof process<"u"&&jl.kindOf(process)==="process",sdw=e=>new Promise((t,r)=>{let i,n,a=(p,c)=>{n||(n=!0,i&&i(p,c))},u=p=>{a(p),t(p)},f=p=>{a(p,!0),r(p)};e(u,f,p=>i=p).catch(f)}),cdw=({address:e,family:t})=>{if(!jl.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},y6f=(e,t)=>cdw(jl.isObject(e)?e:{address:e,family:t}),w6f=udw&&function(t){return sdw(async function(i,n,a){let{data:u,lookup:f,family:p}=t,{responseType:c,responseEncoding:o}=t,l=t.method.toUpperCase(),m,O=!1,j;if(f){let sr=c6f(f,Wr=>jl.isArray(Wr)?Wr:[Wr]);f=(Wr,mi,Yt)=>{sr(Wr,mi,(Mr,Ei,br)=>{if(Mr)return Yt(Mr);let Ii=jl.isArray(Ei)?Ei.map(pi=>y6f(pi)):[y6f(Ei,br)];mi.all?Yt(Mr,Ii):Yt(Mr,Ii[0].address,Ii[0].family)})}}let A=new P6f.EventEmitter,T=()=>{t.cancelToken&&t.cancelToken.unsubscribe(B),t.signal&&t.signal.removeEventListener("abort",B),A.removeAllListeners()};a((sr,Wr)=>{m=!0,Wr&&(O=!0,T())});function B(sr){A.emit("abort",!sr||sr.type?new cSe(null,t,j):sr)}A.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(B),t.signal&&(t.signal.aborted?B():t.signal.addEventListener("abort",B)));let z=Sli(t.baseURL,t.url),C=new URL(z,kB.hasBrowserEnv?kB.origin:void 0),N=C.protocol||_6f[0];if(N==="data:"){let sr;if(l!=="GET")return _Ht(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{sr=dMu(t.url,c==="blob",{Blob:t.env&&t.env.Blob})}catch(Wr){throw hy.from(Wr,hy.ERR_BAD_REQUEST,t)}return c==="text"?(sr=sr.toString(o),(!o||o==="utf8")&&(sr=jl.stripBOM(sr))):c==="stream"&&(sr=Ali.default.Readable.from(sr)),_Ht(i,n,{data:sr,status:200,statusText:"OK",headers:new a7,config:t})}if(_6f.indexOf(N)===-1)return n(new hy("Unsupported protocol "+N,hy.ERR_BAD_REQUEST,t));let U=a7.from(t.headers).normalize();U.set("User-Agent","axios/"+Eli,!1);let{onUploadProgress:k,onDownloadProgress:ve}=t,Y=t.maxRate,X,Ae;if(jl.isSpecCompliantForm(u)){let sr=U.getContentType(/boundary=([-_\w\d]{10,70})/i);u=o6f(u,Wr=>{U.set(Wr)},{tag:`axios-${Eli}-boundary`,boundary:sr&&sr[1]||void 0})}else if(jl.isFormData(u)&&jl.isFunction(u.getHeaders)){if(U.set(u.getHeaders()),!U.hasContentLength())try{let sr=await m6f.default.promisify(u.getLength).call(u);Number.isFinite(sr)&&sr>=0&&U.setContentLength(sr)}catch{}}else if(jl.isBlob(u))u.size&&U.setContentType(u.type||"application/octet-stream"),U.setContentLength(u.size||0),u=Ali.default.Readable.from(iTa(u));else if(u&&!jl.isStream(u)){if(!Buffer.isBuffer(u))if(jl.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(jl.isString(u))u=Buffer.from(u,"utf-8");else return n(new hy("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",hy.ERR_BAD_REQUEST,t));if(U.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new hy("Request body larger than maxBodyLength limit",hy.ERR_BAD_REQUEST,t))}let pt=jl.toFiniteNumber(U.getContentLength());jl.isArray(Y)?(X=Y[0],Ae=Y[1]):X=Ae=Y,u&&(k||X)&&(jl.isStream(u)||(u=Ali.default.Readable.from(u,{objectMode:!1})),u=Ali.default.pipeline([u,new hMu({maxRate:jl.toFiniteNumber(X)})],jl.noop),k&&u.on("progress",h6f(u,cLi(pt,z2r(lLi(k),!1,3)))));let ct;if(t.auth){let sr=t.auth.username||"",Wr=t.auth.password||"";ct=sr+":"+Wr}if(!ct&&C.username){let sr=C.username,Wr=C.password;ct=sr+":"+Wr}ct&&U.delete("authorization");let Dt;try{Dt=Dli(C.pathname+C.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(sr){let Wr=new Error(sr.message);return Wr.config=t,Wr.url=t.url,Wr.exists=!0,n(Wr)}U.set("Accept-Encoding","gzip, compress, deflate"+(p6f?", br":""),!1);let Rt={path:Dt,method:l,headers:U.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:ct,protocol:N,family:p,beforeRedirect:odw,beforeRedirects:{}};!jl.isUndefined(f)&&(Rt.lookup=f),t.socketPath?Rt.socketPath=t.socketPath:(Rt.hostname=C.hostname.startsWith("[")?C.hostname.slice(1,-1):C.hostname,Rt.port=C.port,j6f(Rt,t.proxy,N+"//"+C.hostname+(C.port?":"+C.port:"")+Rt.path));let Zt,Vt=adw.test(Rt.protocol);if(Rt.agent=Vt?t.httpsAgent:t.httpAgent,t.transport?Zt=t.transport:t.maxRedirects===0?Zt=Vt?g6f.default:b6f.default:(t.maxRedirects&&(Rt.maxRedirects=t.maxRedirects),t.beforeRedirect&&(Rt.beforeRedirects.config=t.beforeRedirect),Zt=Vt?ndw:idw),t.maxBodyLength>-1?Rt.maxBodyLength=t.maxBodyLength:Rt.maxBodyLength=1/0,t.insecureHTTPParser&&(Rt.insecureHTTPParser=t.insecureHTTPParser),j=Zt.request(Rt,function(Wr){if(j.destroyed)return;let mi=[Wr],Yt=+Wr.headers["content-length"];if(ve||Ae){let pi=new hMu({maxRate:jl.toFiniteNumber(Ae)});ve&&pi.on("progress",h6f(pi,cLi(Yt,z2r(lLi(ve),!0,3)))),mi.push(pi)}let Mr=Wr,Ei=Wr.req||j;if(t.decompress!==!1&&Wr.headers["content-encoding"])switch((l==="HEAD"||Wr.statusCode===204)&&delete Wr.headers["content-encoding"],(Wr.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":mi.push(N2r.default.createUnzip(d6f)),delete Wr.headers["content-encoding"];break;case"deflate":mi.push(new s6f),mi.push(N2r.default.createUnzip(d6f)),delete Wr.headers["content-encoding"];break;case"br":p6f&&(mi.push(N2r.default.createBrotliDecompress(rdw)),delete Wr.headers["content-encoding"])}Mr=mi.length>1?Ali.default.pipeline(mi,jl.noop):mi[0];let br=Ali.default.finished(Mr,()=>{br(),T()}),Ii={status:Wr.statusCode,statusText:Wr.statusMessage,headers:new a7(Wr.headers),config:t,request:Ei};if(c==="stream")Ii.data=Mr,_Ht(i,n,Ii);else{let pi=[],Ft=0;Mr.on("data",function(ei){pi.push(ei),Ft+=ei.length,t.maxContentLength>-1&&Ft>t.maxContentLength&&(O=!0,Mr.destroy(),n(new hy("maxContentLength size of "+t.maxContentLength+" exceeded",hy.ERR_BAD_RESPONSE,t,Ei)))}),Mr.on("aborted",function(){if(O)return;let ei=new hy("maxContentLength size of "+t.maxContentLength+" exceeded",hy.ERR_BAD_RESPONSE,t,Ei);Mr.destroy(ei),n(ei)}),Mr.on("error",function(ei){j.destroyed||n(hy.from(ei,null,t,Ei))}),Mr.on("end",function(){try{let ei=pi.length===1?pi[0]:Buffer.concat(pi);c!=="arraybuffer"&&(ei=ei.toString(o),(!o||o==="utf8")&&(ei=jl.stripBOM(ei))),Ii.data=ei}catch(ei){return n(hy.from(ei,null,t,Ii.request,Ii))}_Ht(i,n,Ii)})}A.once("abort",pi=>{Mr.destroyed||(Mr.emit("error",pi),Mr.destroy())})}),A.once("abort",sr=>{n(sr),j.destroy(sr)}),j.on("error",function(Wr){n(hy.from(Wr,null,t,j))}),j.on("socket",function(Wr){Wr.setKeepAlive(!0,1e3*60)}),t.timeout){let sr=parseInt(t.timeout,10);if(Number.isNaN(sr)){n(new hy("error trying to parse `config.timeout` to int",hy.ERR_BAD_OPTION_VALUE,t,j));return}j.setTimeout(sr,function(){if(m)return;let mi=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Yt=t.transitional||oLi;t.timeoutErrorMessage&&(mi=t.timeoutErrorMessage),n(new hy(mi,Yt.clarifyTimeoutError?hy.ETIMEDOUT:hy.ECONNABORTED,t,j)),B()})}if(jl.isStream(u)){let sr=!1,Wr=!1;u.on("end",()=>{sr=!0}),u.once("error",mi=>{Wr=!0,j.destroy(mi)}),u.on("close",()=>{!sr&&!Wr&&B(new cSe("Request stream has been aborted",t,j))}),u.pipe(j)}else j.end(u)})};var D6f=kB.hasStandardBrowserEnv?function(){let t=kB.navigator&&/(msie|trident)/i.test(kB.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 f=jl.isString(u)?n(u):u;return f.protocol===i.protocol&&f.host===i.host}}():function(){return function(){return!0}}();var S6f=kB.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];jl.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),jl.isString(i)&&u.push("path="+i),jl.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 E6f=e=>e instanceof a7?{...e}:e;function i3t(e,t){t=t||{};let r={};function i(c,o,l){return jl.isPlainObject(c)&&jl.isPlainObject(o)?jl.merge.call({caseless:l},c,o):jl.isPlainObject(o)?jl.merge({},o):jl.isArray(o)?o.slice():o}function n(c,o,l){if(jl.isUndefined(o)){if(!jl.isUndefined(c))return i(void 0,c,l)}else return i(c,o,l)}function a(c,o){if(!jl.isUndefined(o))return i(void 0,o)}function u(c,o){if(jl.isUndefined(o)){if(!jl.isUndefined(c))return i(void 0,c)}else return i(void 0,o)}function f(c,o,l){if(l in t)return i(c,o);if(l in e)return i(void 0,c)}let p={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:f,headers:(c,o)=>n(E6f(c),E6f(o),!0)};return jl.forEach(Object.keys(Object.assign({},e,t)),function(o){let l=p[o]||n,m=l(e[o],t[o],o);jl.isUndefined(m)&&l!==f||(r[o]=m)}),r}var nTa=e=>{let t=i3t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:f}=t;t.headers=u=a7.from(u),t.url=Dli(Sli(t.baseURL,t.url),e.params,e.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):"")));let p;if(jl.isFormData(r)){if(kB.hasStandardBrowserEnv||kB.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((p=u.getContentType())!==!1){let[c,...o]=p?p.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([c||"multipart/form-data",...o].join("; "))}}if(kB.hasStandardBrowserEnv&&(i&&jl.isFunction(i)&&(i=i(t)),i||i!==!1&&D6f(t.url))){let c=n&&a&&S6f.read(a);c&&u.set(n,c)}return t};var ldw=typeof XMLHttpRequest<"u",A6f=ldw&&function(e){return new Promise(function(r,i){let n=nTa(e),a=n.data,u=a7.from(n.headers).normalize(),{responseType:f,onUploadProgress:p,onDownloadProgress:c}=n,o,l,m,O,j;function A(){O&&O(),j&&j(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let T=new XMLHttpRequest;T.open(n.method.toUpperCase(),n.url,!0),T.timeout=n.timeout;function B(){if(!T)return;let C=a7.from("getAllResponseHeaders"in T&&T.getAllResponseHeaders()),U={data:!f||f==="text"||f==="json"?T.responseText:T.response,status:T.status,statusText:T.statusText,headers:C,config:e,request:T};_Ht(function(ve){r(ve),A()},function(ve){i(ve),A()},U),T=null}"onloadend"in T?T.onloadend=B:T.onreadystatechange=function(){!T||T.readyState!==4||T.status===0&&!(T.responseURL&&T.responseURL.indexOf("file:")===0)||setTimeout(B)},T.onabort=function(){T&&(i(new hy("Request aborted",hy.ECONNABORTED,e,T)),T=null)},T.onerror=function(){i(new hy("Network Error",hy.ERR_NETWORK,e,T)),T=null},T.ontimeout=function(){let N=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",U=n.transitional||oLi;n.timeoutErrorMessage&&(N=n.timeoutErrorMessage),i(new hy(N,U.clarifyTimeoutError?hy.ETIMEDOUT:hy.ECONNABORTED,e,T)),T=null},a===void 0&&u.setContentType(null),"setRequestHeader"in T&&jl.forEach(u.toJSON(),function(N,U){T.setRequestHeader(U,N)}),jl.isUndefined(n.withCredentials)||(T.withCredentials=!!n.withCredentials),f&&f!=="json"&&(T.responseType=n.responseType),c&&([m,j]=z2r(c,!0),T.addEventListener("progress",m)),p&&T.upload&&([l,O]=z2r(p),T.upload.addEventListener("progress",l),T.upload.addEventListener("loadend",O)),(n.cancelToken||n.signal)&&(o=C=>{T&&(i(!C||C.type?new cSe(null,e,T):C),T.abort(),T=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let z=sSn(n.url);if(z&&kB.protocols.indexOf(z)===-1){i(new hy("Unsupported protocol "+z+":",hy.ERR_BAD_REQUEST,e));return}T.send(a||null)})};var fdw=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(c){if(!n){n=!0,f();let o=c instanceof Error?c:this.reason;i.abort(o instanceof hy?o:new cSe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new hy(`timeout ${t} of ms exceeded`,hy.ETIMEDOUT))},t),f=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(a):c.removeEventListener("abort",a)}),e=null)};e.forEach(c=>c.addEventListener("abort",a));let{signal:p}=i;return p.unsubscribe=()=>jl.asap(f),p}},M6f=fdw;var ddw=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},pdw=async function*(e,t){for await(let r of _dw(e))yield*ddw(r,t)},_dw=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()}},bMu=(e,t,r,i)=>{let n=pdw(e,t),a=0,u,f=p=>{u||(u=!0,i&&i(p))};return new ReadableStream({async pull(p){try{let{done:c,value:o}=await n.next();if(c){f(),p.close();return}let l=o.byteLength;if(r){let m=a+=l;r(m)}p.enqueue(new Uint8Array(o))}catch(c){throw f(c),c}},cancel(p){return f(p),n.return()}},{highWaterMark:2})};var oTa=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",q6f=oTa&&typeof ReadableStream=="function",hdw=oTa&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),C6f=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ydw=q6f&&C6f(()=>{let e=!1,t=new Request(kB.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),T6f=64*1024,gMu=q6f&&C6f(()=>jl.isReadableStream(new Response("").body)),aTa={stream:gMu&&(e=>e.body)};oTa&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!aTa[t]&&(aTa[t]=jl.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new hy(`Response type '${t}' is not supported`,hy.ERR_NOT_SUPPORT,i)})})})(new Response);var vdw=async e=>{if(e==null)return 0;if(jl.isBlob(e))return e.size;if(jl.isSpecCompliantForm(e))return(await new Request(kB.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(jl.isArrayBufferView(e)||jl.isArrayBuffer(e))return e.byteLength;if(jl.isURLSearchParams(e)&&(e=e+""),jl.isString(e))return(await hdw(e)).byteLength},bdw=async(e,t)=>{let r=jl.toFiniteNumber(e.getContentLength());return r??vdw(t)},x6f=oTa&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:f,onUploadProgress:p,responseType:c,headers:o,withCredentials:l="same-origin",fetchOptions:m}=nTa(e);c=c?(c+"").toLowerCase():"text";let O=M6f([n,a&&a.toAbortSignal()],u),j,A=O&&O.unsubscribe&&(()=>{O.unsubscribe()}),T;try{if(p&&ydw&&r!=="get"&&r!=="head"&&(T=await bdw(o,i))!==0){let U=new Request(t,{method:"POST",body:i,duplex:"half"}),k;if(jl.isFormData(i)&&(k=U.headers.get("content-type"))&&o.setContentType(k),U.body){let[ve,Y]=cLi(T,z2r(lLi(p)));i=bMu(U.body,T6f,ve,Y)}}jl.isString(l)||(l=l?"include":"omit");let B="credentials"in Request.prototype;j=new Request(t,{...m,signal:O,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:B?l:void 0});let z=await fetch(j),C=gMu&&(c==="stream"||c==="response");if(gMu&&(f||C&&A)){let U={};["status","statusText","headers"].forEach(X=>{U[X]=z[X]});let k=jl.toFiniteNumber(z.headers.get("content-length")),[ve,Y]=f&&cLi(k,z2r(lLi(f),!0))||[];z=new Response(bMu(z.body,T6f,ve,()=>{Y&&Y(),A&&A()}),U)}c=c||"text";let N=await aTa[jl.findKey(aTa,c)||"text"](z,e);return!C&&A&&A(),await new Promise((U,k)=>{_Ht(U,k,{data:N,headers:a7.from(z.headers),status:z.status,statusText:z.statusText,config:e,request:j})})}catch(B){throw A&&A(),B&&B.name==="TypeError"&&/fetch/i.test(B.message)?Object.assign(new hy("Network Error",hy.ERR_NETWORK,e,j),{cause:B.cause||B}):hy.from(B,B&&B.code,e,j)}});var mMu={http:w6f,xhr:A6f,fetch:x6f};jl.forEach(mMu,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var B6f=e=>`- ${e}`,gdw=e=>jl.isFunction(e)||e===null||e===!1,uTa={getAdapter:e=>{e=jl.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,!gdw(r)&&(i=mMu[(u=String(r)).toLowerCase()],i===void 0))throw new hy(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([f,p])=>`adapter ${f} `+(p===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1933,7 +1933,7 @@ ${n.style.help("(Use arrow keys)")}`);let U=ifi({items:o,active:T,renderItem({it
1933
1933
  ${n.style.description(z.description)}`:"";return[[j,C,ve].filter(Boolean).join(" "),`${k??U}${N}${Y}`]});var sxu=bo(GVr(),1);var qLf=bo(z9i(),1),Mjw={icon:{cursor:SBe.pointer},style:{disabled:e=>sxu.default.dim(`- ${e}`),description:e=>sxu.default.cyan(e)},helpMode:"auto"};function ZLi(e){return!NT.isSeparator(e)&&!e.disabled}function Tjw(e){return e.map(t=>{if(NT.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value);return{value:t.value,name:r,description:t.description,short:t.short??r,disabled:t.disabled??!1}})}var qjw=g4((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=ABe(!0),a=u7(Mjw,e.theme),[u,f]=Im("idle"),p=v4({status:u,theme:a}),c=ABe(),o=bSe(()=>Tjw(e.choices),[e.choices]),l=bSe(()=>{let U=o.findIndex(ZLi),k=o.findLastIndex(ZLi);if(U===-1)throw new QVr("[select prompt] No selectable choices. All choices are disabled.");return{first:U,last:k}},[o]),m=bSe(()=>"default"in e?o.findIndex(U=>ZLi(U)&&U.value===e.default):-1,[e.default,o]),[O,j]=Im(m===-1?l.first:m),A=o[O];b4((U,k)=>{if(clearTimeout(c.current),hR(U))f("done"),t(A.value);else if(JVr(U)||KLi(U)){if(k.clearLine(0),r||JVr(U)&&O!==l.first||KLi(U)&&O!==l.last){let ve=JVr(U)?-1:1,Y=O;do Y=(Y+ve+o.length)%o.length;while(!ZLi(o[Y]));j(Y)}}else if(xqa(U)){k.clearLine(0);let ve=Number(U.name)-1,Y=o[ve];Y!=null&&ZLi(Y)&&j(ve)}else if(YLi(U))k.clearLine(0);else{let ve=k.line.toLowerCase(),Y=o.findIndex(X=>NT.isSeparator(X)||!ZLi(X)?!1:X.name.toLowerCase().startsWith(ve));Y!==-1&&j(Y),c.current=setTimeout(()=>{k.clearLine(0)},700)}}),d3t(()=>()=>{clearTimeout(c.current)},[]);let T=a.style.message(e.message,u),B="",z="";(a.helpMode==="always"||a.helpMode==="auto"&&n.current)&&(n.current=!1,o.length>i?z=`
1934
1934
  ${a.style.help("(Use arrow keys to reveal more choices)")}`:B=a.style.help("(Use arrow keys)"));let C=ifi({items:o,active:O,renderItem({item:U,isActive:k}){if(NT.isSeparator(U))return` ${U.separator}`;if(U.disabled){let X=typeof U.disabled=="string"?U.disabled:"(disabled)";return a.style.disabled(`${U.name} ${X}`)}let ve=k?a.style.highlight:X=>X,Y=k?a.icon.cursor:" ";return ve(`${Y} ${U.name}`)},pageSize:i,loop:r});if(u==="done")return`${p} ${T} ${a.style.answer(A.short)}`;let N=A.description?`
1935
1935
  ${a.style.description(A.description)}`:"";return`${[p,T,B].filter(Boolean).join(" ")}
1936
- ${C}${z}${N}${qLf.default.cursorHide}`});var CLf=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Jqa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=DA.Info;constructor(t){this.ttyAwareLogger=new yqa(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.46.8"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ic.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new cCe}failWithoutThrowing(t,r){this.didSucceed=!1,dqa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await iLi()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await O5f({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1936
+ ${C}${z}${N}${qLf.default.cursorHide}`});var CLf=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Jqa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=DA.Info;constructor(t){this.ttyAwareLogger=new yqa(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.46.10"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ic.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new cCe}failWithoutThrowing(t,r){this.didSucceed=!1,dqa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await iLi()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await O5f({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1937
1937
  `)||(r+=`
1938
1938
  `),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=Suu(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 USn(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 cCe}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await iLi()).sendEvent(t)}logger=_Pn(this.log.bind(this));constructTaskInitForWorkspace(t){let r=xLf(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?xLf(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=CLf[this.numTasks++%CLf.length],u=Ic.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===nN.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=>n9r.indexOf(i.level)>=n9r.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===DA.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 $Li({cliEnvironment:this.environment,includePreReleases:t}),i=Zne(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await vqa({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await nxu({message:t,default:r})}};function xLf(e){return`[${e}]:`}function MBe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ic.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ic.dim(r)),i.join(`
1939
1939
  `)}var BLf=require("fs/promises");async function cxu({absoluteFilePathToOverrides:e,data:t,context:r}){let i=null;try{let n=(await(0,BLf.readFile)(e,"utf8")).toString();try{i=JSON.parse(n)}catch{i=Qy.load(n,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return Cuu({data:t,overrides:i})}var kne={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,cooerceEnumsToLiterals:!0,respectReadonlySchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,filter:void 0,asyncApiNaming:"v1"};function lxu({options:e,overrides:t}){return{disableExamples:t?.disableExamples??kne.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??kne.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??kne.useTitlesAsName,audiences:t?.audiences??e?.audiences??kne.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??kne.optionalAdditionalProperties,cooerceEnumsToLiterals:t?.cooerceEnumsToLiterals??e?.cooerceEnumsToLiterals??kne.cooerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??kne.respectReadonlySchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??kne.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??kne.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??kne.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??kne.shouldUseUndiscriminatedUnionsWithLiterals,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??kne.objectQueryParameters,filter:t?.filter??e?.filter??kne.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??kne.asyncApiNaming}}var _3t={openapi:e=>({...e,type:"openapi",_visit:function(t){return _3t._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return _3t._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 kLi={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return kLi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var tU={basic:e=>({...e,type:"basic",_visit:function(t){return tU._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return tU._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return tU._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return tU._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return tU._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 NP={primitive:e=>({value:e,type:"primitive",_visit:function(t){return NP._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return NP._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return NP._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return NP._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return NP._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return NP._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return NP._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return NP._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 Yy={int:e=>({value:e,type:"int",_visit:function(t){return Yy._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return Yy._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return Yy._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return Yy._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return Yy._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return Yy._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Yy._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return Yy._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return Yy._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return Yy._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return Yy._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 eUi={boolean:e=>({value:e,type:"boolean",_visit:function(t){return eUi._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return eUi._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 YVr={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return YVr._visit(this,t)}}),undisciminated:e=>({value:e,type:"undisciminated",_visit:function(t){return YVr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undisciminated":return t.undisciminated(e.value);default:return t._other(e)}}};var SH={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case SH.GenerallyAvailable:return t.generallyAvailable();case SH.Beta:return t.beta();case SH.Deprecated:return t.deprecated();default:return t._other()}}};var W2r={cursor:e=>({...e,type:"cursor",_visit:function(t){return W2r._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return W2r._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 H2r={language:e=>({...e,type:"language",_visit:function(t){return H2r._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return H2r._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 EH={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 EH.Curl:return t.curl();case EH.Python:return t.python();case EH.Javascript:return t.javascript();case EH.Typescript:return t.typescript();case EH.Go:return t.go();case EH.Ruby:return t.ruby();case EH.Csharp:return t.csharp();case EH.Java:return t.java();case EH.Js:return t.js();case EH.Node:return t.node();case EH.Ts:return t.ts();case EH.Nodets:return t.nodets();case EH.Golang:return t.golang();case EH.Dotnet:return t.dotnet();case EH.Jvm:return t.jvm();default:return t._other()}}};var h3t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return h3t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return h3t._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 y3t={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return y3t._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return y3t._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 v$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case v$.Get:return t.get();case v$.Post:return t.post();case v$.Put:return t.put();case v$.Patch:return t.patch();case v$.Delete:return t.delete();case v$.Head:return t.head();case v$.Options:return t.options();case v$.Trace:return t.trace();default:return t._other()}}};var XVr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return XVr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return XVr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return XVr._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 TBe={file:e=>({...e,type:"file",_visit:function(t){return TBe._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return TBe._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 eae={file:e=>({...e,type:"file",_visit:function(t){return eae._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return eae._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return eae._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return eae._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return eae._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return eae._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 rb={primitive:e=>({...e,type:"primitive",_visit:function(t){return rb._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return rb._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return rb._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return rb._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return rb._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return rb._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return rb._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return rb._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return rb._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return rb._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return rb._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 eD={int:e=>({...e,type:"int",_visit:function(t){return eD._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return eD._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return eD._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return eD._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return eD._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return eD._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return eD._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return eD._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return eD._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return eD._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return eD._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 nz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return nz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return nz._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 J2r={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return J2r._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return J2r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(e);default:return t._other(e)}}};var gSe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return gSe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return gSe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gSe._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 az={file:e=>({...e,type:"file",_visit:function(t){return az._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return az._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return az._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return az._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return az._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return az._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 Dp={primitive:e=>({...e,type:"primitive",_visit:function(t){return Dp._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Dp._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Dp._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Dp._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Dp._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Dp._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Dp._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Dp._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Dp._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Dp._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Dp._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 $Z={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return $Z._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return $Z._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(e);default:return t._other(e)}}};var oy={int:e=>({...e,type:"int",_visit:function(t){return oy._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return oy._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return oy._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return oy._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return oy._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return oy._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return oy._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return oy._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return oy._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return oy._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return oy._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 Ub={};Gs(Ub,{AllOfPropertyConflict:()=>jUi,ArraySchema:()=>ixa,ArraySchemaWithExample:()=>qxa,Availability:()=>tCa,Base64WithExample:()=>Sxa,BasicSecurityScheme:()=>nCa,BearerSecurityScheme:()=>aCa,BooleanSchema:()=>XCa,BooleanWithExample:()=>Exa,CasingOverrides:()=>sCa,CommonProperty:()=>fxa,CommonPropertyWithExample:()=>Lxa,CursorPagination:()=>FCa,CustomCodeSample:()=>zCa,CustomCodeSampleLanguage:()=>xCa,CustomCodeSampleSdk:()=>ICa,DateWithExample:()=>Dxa,DatetimeWithExample:()=>wxa,DiscriminatedOneOfSchema:()=>cxa,DiscriminatedOneOfSchemaWithExample:()=>Fxa,DoubleSchema:()=>KCa,DoubleWithExample:()=>Pxa,Encoding:()=>eCa,Endpoint:()=>LCa,EndpointExample:()=>bUi,EndpointResponseExample:()=>CCa,EndpointSdkName:()=>PHt,EndpointWithExample:()=>cUf,EnumSchema:()=>aUi,EnumSchemaWithExample:()=>Mxa,EnumValue:()=>eWr,ErrorExample:()=>ECa,FernExample:()=>MCa,FileResponse:()=>pUi,FileSchema:()=>OCa,FloatWithExample:()=>Oxa,FullEndpointExample:()=>NCa,FullExample:()=>OC,FullObjectExample:()=>yCa,FullOneOfExample:()=>bCa,GlobalHeader:()=>kCa,Header:()=>iWr,HeaderExample:()=>vUi,HeaderSecurityScheme:()=>oCa,HeaderWithExample:()=>oWr,HttpEndpointServer:()=>hUi,HttpError:()=>ACa,HttpErrorWithExample:()=>yxa,HttpMethod:()=>sUi,IdempotencyHeader:()=>exa,Int64WithExample:()=>bxa,IntSchema:()=>GCa,IntWithExample:()=>vxa,JsonRequest:()=>wCa,JsonRequestWithExample:()=>pxa,JsonResponse:()=>_Ui,JsonResponseWithExample:()=>SUi,KeyValuePair:()=>vCa,LiteralExample:()=>hCa,LiteralSchema:()=>PUi,LiteralSchemaValue:()=>txa,LongSchema:()=>$Ca,MapSchema:()=>nxa,MapSchemaWithExample:()=>Cxa,MultipartRequest:()=>dUi,MultipartRequestProperty:()=>jCa,MultipartSchema:()=>PCa,NamedFullExample:()=>wHt,Namespace:()=>cCa,NamespaceId:()=>_Ca,NullableSchema:()=>oxa,NullableSchemaWithExample:()=>Bxa,OauthSecurityScheme:()=>fCa,ObjectProperty:()=>sxa,ObjectPropertyConflictInfo:()=>wUi,ObjectPropertyWithExample:()=>Nxa,ObjectSchema:()=>rxa,ObjectSchemaWithExample:()=>Ixa,OctetStreamRequest:()=>fUi,OffsetPagination:()=>RCa,OneOfSchema:()=>uxa,OneOfSchemaWithExample:()=>zxa,OpenApiIntermediateRepresentation:()=>uUf,OpenApiSource:()=>Yqa,OptionalSchema:()=>axa,OptionalSchemaWithExample:()=>xxa,Pagination:()=>gUi,PathParameter:()=>cUi,PathParameterExample:()=>TCa,PathParameterWithExample:()=>dxa,PrimitiveExample:()=>uUi,PrimitiveSchema:()=>aWr,PrimitiveSchemaValue:()=>ZCa,PrimitiveSchemaValueWithExample:()=>Axa,PrimitiveSchemaWithExample:()=>EUi,PropertyKey:()=>oUi,ProtobufEncoding:()=>kqa,ProtobufSource:()=>Xqa,QueryParameter:()=>lUi,QueryParameterExample:()=>yUi,QueryParameterWithExample:()=>DUi,QuerySecurityScheme:()=>uCa,ReferencedSchema:()=>jHt,Request:()=>DCa,RequestWithExample:()=>_xa,Response:()=>SCa,ResponseWithExample:()=>hxa,Schema:()=>Ej,SchemaId:()=>KZ,SchemaWithExample:()=>_q,Schemas:()=>QCa,SdkGroup:()=>lCa,SdkGroupInfo:()=>gCa,SdkGroupName:()=>tWr,SecurityScheme:()=>dCa,SecuritySchemeId:()=>iCa,Server:()=>pCa,Source:()=>Zqa,StatusCode:()=>rWr,StreamingResponseExample:()=>qCa,StringSchema:()=>YCa,StringSchemaWithExample:()=>jxa,SupportedSdkLanguage:()=>BCa,Tag:()=>rCa,TagId:()=>YZ,Tags:()=>mCa,TextResponse:()=>nWr,Uint64WithExample:()=>mxa,UintWithExample:()=>gxa,UnDiscriminatedOneOfSchema:()=>lxa,UnDiscriminatedOneOfSchemaWithExample:()=>Rxa,UnknownSchemaWithExample:()=>Txa,Webhook:()=>UCa,WebhookExampleCall:()=>OUi,WebhookHttpMethod:()=>mUi,WebhookWithExample:()=>lUf,WebsocketChannel:()=>JCa,WebsocketHandshake:()=>VCa,WebsocketHandshakeWithExample:()=>sUf,WebsocketMessageExample:()=>WCa,WebsocketSessionExample:()=>HCa,WithAvailability:()=>e0,WithDescription:()=>t_,WithEncoding:()=>tae,WithInline:()=>rT,WithName:()=>Hm,WithNamespace:()=>OHt,WithSdkGroupName:()=>Sj,WithSource:()=>$0,WithTitle:()=>Dj,commons:()=>hxu,example:()=>yxu,finalIr:()=>vxu,parseIr:()=>bxu});var hxu={};Gs(hxu,{BasicSecurityScheme:()=>nCa,BearerSecurityScheme:()=>aCa,Encoding:()=>eCa,HeaderSecurityScheme:()=>oCa,Namespace:()=>cCa,NamespaceId:()=>_Ca,OauthSecurityScheme:()=>fCa,OpenApiSource:()=>Yqa,ProtobufEncoding:()=>kqa,ProtobufSource:()=>Xqa,QuerySecurityScheme:()=>uCa,SchemaId:()=>KZ,SdkGroup:()=>lCa,SdkGroupName:()=>tWr,SecurityScheme:()=>dCa,SecuritySchemeId:()=>iCa,Server:()=>pCa,Source:()=>Zqa,StatusCode:()=>rWr,Tag:()=>rCa,TagId:()=>YZ,WithAvailability:()=>e0,WithDescription:()=>t_,WithEncoding:()=>tae,WithInline:()=>rT,WithName:()=>Hm,WithNamespace:()=>OHt,WithSdkGroupName:()=>Sj,WithSource:()=>$0,WithTitle:()=>Dj});var gi={};Gs(gi,{JsonError:()=>tUi,ParseError:()=>rUi,any:()=>$Lf,boolean:()=>KLf,booleanLiteral:()=>GLf,date:()=>zLf,discriminant:()=>nUf,enum_:()=>Gqa,getObjectLikeUtils:()=>mHt,getObjectUtils:()=>nUi,getSchemaUtils:()=>e2,isProperty:()=>kVr,lazy:()=>NLf,lazyObject:()=>HLf,list:()=>Kqa,number:()=>YLf,object:()=>$qa,objectWithoutOptionalProperties:()=>WLf,optional:()=>fxu,property:()=>RLf,record:()=>eUf,set:()=>tUf,string:()=>XLf,stringLiteral:()=>QLf,transform:()=>dxu,undiscriminatedUnion:()=>iUf,union:()=>oUf,unknown:()=>ZLf,withParsedProperties:()=>_xu});var $S={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 Ax(e,t){return`Expected ${t}. Received ${Cjw(e)}.`}function Cjw(e){if(Array.isArray(e))return"list";if(e===null)return"null";switch(typeof e){case"string":return`"${e}"`;case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function b$(e){return{...e,json:ILf(e.json),parse:ILf(e.parse)}}function ILf(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(`
@@ -1973,7 +1973,7 @@ ${m}
1973
1973
  `)}];if(t["base-properties"]!=null){let C=Object.fromEntries(Object.entries(l).filter(([U])=>t["base-properties"]?.[U]!=null)),N=ipi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:C,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:f,depth:p+1});if(N.length>0)return N}let O=typeof m=="string"?m:m.type;if(typeof O!="string")return H0d(l);let j=i.resolveType({type:O,file:a});if(j==null)return[];if(j._type==="named"&&YE(j.declaration)){let C=Object.fromEntries(Object.entries(l).filter(([N])=>t["base-properties"]?.[N]==null));return ipi({typeName:e,typeNameForBreadcrumb:e,rawObject:j.declaration,file:j.file,example:C,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:f,depth:p+1})}let A=typeof m!="string"&&typeof m.key=="string"?m.key:void 0;if(A==null)return[];let{[A]:T,...B}=l,z=[];return T==null?z.push({message:`Missing property "${A}"`}):z.push(...RH({rawTypeReference:O,example:T,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:f,depth:p+1})),z.push(...H0d(B)),z}function H0d(e){return Object.keys(e).map(t=>({severity:"error",message:`Unexpected property "${t}"`}))}function u4a({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:f,depth:p}){return f4(t,{alias:c=>N0d({rawAlias:c,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:f,depth:p}),enum:c=>F0d({rawEnum:c,example:a,breadcrumbs:f}),object:c=>ipi({typeName:e,typeNameForBreadcrumb:e,rawObject:c,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:f,depth:p}),discriminatedUnion:c=>J0d({typeName:e,rawUnion:c,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:f,depth:p}),undiscriminatedUnion:c=>R0d({rawUnion:c,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:f,depth:p})})}var ebd=/^([+-]?\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)?)?)?)?$/,Bc1=/^[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}$/,Ic1=/^\d{4}-\d{2}-\d{2}$/,zc1=128;function RH({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:f}){if(f>zc1)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(GVt)){let p=r.resolveType({type:e,file:n});if(p==null)return[];let c=i.parseExampleReference(t);if(c==null)return[];let o=r.resolveNamedType({referenceToNamedType:c.rawTypeReference,file:n});return o==null?[]:tqn({expected:p,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return _ci({type:e,_default:void 0,validation:void 0,visitor:{primitive:p=>Nc1({primitiveType:p,example:t}),named:p=>{let c=r.getDeclarationOfNamedType({referenceToNamedType:p,file:n});return c==null?[]:u4a({typeName:c.typeName,typeDeclaration:c.declaration,file:c.file,example:t,typeResolver:r,exampleResolver:i,workspace:a,breadcrumbs:u,depth:f+1})},map:({keyType:p,valueType:c})=>UD(t)?Object.entries(t).flatMap(([o,l])=>[...RH({rawTypeReference:p,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:f+1}),...RH({rawTypeReference:c,example:l,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:f+1})]):ZBe(t,"a map"),list:p=>Array.isArray(t)?t.flatMap((c,o)=>RH({rawTypeReference:p,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:f+1})):ZBe(t,"a list"),set:p=>{if(!Array.isArray(t))return ZBe(t,"a list");let c=suu(t);return c.length>0?[{severity:"error",message:`Set has duplicate elements:
1974
1974
  `+c.map(o=>` - ${JSON.stringify(o)}`).join(`
1975
1975
  `)}]:t.flatMap((o,l)=>RH({rawTypeReference:p,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${l}`],depth:f+1}))},optional:p=>t==null?[]:RH({rawTypeReference:p,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:f+1}),unknown:()=>[],literal:p=>{switch(p.type){case"boolean":return ISe(c=>c===p.boolean,p.boolean.toString())(t);case"string":return ISe(c=>c===p.string,`"${p.string}"`)(t);default:sc(p)}}}})}function Nc1({primitiveType:e,example:t}){return e.v2!=null?JS._visit(e.v2,{integer:r=>Fc1({example:t,rules:r.validation}),long:()=>K0d(t),uint:()=>Q0d(t),uint64:()=>G0d(t),double:r=>Rc1({example:t,rules:r.validation}),float:()=>$0d(t),boolean:()=>Y0d(t),string:r=>Lc1({example:t,rules:r.validation}),uuid:()=>X0d(t),date:()=>k0d(t),dateTime:()=>Z0d(t),base64:()=>lHi(t),bigInteger:()=>lHi(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):lO._visit(e.v1,{integer:()=>tbd(t),long:()=>K0d(t),uint:()=>Q0d(t),uint64:()=>G0d(t),double:()=>rbd(t),float:()=>$0d(t),boolean:()=>Y0d(t),string:()=>lHi(t),uuid:()=>X0d(t),dateTime:()=>Z0d(t),date:()=>k0d(t),base64:()=>lHi(t),bigInteger:()=>lHi(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function Fc1({example:e,rules:t}){let r=tbd(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 Rc1({example:e,rules:t}){let r=rbd(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 Lc1({example:e,rules:t}){let r=lHi(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 lHi=ISe(e=>typeof e=="string","a string"),tbd=ISe(e=>Number.isInteger(e),"an integer"),Q0d=ISe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),G0d=ISe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),$0d=ISe(e=>typeof e=="number","a float"),rbd=ISe(e=>typeof e=="number","a double"),K0d=ISe(e=>Number.isInteger(e),"an integer"),Y0d=ISe(e=>typeof e=="boolean","a boolean"),X0d=ISe(e=>typeof e=="string"&&Bc1.test(e),"a UUID"),Z0d=ISe(e=>typeof e=="string"&&ebd.test(e),"an ISO 8601 timestamp"),k0d=ISe(e=>typeof e=="string"&&Ic1.test(e)&&ebd.test(e),"a date");function ISe(e,t){return r=>e(r)?[]:ZBe(r,t)}function tqn({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&&tqn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return tqn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&tqn({expected:e.container.keyType,actual:t.container.keyType})&&tqn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:Uc1({expected:e.container.literal,actual:t.container.literal});default:sc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;sc(e)}function Uc1({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:sc(e)}}function s4a({_enum:e,file:t}){let r=e.enum.map(n=>({...V$(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:fHi(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 ibd(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 fHi(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function ELu({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:f}){return f4(t,{alias:p=>WD.alias({value:RT({example:r,rawTypeBeingExemplified:typeof p=="string"?p:p.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:f})}),object:p=>nbd({typeName:e,rawObject:p,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:f}),discriminatedUnion:p=>{let c=npi(p);if(!UD(r))throw new Error("Example is not an object");let o=r[c];if(o==null)throw new Error("Example is missing discriminant: "+c);if(typeof o!="string")throw new Error("Discriminant value is not a string");let l=p.union[o];if(l==null)throw new Error(`${o} is not one of the specified discriminant values.`);let m=typeof l=="string"?l:typeof l.type=="string"?l.type:void 0;return WD.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:xHr(p).name,wireValue:c}),singleUnionType:Wc1({rawValueType:m,rawSingleUnionType:l,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,example:r,discriminant:c,discriminantValueForExample:o,workspace:f})})},enum:p=>{if(typeof r!="string")throw new Error("Enum example is not a string");return WD.enum({value:u.casingsGenerator.generateNameAndWireValue({name:ibd(r,p).name,wireValue:r})})},undiscriminatedUnion:p=>{for(let[c,o]of p.union.entries())if(RH({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:f,breadcrumbs:[],depth:0}).length===0)return WD.undiscriminatedUnion({index:c,singleUnionType:RT({example:r,rawTypeBeingExemplified:typeof o=="string"?o:o.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:f})});throw new Error("Example doesn't match any of the undiscriminated unions")}})}function RT({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}){let{resolvedExample:f,file:p}=a.resolveExampleOrThrow({example:e,file:t}),c=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:_ci({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>Vc1({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:m})=>{if(!UD(f))throw new Error("Example is not an object");return Wm.container(KE.map({map:Object.entries(f).map(([O,j])=>({key:RT({example:O,fileContainingExample:p,rawTypeBeingExemplified:l,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:RT({example:j,fileContainingExample:p,rawTypeBeingExemplified:m,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})})),keyType:i.parseTypeReference(l),valueType:i.parseTypeReference(m)}))},list:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return Wm.container(KE.list({list:f.map(m=>RT({example:m,fileContainingExample:p,rawTypeBeingExemplified:l,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(l)}))},set:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return Wm.container(KE.set({set:f.map(m=>RT({example:m,fileContainingExample:p,rawTypeBeingExemplified:l,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(l)}))},optional:l=>Wm.container(KE.optional({optional:f!=null?RT({example:f,fileContainingExample:p,rawTypeBeingExemplified:l,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(l)})),literal:l=>{switch(l.type){case"boolean":return Wm.container(KE.literal({literal:$y.boolean(l.boolean)}));case"string":return Wm.container(KE.literal({literal:$y.string({original:l.string})}));default:sc(l)}},named:l=>{let m=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:i}),O=i.parseTypeReference(l);if(O.type!=="named")throw new Error("Type reference is not to a named type.");let j={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return Wm.named({typeName:j,shape:ELu({typeName:j,typeDeclaration:m.declaration,fileContainingType:m.file,fileContainingExample:p,example:f,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Wm.unknown(c)}}),jsonExample:c}}function Vc1({example:e,typeBeingExemplified:t}){return lO._visit(t,{string:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.date(e))},base64:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.integer(e))},float:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.float(e))},double:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.double(e))},long:()=>{if(typeof e!="number")throw new Error("Example is not a number");return Wm.primitive($y.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error("Example is not a boolean");return Wm.primitive($y.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error("Example is not a string");return Wm.primitive($y.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function nbd({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:f}){if(!UD(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return WD.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((p,[c,o])=>{let l=abd({typeName:e,wirePropertyKey:c,rawObject:t,typeResolver:a,file:i});if(l==null)return p;let m=RT({example:o,fileContainingExample:n,rawTypeBeingExemplified:typeof l.rawPropertyType=="string"?l.rawPropertyType:l.rawPropertyType.type,fileContainingRawTypeReference:l.file,typeResolver:a,exampleResolver:u,workspace:f});return p.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:m,originalTypeDeclaration:l.typeName}),p},[]):[]})}function abd({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:rqn({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function rqn({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"||!YE(u.declaration))throw new Error("Extension is not of a named object");let f=abd({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function Wc1({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:i,typeResolver:n,exampleResolver:a,example:u,discriminant:f,discriminantValueForExample:p,workspace:c}){let o=i.casingsGenerator.generateNameAndWireValue({name:cHi({unionKey:p,rawSingleUnionType:t}).name,wireValue:p});if(e==null)return{wireDiscriminantValue:o,shape:s4.noProperties()};let l=SLu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(l.propertiesType){case"singleProperty":{if(!UD(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:s4.singleProperty(RT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:c}))}}case"samePropertiesAsObject":{if(!UD(u))throw new Error("Example is not an object");let{[f]:m,...O}=u,j=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;oUr(j.declaration);)j=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof j.declaration=="string"?j.declaration:j.declaration.type,file:r});if(!YE(j.declaration))throw new Error(`${e} is not an object`);let A={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:s4.samePropertiesAsObject({typeId:FP.generateTypeId(A),object:nbd({rawObject:j.declaration,example:O,fileContainingType:j.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:A,workspace:c})})}}default:sc(l)}}function c4a({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=zIr({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...V$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function zIr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function R3t(e){return typeof e.request!="string"&&e.request?.["path-parameters"]?e.request?.["path-parameters"]:e["path-parameters"]!=null?e["path-parameters"]:{}}function l4a(e){let t=JSON.stringify(e),r=2166136261;for(let n=0;n<t.length;n++){let a=t.charCodeAt(n);r^=a,r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24)}return(r>>>0).toString(16)}function obd({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:p}){let c=Jc1({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:p});return{id:r.name??l4a(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:Yc1({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...Qc1({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:f,workspace:p}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,l])=>{let m=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(m==null)throw new Error(`Query parameter ${o} does not exist`);return{name:f.casingsGenerator.generateNameAndWireValue({name:zIr({queryParameterKey:o,queryParameter:m}).name,wireValue:o}),value:RT({example:l,rawTypeBeingExemplified:typeof m=="string"?m:m.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:p}),shape:Hc1({queryParameter:m})}}):[],request:Gc1({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:f,workspace:p}),response:$c1({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:f,workspace:p})}}function Hc1({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?h5.exploded():h5.single()}function Jc1({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,variableResolver:a,file:u,workspace:f}){let p=[],c=[],o=[],l=({name:m,pathParameterDeclaration:O,examplePathParameter:j})=>{let A=iqn({parameter:O,variableResolver:a,file:u});return{name:m,value:RT({example:j,rawTypeBeingExemplified:A.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:A.file,fileContainingExample:u,workspace:f})}};if(r["path-parameters"]!=null){let m=R3t(t);for(let[O,j]of Object.entries(r["path-parameters"])){let A=u.rootApiFile["path-parameters"]?.[O],T=e["path-parameters"]?.[O],B=m[O];if(A!=null)p.push(l({name:u.casingsGenerator.generateName(O),pathParameterDeclaration:A,examplePathParameter:j}));else if(B!=null)o.push(l({name:u.casingsGenerator.generateName(O),pathParameterDeclaration:B,examplePathParameter:j}));else if(T!=null)c.push(l({name:u.casingsGenerator.generateName(O),pathParameterDeclaration:T,examplePathParameter:j}));else throw new Error(`Path parameter ${O} does not exist`)}}return{rootPathParameters:p,endpointPathParameters:o,servicePathParameters:c}}function Qc1({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:u}){let f=[],p=[];if(r.headers!=null)for(let[c,o]of Object.entries(r.headers)){let l=typeof t.request!="string"?t.request?.headers?.[c]:void 0,m=e.headers?.[c];if(l!=null)p.push({name:a.casingsGenerator.generateNameAndWireValue({name:sJt({headerKey:c,header:l}).name,wireValue:c}),value:RT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(m!=null)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:sJt({headerKey:c,header:m}).name,wireValue:c}),value:RT({example:o,rawTypeBeingExemplified:typeof m=="string"?m:m.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${c} does not exist`)}return{endpointHeaders:p,serviceHeaders:f}}function Gc1({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"&&Pwn(u)!=null)return;if(!YB(u))return o$.reference(RT({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(!UD(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let f=[];for(let[p,c]of Object.entries(t.request)){let o=u.properties?.[p],l=typeof o=="string"?o:o?.type;if(!(l!=null&&xxe(l)!=null))if(o!=null)f.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:p,property:o}).name,wireValue:p}),value:RT({example:c,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let m=rqn({extends_:u.extends,wirePropertyKey:p,typeResolver:r,file:n});if(m==null)throw new Error("Could not find original type declaration for property: "+p);f.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:p,property:m.rawPropertyType}).name,wireValue:p}),value:RT({example:c,rawTypeBeingExemplified:typeof m.rawPropertyType=="string"?m.rawPropertyType:m.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:m.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:m.typeName})}}return o$.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:f})}function $c1({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?Ox.ok(XB.body(void 0)):yci(e,t.response,{body:f=>{if(f.error!=null){let p=i.getDeclarationOrThrow(f.error,a);return Ox.error({error:qHr({errorName:f.error,file:a}),body:p.declaration.type!=null?RT({example:f.body,rawTypeBeingExemplified:p.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:p.file,fileContainingExample:a,workspace:u}):void 0})}return Ox.ok(XB.body(Kc1({endpoint:e,example:f,typeResolver:r,exampleResolver:n,file:a,workspace:u})))},stream:f=>{let p=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return Ox.ok(XB.stream(f.stream.map(c=>{if(p!=null)return RT({example:c,rawTypeBeingExemplified:p,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(OM)))},events:f=>{let p=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return Ox.ok(XB.sse(f.stream.map(({event:c,data:o})=>{if(p==null)return;let l=RT({example:o,rawTypeBeingExemplified:p,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter(OM)))}})}function Kc1({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 RT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function Yc1({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=OP(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 ubd({endpoint:e,file:t,typeResolver:r}){return{body:Xc1({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function Xc1({endpoint:e,file:t,typeResolver:r}){let i=Zc1({endpoint:e,file:t,typeResolver:r}),n=kc1({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=uH.fileDownload({...i});break}case"json":{a=uH.json({...i.value});break}case"text":{a=uH.text({...i});break}case"bytes":{a=uH.bytes({...i});break}default:sc(i)}return T2.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return T2.streaming(n)}}function Zc1({endpoint:e,file:t,typeResolver:r}){let{response:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type;return xxe(a)!=null?T2.fileDownload({docs:n}):jwn(a)!=null?T2.text({docs:n}):oWt(a)!=null?T2.bytes({docs:n}):el1(i,n,t,r)}}function kc1({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 bRi(a)?Sne.text({docs:n}):typeof i!="string"&&u==="sse"?Sne.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0}):Sne.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0})}}function el1(e,t,r,i){let n=r.parseTypeReference(e),a=i.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?T2.json(P6t.nestedPropertyAsResponse({docs:t,responseBodyType:n,responseProperty:XTn({typeResolver:i,file:r,resolvedType:a,property:u})})):T2.json(P6t.response({docs:t,responseBodyType:n}))}function sbd({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return Axe.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 cbd({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return Axe.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 lbd(e){return tl1(e)?{type:"offset",offset:N3t(e.offset),results:BIr(e.results),step:e.step!=null?N3t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?BIr(e["has-next-page"]):void 0}:{type:"cursor",cursor:N3t(e.cursor),next_cursor:BIr(e.next_cursor),results:BIr(e.results)}}function tl1(e){return e.offset!=null&&e.results!=null}function fbd({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=lbd(n);switch(a.type){case"cursor":return sbd({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return cbd({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});default:sc(a)}}function f4a({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function dbd({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:f4a({source:e}),name:CHr.generateName(r)}}function pbd({file:e,serviceDeclaration:t,sourceResolver:r}){return fci(t.source)?hbd(e,t.source,r,t.transport?.grpc?.["service-name"]):Dxe.http()}function _bd({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=fci(r.source),f=!u;if(n){if(a&&u)throw new Error("Cannot have a grpc endpoint on an http service");if(n&&f)return Dxe.http();if(n&&u){let p=r.source,c=r.transport?.grpc?.["service-name"];return c?hbd(e,p,i,c):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
1976
- ${JSON.stringify(r)}"`)}}function hbd(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=dbd({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Dxe.grpc({service:a})}function ybd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:p,sourceResolver:c,globalErrors:o,workspace:l}){let m=dHi({pathParameters:r["path-parameters"],location:Sxe.Service,file:i,variableResolver:p}),O=pbd({file:i,serviceDeclaration:r,sourceResolver:c}),j={fernFilepath:i.fernFilepath};return{availability:gae(r.availability),name:j,displayName:r["display-name"]??void 0,basePath:XBe(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([T,B])=>kBe({headerKey:T,header:B,file:i})):[],pathParameters:m,encoding:al1(O,r),transport:O,endpoints:Object.entries(r.endpoints).map(([T,B])=>{let z=dHi({pathParameters:R3t(B),location:Sxe.Endpoint,file:i,variableResolver:p}),C={...V$(B),id:"",name:i.casingsGenerator.generateName(T),displayName:B["display-name"],auth:B.auth??r.auth,idempotent:B.idempotent??r.idempotent??!1,baseUrl:B.url??r.url??e,method:B.method!=null?nl1(B.method):wne.Post,basePath:B["base-path"]!=null?XBe(B["base-path"]):void 0,path:XBe(B.path),fullPath:XBe(B["base-path"]!=null?OP(B["base-path"],B.path):i.rootApiFile["base-path"]!=null?OP(i.rootApiFile["base-path"],r["base-path"],B.path):OP(r["base-path"],B.path)),pathParameters:z,allPathParameters:B["base-path"]!=null?z:[...t,...m,...z],queryParameters:typeof B.request!="string"&&B.request?.["query-parameters"]!=null?Object.entries(B.request["query-parameters"]).map(([N,U])=>c4a({file:i,queryParameterKey:N,queryParameter:U})):[],headers:typeof B.request!="string"&&B.request?.headers!=null?Object.entries(B.request.headers).map(([N,U])=>kBe({headerKey:N,header:U,file:i})):[],requestBody:T0d({request:B.request,file:i}),sdkRequest:I0d({service:r,request:B.request,endpoint:B,endpointKey:T,file:i,typeResolver:a,propertyResolver:u}),response:ubd({endpoint:B,file:i,typeResolver:a}),errors:[...S0d({errors:B.errors,file:i}),...o],userSpecifiedExamples:B.examples!=null?B.examples.map(N=>({example:obd({service:r,endpoint:B,example:N,typeResolver:a,errorResolver:n,exampleResolver:f,variableResolver:p,file:i,workspace:l}),codeSamples:N["code-samples"]?.map(U=>z0d({codeSample:U,file:i}))})):[],autogeneratedExamples:[],pagination:fbd({propertyResolver:u,file:i,endpointName:T,endpointSchema:B}),transport:_bd({file:i,serviceTransport:O,endpointDeclaration:B,sourceResolver:c})};return C.id=FP.generateEndpointId(j,C),C})}}function dHi({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>rl1({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function rl1({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...V$(t),name:i.casingsGenerator.generateName(e),valueType:il1({parameter:t,variableResolver:n,file:i}),location:r,variable:_8i(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function il1({parameter:e,variableResolver:t,file:r}){let i=iqn({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function iqn({parameter:e,variableResolver:t,file:r}){let i=d4a({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function d4a({parameter:e,variableResolver:t,file:r}){if(_8i(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 nl1(e){switch(e){case"GET":return wne.Get;case"POST":return wne.Post;case"PUT":return wne.Put;case"PATCH":return wne.Patch;case"DELETE":return wne.Delete;default:sc(e)}}function kBe({headerKey:e,header:t,file:r}){let{name:i}=sJt({headerKey:e,header:t});return{...V$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function sJt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function al1(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:sc(e)}}var W$={};Gs(W$,{validateObjectExample:()=>ipi,validateTypeExample:()=>u4a,validateTypeReferenceExample:()=>RH});function vbd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function p4a({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function bbd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:FP.generateEndpointIdFromResolvedEndpoint(n),serviceId:FP.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:p4a({fernFilePath:n.file.fernFilepath})?void 0:FP.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 gbd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:FP.generateEndpointIdFromResolvedEndpoint(n),serviceId:FP.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:p4a({fernFilePath:n.file.fernFilepath})?void 0:FP.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},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 mbd({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=gbd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?bbd({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:f}}var nqn={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}},ALu={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 Obd(e){return{endpoint:e["get-token"].endpoint,requestProperties:ol1({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ul1({responseProperties:e["get-token"]?.["response-properties"]})}}function Pbd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:sl1({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:cl1({responseProperties:e["refresh-token"]?.["response-properties"]})}}function ol1({requestProperties:e}){if(e==null)return nqn.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?N3t(t):nqn.requestProperties.client_id,client_secret:r!=null?N3t(r):nqn.requestProperties.client_secret,scopes:i!=null?N3t(i):nqn.requestProperties.scopes}}function ul1({responseProperties:e}){return jbd({responseProperties:e,defaultValue:nqn.responseProperties})}function sl1({requestProperties:e}){if(e==null)return ALu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?N3t(t):ALu.requestProperties.refresh_token}}function cl1({responseProperties:e}){return jbd({responseProperties:e,defaultValue:ALu.responseProperties})}function jbd({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?BIr(r):t.access_token,expires_in:i!=null?BIr(i):t.expires_in,refresh_token:n!=null?BIr(n):t.refresh_token}}function Abd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:GLr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return wwn(e.auth,{single:a=>{let u=wbd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:GLr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:GLr.Any,schemes:a.map(u=>wbd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function wbd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(f,p)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return Dgu(c,{header:o=>oH.header({docs:p,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>Sbd({file:r,docs:p,rawScheme:o}),bearer:o=>Dbd({file:r,docs:p,rawScheme:o}),oauth:o=>Ebd({file:r,docs:p,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Dbd({file:r,docs:void 0,rawScheme:void 0});case"basic":return Sbd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return Ebd({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Dbd({file:e,docs:t,rawScheme:r}){return oH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Sbd({file:e,docs:t,rawScheme:r}){return oH.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 Ebd({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return oH.oauth({docs:t,configuration:$Lr.clientCredentials(mbd({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Obd(r),refreshTokenEndpoint:Pbd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Mbd({file:e,rawApiFileSchema:t}){if(t.version!=null)return YLr.header({header:ll1({file:e,header:t.version.header}),value:fl1({file:e,versionDeclaration:t.version})})}function ll1({file:e,header:t}){return typeof t=="string"?kBe({file:e,headerKey:t,header:{type:"string"}}):kBe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function fl1({file:e,versionDeclaration:t}){return s4a({_enum:{default:t.default,enum:t.values},file:e})}function Tbd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[f,p]of Object.entries(e.messages??{}))u.push({type:f,availability:gae(p.availability),docs:p.docs,origin:p.origin,body:_l1({body:p.body,file:n}),displayName:p["display-name"]});return{availability:gae(e.availability),path:XBe(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(([f,p])=>kBe({headerKey:f,header:p,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?dHi({pathParameters:e["path-parameters"],location:Sxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([f,p])=>{let{name:c}=zIr({queryParameterKey:f,queryParameter:p}),o=n.parseTypeReference(p);return{...V$(p),name:n.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof p!="string"&&p["allow-multiple"]!=null?p["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let p=yl1({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:f.name!=null?n.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:bl1({channel:e,example:f,pathParams:p}),...p,...vl1({channel:e,example:f,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:f["query-parameters"]!=null?Object.entries(f["query-parameters"]).map(([c,o])=>{let l=e["query-parameters"]?.[c];if(l==null)throw new Error(`Query parameter ${c} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:zIr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:RT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:dl1({queryParameter:l})}}):[],messages:f.messages.map(c=>{let o=e.messages?.[c.type];if(o==null)throw new Error(`Message ${c.type} does not exist`);return{type:c.type,body:pl1({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function dl1({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?h5.exploded():h5.single()}function pl1({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!gl1(e.body))return D6t.reference(RT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!UD(t))throw new Error("Example must be an object");let u=[];for(let[f,p]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:f,property:c}).name,wireValue:f}),value:RT({example:p,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=rqn({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:RT({example:p,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 D6t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function _l1({body:e,file:t}){return typeof e=="string"?qne.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):hl1(e)?qne.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):qne.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:z3t(e.extends??[]).map(r=>pU({typeName:r,file:t})),properties:[]})}function hl1(e){return e.type!=null}function yl1({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let f=[],p=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let m=iqn({parameter:o,variableResolver:n,file:a});return{name:c,value:RT({example:l,rawTypeBeingExemplified:m.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:m.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let c=R3t(e);for(let[o,l]of Object.entries(t["path-parameters"])){let m=c[o];if(m!=null)f.push(p({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:m,examplePathParameter:l}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:f}}function vl1({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[f,p]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:sJt({headerKey:f,header:c}).name,wireValue:f}),value:RT({example:p,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function bl1({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 gl1(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function MLu({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:t2r(i,{singleBaseUrl:()=>g6t.singleBaseUrl(ml1({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>g6t.multipleBaseUrls(Ol1({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function ml1({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>t2r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:qbd(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function Ol1({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>t2r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Ih(a.urls,u=>qbd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function qbd(e){return e.endsWith("/")?e.slice(0,-1):e}function Cbd({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let f of t.examples)u.push({name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,docs:f.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:RT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:qHr({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 xbd="content";function Bbd(e,t){if(e==null||e.strategy==="status-code")return j6t.statusCode();switch(e.strategy){case"property":return j6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:xbd,wireValue:xbd})});default:sc(e)}}function Ibd({readme:e,services:t}){let r=new TLu(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 TLu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=jl1({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:Pl1(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function Pl1(e){let t="";e.fullPath.head.length>0&&(t=OP(t,e.fullPath.head));for(let r of e.fullPath.parts)t=OP(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=OP(t,r.tail));return t.startsWith("/")?t:`/${t}`}function jl1({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 zbd({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:FP.generateWebhookId(t.fernFilepath,u),availability:gae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?Object.entries(f.headers).map(([p,c])=>kBe({headerKey:p,header:c,file:t})):[],payload:wl1({payload:f.payload,file:t}),examples:f.examples!=null?Sl1({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function wl1({payload:e,file:t}){return typeof e=="string"?Tne.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):_4a(e)?Tne.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Tne.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:z3t(e.extends).map(r=>pU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>Dl1({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?gae(i.availability):void 0,file:t})):[]})}function Dl1({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:FH({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function Sl1({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:_4a(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:RT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!UD(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:RT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function _4a(e){return e.type!=null}function pHi(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 Nbd({name:e,source:t}){return k1.userDefined({file:f4a({source:t}),name:CHr.generateName(e)})}function Fbd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=El1({type:e.proto.type});if(t!=null)return t}}function El1({type:e}){switch(e){case"google.protobuf.Any":return k1.wellKnown(F_.any());case"google.protobuf.Api":return k1.wellKnown(F_.api());case"google.protobuf.BoolValue":return k1.wellKnown(F_.boolValue());case"google.protobuf.BytesValue":return k1.wellKnown(F_.bytesValue());case"google.protobuf.DoubleValue":return k1.wellKnown(F_.doubleValue());case"google.protobuf.Duration":return k1.wellKnown(F_.duration());case"google.protobuf.Empty":return k1.wellKnown(F_.empty());case"google.protobuf.Enum":return k1.wellKnown(F_.enum());case"google.protobuf.EnumValue":return k1.wellKnown(F_.enumValue());case"google.protobuf.Field":return k1.wellKnown(F_.field());case"google.protobuf.FieldCardinality":return k1.wellKnown(F_.fieldCardinality());case"google.protobuf.FieldKind":return k1.wellKnown(F_.fieldKind());case"google.protobuf.FieldMask":return k1.wellKnown(F_.fieldMask());case"google.protobuf.FloatVlaue":return k1.wellKnown(F_.floatValue());case"google.protobuf.Int32Value":return k1.wellKnown(F_.int32Value());case"google.protobuf.Int64Value":return k1.wellKnown(F_.int64Value());case"google.protobuf.ListValue":return k1.wellKnown(F_.listValue());case"google.protobuf.Method":return k1.wellKnown(F_.method());case"google.protobuf.Mixin":return k1.wellKnown(F_.mixin());case"google.protobuf.NullValue":return k1.wellKnown(F_.nullValue());case"google.protobuf.Option":return k1.wellKnown(F_.option());case"google.protobuf.SourceContext":return k1.wellKnown(F_.sourceContext());case"google.protobuf.StringValue":return k1.wellKnown(F_.stringValue());case"google.protobuf.Struct":return k1.wellKnown(F_.struct());case"google.protobuf.Syntax":return k1.wellKnown(F_.syntax());case"google.protobuf.Timestamp":return k1.wellKnown(F_.timestamp());case"google.protobuf.Type":return k1.wellKnown(F_.type());case"google.protobuf.Uint32Value":return k1.wellKnown(F_.uint32Value());case"google.protobuf.Uint64Value":return k1.wellKnown(F_.uint64Value());case"google.protobuf.Value":return k1.wellKnown(F_.value())}}function Rbd({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=e7(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&YE(a.declaration)){let u=e7(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([p,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=n.arguments?.[u.indexOf(c)]??c),[p,o]});return iB.object({extends:z3t(a.declaration.extends).map(p=>pU({typeName:p,file:t})),properties:YTn({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Lbd({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return wxe(i)?Rbd({generic:i,file:t,typeResolver:r}):iB.alias({aliasOf:t.parseTypeReference(e),resolvedType:Al1({aliasOf:i,file:t,typeResolver:r})})}function Al1({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return sH.primitive(i.originalTypeReference.primitive);case"container":return sH.container(i.originalTypeReference.container);case"unknown":return sH.unknown();case"named":{let n=YE(i.declaration)?w6t.Object:uUr(i.declaration)?w6t.Union:A6t(i.declaration)?w6t.Enum:h8i(i.declaration)?w6t.UndiscriminatedUnion:sc(i.declaration);return sH.named({name:i.name,shape:n})}}}function Ubd({union:e,file:t}){return iB.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function Vbd(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 CLu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new qLu}){let n=f4(e,{alias:u=>{let f=typeof u=="string"?u:u.type,p=e7(f);if(p!=null){let c=new Set(p.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=e7(o.typeName)?.arguments;if(YE(o.declaration)){let m=Vbd(o.declaration);l&&m.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>Vbd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(p=>typeof p=="string"?p:p.type)),f.push(...Object.values(u.union).reduce((p,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&p.push(o),p},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,p)=>{let c=typeof p=="string"?p:p.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of n){let f=l$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:p,valueType:c})=>[...p,...c],list:p=>p,optional:p=>p,set:p=>p,named:p=>[p],literal:()=>[],unknown:()=>[]}});for(let p of f){let c=pU({typeName:p,file:t});if(!i.hasTypeNameBeenSeen(c)){i.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:p,file:t});if(wxe(o.typeName))continue;a.push(...CLu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var qLu=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 Wbd({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let f=V$(t),p=pU({typeName:e,file:r}),c=CLu({typeDeclaration:t,file:r,typeResolver:i}),o={};YE(t)&&(o=pHi(t.properties??{}));let l=Tl1({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:Bl1(t),name:p,shape:Ml1({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(c.map(m=>m.typeId)),encoding:ql1({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(m=>({name:m.name!=null?r.casingsGenerator.generateName(m.name):void 0,docs:m.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:m.value,file:r}).resolvedExample,shape:ELu({typeName:p,example:m.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(m=>m.fernFilepath))}}function Ml1({typeDeclaration:e,file:t,typeResolver:r}){return f4(e,{alias:i=>Lbd({alias:i,file:t,typeResolver:r}),object:i=>A0d({object:i,file:t}),discriminatedUnion:i=>W0d({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>Ubd({union:i,file:t}),enum:i=>iB.enum(s4a({_enum:i,file:t}))})}function Tl1({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=Fbd({encoding:t.encoding});if(a!=null)return kBr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return kBr.proto(Nbd({source:n,name:r}))}function ql1({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?Cl1(e.encoding):xl1(t)}function Cl1(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function xl1(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Bl1(e){if(typeof e!="string"&&"inline"in e)return e.inline}var Hbd="1.0.0";var h4a=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:Hbd,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:qd.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return qd.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 qd.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:sc(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return qd.ReferencedRequestBodyType.bytes();case"typeReference":return qd.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:sc(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return qd.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 qd.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return qd.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:qd.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return qd.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:qd.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:sc(r)}}convertFileUploadRequestBody({properties:t}){return qd.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 qd.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:sc(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return qd.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return qd.FileUploadRequestBodyProperty.fileArray(t.key);default:sc(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=qd.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:sc(t)}}convertContainerType(t){switch(t.type){case"list":return qd.TypeReference.list(this.convertTypeReference(t.list));case"map":return qd.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return qd.TypeReference.optional(this.convertTypeReference(t.optional));case"set":return qd.TypeReference.set(this.convertTypeReference(t.set));case"literal":return qd.TypeReference.literal(this.convertLiteral(t.literal));default:sc(t)}}convertNamedType(t){return qd.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:sc(t.shape)}}convertAlias({declaration:t,alias:r}){return qd.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return qd.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 qd.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return qd.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:sc(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return qd.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return qd.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 qd.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return qd.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return qd.LiteralType.boolean(t.boolean);case"string":return qd.LiteralType.string(t.string);default:sc(t)}}convertPrimitiveType(t){return qd.TypeReference.primitive(t.v1)}convertUnknownType(){return qd.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return qd.Auth.basic(r);case"bearer":return qd.Auth.bearer(r);case"header":return qd.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:sc(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=OP(r,t.fullPath.head));for(let i of t.fullPath.parts)r=OP(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=OP(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function Jbd(e){return new h4a(e).convert()}function Gbd({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return Fl1({fieldName:e,validation:Il1(t.v2)});case"BASE_64":return{type:"success",example:$y.base64(bP.BASE64),jsonExample:bP.BASE64};case"BOOLEAN":return{type:"success",example:$y.boolean(bP.BOOLEAN),jsonExample:bP.BOOLEAN};case"DATE":return{type:"success",example:$y.date(bP.DATE),jsonExample:bP.DATE};case"DATE_TIME":return{type:"success",example:$y.datetime({datetime:new Date(bP.DATE_TIME),raw:bP.DATE_TIME}),jsonExample:bP.DATE_TIME};case"DOUBLE":return Rl1({fieldName:e,validation:zl1(t.v2)});case"FLOAT":return{type:"success",example:$y.float(bP.FLOAT),jsonExample:bP.FLOAT};case"INTEGER":return Ll1({fieldName:e,validation:Nl1(t.v2)});case"UINT_64":return{type:"success",example:$y.uint64(bP.INT64),jsonExample:bP.INT64};case"UINT":return{type:"success",example:$y.uint(bP.UINT),jsonExample:bP.UINT};case"BIG_INTEGER":return{type:"success",example:$y.bigInteger(bP.INT64.toString()),jsonExample:`${bP.INT64}`};case"LONG":return{type:"success",example:$y.long(bP.INT64),jsonExample:bP.INT64};case"UUID":return{type:"success",example:$y.uuid(bP.UUID),jsonExample:bP.UUID};default:sc(t.v1)}}function Il1(e){if(e?.type==="string")return e.validation}function zl1(e){if(e?.type==="double")return e.validation}function Nl1(e){if(e?.type==="integer")return e.validation}function Qbd(e){if(e<=bP.SAMPLE_STRINGS.length){let t=bP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return bP.SAMPLE_STRINGS[bP.SAMPLE_STRINGS.length-1]+".".repeat(e-bP.SAMPLE_STRINGS.length)}function Fl1({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=Qbd(i);return{type:"success",example:$y.string({original:a}),jsonExample:a}}else if(n){let a=Qbd(n);return{type:"success",example:$y.string({original:a}),jsonExample:a}}}let r=e??bP.STRING;return{type:"success",example:$y.string({original:r}),jsonExample:r}}function Rl1({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$y.double(r),jsonExample:r};if(i)return{type:"success",example:$y.double(i),jsonExample:i}}return{type:"success",example:$y.double(bP.DOUBLE),jsonExample:bP.DOUBLE}}function Ll1({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$y.integer(r),jsonExample:r};if(i)return{type:"success",example:$y.integer(i),jsonExample:i}}return{type:"success",example:$y.integer(bP.INT),jsonExample:bP.INT}}function $bd({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return BHr({containerType:t});switch(t.type){case"list":{let u=sz({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:KE.literal({literal:t.literal._visit({boolean:u=>$y.boolean(u),string:u=>$y.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 BHr({containerType:t});let u=sz({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=sz({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=sz({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),f=sz({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:sc(t)}}function BHr({containerType:e}){switch(e.type){case"list":return{type:"success",example:KE.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:KE.literal({literal:e.literal._visit({boolean:t=>$y.boolean(t),string:t=>$y.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:KE.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:KE.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:KE.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:sc(e)}}function _Hi({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 Ybd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=sz({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:p}=u;return{type:"success",example:WD.alias({value:f}),jsonExample:p}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:WD.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=Kbd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:p}=u;return{type:"success",example:WD.object(f),jsonExample:p}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let p=sz({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(p.type==="failure"){++u;continue}let{example:c,jsonExample:o}=p;return{type:"success",example:WD.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let p=f.shape._visit({noProperties:()=>({type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue}}),samePropertiesAsObject:c=>{let o=t[c.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${c.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let l=Kbd({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:m,jsonExample:O}=l;return{type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.samePropertiesAsObject({typeId:o.name.typeId,object:m})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=sz({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:m}=o;return{type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:m}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(p.type!=="failure")return p}}}return{type:"failure",message:"Failed to generate example for type reference"}}function Kbd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let f={},p=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=sz({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!_Hi({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:m}=o;p.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=m}return{type:"success",example:WD.object({properties:p}),jsonExample:f}}function sz({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 f=Ybd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:p,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:Wm.named({shape:p,typeName:u.name})},jsonExample:c}}case"container":{let u=$bd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=BHr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Wm.container(c)},jsonExample:o}}let{example:f,jsonExample:p}=u;return{type:"success",example:{jsonExample:p,shape:Wm.container(f)},jsonExample:p}}case"primitive":{let{jsonExample:u,example:f}=Gbd({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Wm.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Wm.unknown(u)},jsonExample:u}}}}var xLu=wM.primitive({v1:lO.String,v2:JS.string({default:void 0,validation:void 0})});function aqn({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:Ox.ok(XB.body(void 0)),docs:void 0},f=[{params:t.pathParameters,add:c=>u.endpointPathParameters.push(c)},{params:r.pathParameters,add:c=>u.servicePathParameters.push(c)},{params:e.pathParameters,add:c=>u.rootPathParameters.push(c)}];for(let c of f)for(let o of c.params){let l=sz({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(l.type==="failure")return l;let{example:m}=l;c.add({name:o.name,value:m})}for(let c of t.queryParameters){if(n&&_Hi({typeDeclarations:i,typeReference:c.valueType}))continue;let o=sz({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:c.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?h5.exploded():h5.single(),value:l})}let p=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of p)for(let o of c.params){if(n&&_Hi({typeDeclarations:i,typeReference:o.valueType}))continue;let l=sz({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(l.type==="failure")return l;let{example:m}=l;c.add({name:o.name,value:m})}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 c={},o=[];for(let l of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let m=sz({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(m.type==="failure"&&!_Hi({typeDeclarations:i,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${m.message}`};if(m.type==="failure")continue;let{example:O,jsonExample:j}=m;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=j}u.request=o$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:o}=c;u.request=o$.reference(o);break}default:sc(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 c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"streamParameter":{let c;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":c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1});break;default:sc(t.response.body.nonStreamResponse)}if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"streaming":{let c;switch(t.response.body.value.type){case"sse":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.sse([{data:{...o,jsonExample:l},event:""}]));break}case"json":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.stream([{...o,jsonExample:l}]));break}case"text":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.stream([{...o,jsonExample:l}]));break}default:sc(t.response.body.value)}break}case"text":{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:sc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Ox.error({body:void 0,error:a.declaration.name});else{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:o}=c;u.response=Ox.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:l4a(u),url:Ul1(t,u),...u},jsonExample:void 0}}function Ul1(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 Xbd(e,t){let r=t[e];if(r==null)throw new pBr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Zbd(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,Wl1({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>Vl1({endpoint:i,ir:e}))}]))}}function Vl1({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>kbd(r,t))}}}function Wl1({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>kbd(r,t))}}}return e}function kbd(e,t){let r=BLu(e.typeId,t);return egd({objectTypeDeclaration:r,ir:t})}function BLu(e,t){let r=Xbd(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return BLu(r.shape.resolvedType.name.typeId,t)}throw new pBr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function egd({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=BLu(i.typeId,t);return egd({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}var y4a=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:f,subpackages:p,queryParameters:c,requestProperties:o,webhookPayloadProperties:l,channels:m}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=p,this.requestProperties=o,this.queryParameters=c,this.channels=m}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=FP.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=FP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=FP.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 b4a=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=Hl1(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=FP.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=FP.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=FP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&G6(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=FP.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,p=new Set;for(let c of[...t.headers,...r.headers])G6(c.valueType,u,p);for(let c of[...t.pathParameters,...r.pathParameters])G6(c.valueType,u,p);for(let c of r.queryParameters)G6(c.valueType,u,p);if(i!=null&&i.request!=null&&typeof i.request!="string"){let c=pHi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&cR._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)v4a(o,u,p);for(let o of c.properties)G6(o.valueType,u,p);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&YB(i.request.body)){let o=pHi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{G6(c,u,p)},fileUpload:({properties:c})=>{for(let o of c)Dne._visit(o,{file:Mc,bodyProperty:({valueType:l})=>{G6(l,u,p)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&T2._visit(r.response.body,{fileDownload:Mc,json:c=>{G6(c.responseBodyType,u,p)},streaming:c=>{c._visit({sse:o=>G6(o.payload,u,p),json:o=>G6(o.payload,u,p),text:Mc,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>G6(o.payload,u,p),json:o=>G6(o.payload,u,p),text:Mc,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&G6(c.nonStreamResponse.value.responseBodyType,u,p)},text:Mc,bytes:Mc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(FP.generateErrorId(c.error)),p.add(c.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:f,referencedSubpackages:p}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=FP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),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&&Tne._visit(r.payload,{inlinedPayload:f=>{for(let p of f.extends)v4a(p,a,u);for(let p of f.properties)G6(p.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!_4a(i.payload)){let p=pHi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:p}}},reference:({payloadType:f})=>{G6(f,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 f of i.messages)qne._visit(f.body,{reference:({bodyType:p})=>{G6(p,a,u)},inlinedBody:p=>{for(let c of p.extends)v4a(c,a,u);for(let c of p.properties)G6(c.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 f of this.endpointsNeededForAudience.keys()){let p=this.getEndpointNode(f);for(let c of p.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,p.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let p=this.getWebhookNode(f);this.addReferencedTypes(t,p.referencedTypes)}for(let f of this.channelsNeededForAudience.keys()){let p=this.getChannelNode(f);this.addReferencedTypes(t,p.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,p]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}c.size>0&&(i[f]=c),i[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}n[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.parametersByAudience[o];l?.forEach(m=>{c.add(m)})}a[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}u[f]=c.size>0?c:void 0}}return new y4a({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(f=>{t.add(f)});else{n.allDescendants.forEach(f=>{t.add(f)});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:sc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(FP.generateSubpackageId(i))}}};function Hl1(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:sc(e)}}function G6(e,t,r){wM._visit(e,{container:i=>{Jl1(i,t,r)},named:i=>{v4a(i,t,r)},primitive:Mc,unknown:Mc,_other:Mc})}function v4a(e,t,r){t.add(FP.generateTypeId(e)),r.add(e.fernFilepath)}function Jl1(e,t,r){nB._visit(e,{list:i=>{G6(i,t,r)},map:i=>{G6(i.keyType,t,r),G6(i.valueType,t,r)},optional:i=>{G6(i,t,r)},set:i=>{G6(i,t,r)},literal:Mc,_other:Mc})}function rgd({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:$6({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?s4.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=$6({filteredIr:e,exampleTypeReference:r});return i!==void 0?s4.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function $6({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Wm.container(KE.list({...i,list:i.list.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Wm.container(KE.set({...i,set:i.set.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?$6({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Wm.container(KE.optional({optional:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Wm.container(KE.map({...i,map:i.map.map(n=>{let a=$6({filteredIr:e,exampleTypeReference:n.key}),u=$6({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=$6({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Wm.named({...r,shape:WD.enum(i)})}),object:i=>({...t,shape:Wm.named({...r,shape:WD.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:$6({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=rgd({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=$6({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function ILu({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Ql1({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function tgd({filteredIr:e,headers:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Gl1({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=$6({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=$6({filteredIr:e,exampleTypeReference:r});return i!==void 0?o$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function $l1({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Ox.ok(XB.body(i!=null?$6({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Ox.ok(XB.stream(i.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(OM))),sse:i=>Ox.ok(XB.sse(i.map(({event:n,data:a})=>{let u=$6({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(OM))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Ox.error({error:r,body:i!=null?$6({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function zLu({filteredIr:e,example:t}){return{...t,rootPathParameters:ILu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:ILu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:ILu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:tgd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:tgd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:Ql1({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?Gl1({filteredIr:e,requestBody:t.request}):void 0,response:$l1({filteredIr:e,response:t.response})}}function igd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:WD.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:WD.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:$6({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=rgd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:WD.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=$6({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:WD.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var g4a=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:FP.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:Ih(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!ngd(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(!ngd(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(c=>{let o=this.subpackages[c];if(o==null)throw new Error("Subpackage ID is invalid: "+c);return o}),u=r+1,f={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},p=a.find(c=>c.name.originalName===n.originalName);if(p==null){let c=FP.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,i.subpackages.push(c),p=o}return this.getPackageForFernFilepath(t,u,p)}};function ngd(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 agd({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 f=r[i];if(f!=null)return{endpointName:n,relativeFilepath:THr({referencedIn:t,importPath:f})}}var api=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 O4(this.workspace,(n,a,u)=>{let f=fO({relativeFilepath:n,definitionFile:a,casingsGenerator:CHr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[p,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(i={endpointId:p,endpoint:c,file:f})}),Wfi(this.workspace,(n,a)=>{let u=fO({relativeFilepath:n,definitionFile:a,casingsGenerator:CHr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,p]of Object.entries(a.service?.endpoints??{}))p.method===t&&p.path===r&&(i={endpointId:f,endpoint:p,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new vci().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=agd({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var opi=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=BSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:fO({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var zSe=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(UD(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(`\\${GVt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(GVt))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(GVt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(GVt.length),exampleName:n}}};var m4a=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:Ene.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=typeof i["query-parameters"]!=null?i["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Ene.query(c4a({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:Ene.body(u)}}if(YB(i.body)){let u=jLu({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Ene.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:Ene.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return PLu({typeResolver:this.typeResolver,file:ZTn(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 MA=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=BSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=e7(i.typeName);if(u!=null){for(let f of Object.keys(n.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let p=n.types?.[f];return p!=null?{typeName:f,declaration:p,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return l$({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:wM.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:wM.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:wM.container(nB.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:wM.container(nB.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:wM.container(nB.optional(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:wM.container(nB.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:wM.container(nB.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(f=>f.file===u.file&&f.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(oUr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let f=eqn({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||cae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:f,file:u}}};var L3t=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:IIr({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 O4a(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function LH({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,disableExamples:n,audiences:a,readme:u,packageName:f,version:p,context:c,fdrApiDefinitionId:o,includeOptionalRequestPropertyExamples:l,sourceResolver:m}){let O=oJt({generationLanguage:t,keywords:r,smartCasing:i}),j=new b4a(a),A=IIr({casingsGenerator:O,rootApiFile:e.definition.rootApiFile.contents}),T=(e.definition.rootApiFile.contents.errors??[]).map(pi=>({error:qHr({errorName:pi,file:A}),docs:void 0})),B=new MA(e),z=new api(e),C=new m4a(B,z),N=new opi(e),U=new zSe(B),k=new L3t,ve={fdrApiDefinitionId:o,apiVersion:Mbd({file:A,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:O.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:i4a(e.definition.rootApiFile.contents.docs),auth:Abd({rawApiFileSchema:e.definition.rootApiFile.contents,file:A,propertyResolver:C,endpointResolver:z}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([pi,Ft])=>kBe({headerKey:pi,header:Ft,file:A})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([pi,Ft])=>kBe({headerKey:pi,header:Ft,file:A})):[],types:{},errors:{},services:{},constants:vbd(O),environments:MLu({casingsGenerator:O,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:Bbd(e.definition.rootApiFile.contents["error-discrimination"],A),basePath:e.definition.rootApiFile.contents["base-path"]!=null?XBe(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:dHi({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:A,location:Sxe.Root,variableResolver:k}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([pi,Ft])=>({docs:typeof Ft!="string"?Ft.docs:void 0,id:pi,name:A.casingsGenerator.generateName(pi),type:A.parseTypeReference(Ft)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},Y=new g4a,X=pi=>{Y.addSubpackage(pi.fernFilepath),LD(pi.definitionFile,{imports:Mc,docs:Ft=>{Ft!=null&&Y.addDocs(pi.fernFilepath,Ft)},types:Ft=>{if(Ft!=null)for(let[Xt,ei]of Object.entries(Ft)){if(wxe(Xt))continue;let ai=Wbd({typeName:Xt,typeDeclaration:ei,file:pi,typeResolver:B,exampleResolver:U,sourceResolver:m,workspace:e}),hn=ai.typeDeclaration;n&&(hn.userProvidedExamples=[],hn.autogeneratedExamples=[]);let cn=ai.descendantFilepaths,ia=FP.generateTypeId(hn.name);ve.types[ia]=hn,Y.addType(ia,hn),j.addType({declaredTypeName:hn.name,descendantTypeIds:hn.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:ai.propertiesByAudience,descendantFilepaths:cn}),j.markTypeForAudiences(hn.name,E0d(ei))}},errors:Ft=>{if(Ft==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[ei,ai]of Object.entries(Ft)){let hn=Cbd({errorName:ei,errorDeclaration:ai,file:pi,typeResolver:B,exampleResolver:U,workspace:e}),cn=FP.generateErrorId(hn.name);ve.errors[cn]=hn,Y.addError(cn,hn),j.addError(hn)}},service:Ft=>{if(Ft==null)return;let Xt=ybd({rootDefaultUrl:pi.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:ve.pathParameters,serviceDefinition:Ft,file:pi,errorResolver:N,typeResolver:B,propertyResolver:C,exampleResolver:U,sourceResolver:m,globalErrors:T,variableResolver:k,workspace:e}),ei=FP.generateServiceId(Xt.name);ve.services[ei]=Xt,Y.addService(ei,Xt);let ai={};Xt.endpoints.forEach(hn=>{n&&(hn.autogeneratedExamples=[],hn.userSpecifiedExamples=[]);let cn=Ft.endpoints[hn.name.originalName];j.addEndpoint(Xt,hn,cn),ai[hn.name.originalName]=hn}),Ft.audiences!=null&&j.markEndpointForAudience(Xt.name,Xt.endpoints,Ft.audiences),Object.entries(Ft.endpoints).map(([hn,cn])=>{let ia=ai[hn];ia!=null&&cn.audiences!=null&&j.markEndpointForAudience(Xt.name,[ia],cn.audiences)})},webhooks:Ft=>{if(Ft==null)return;let Xt=FP.generateWebhookGroupId(pi.fernFilepath),ei=zbd({webhooks:Ft,file:pi,typeResolver:B,exampleResolver:U,workspace:e}),ai={};for(let hn of ei)ai[hn.name.originalName]=hn;Object.entries(Ft).forEach(([hn,cn])=>{let ia=ai[hn];ia!=null&&(j.addWebhook(pi,ia,cn),cn.audiences!=null&&j.markWebhookForAudiences(pi,ia,cn.audiences))}),ve.webhookGroups[Xt]=ei,Y.addWebhookGroup(Xt,pi.fernFilepath)},channel:Ft=>{if(Ft==null)return;let Xt=FP.generateWebSocketChannelId(pi.fernFilepath),ei=Tbd({channel:Ft,file:pi,variableResolver:k,typeResolver:B,exampleResolver:U,workspace:e});j.addChannel(pi,Xt,ei,Ft),Ft.audiences!=null&&j.markChannelForAudiences(pi,Xt,Ft.audiences),ve.websocketChannels!=null&&(ve.websocketChannels[Xt]=ei,Y.addWebSocketChannel(Xt,pi.fernFilepath))}})};O4(e,(pi,Ft,Xt)=>{X(fO({relativeFilepath:pi,definitionFile:Ft,casingsGenerator:O,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Xt.defaultUrl}))}),Wfi(e,(pi,Ft)=>{if(Ft.navigation!=null)if(typeof Ft.navigation=="string")Y.addPackageRedirection({from:bae({relativeFilepath:pi,casingsGenerator:O}),to:bae({relativeFilepath:M6(tCe(pi),Q0.of(Ft.navigation)),casingsGenerator:O})});else{let Xt=Ft.navigation.map(ei=>FP.generateSubpackageId(bae({relativeFilepath:M6(tCe(pi),Q0.of(ei)),casingsGenerator:O})));pi===HE?Y.sortRootPackage(Xt):Y.sortSubpackage(FP.generateSubpackageId(bae({relativeFilepath:pi,casingsGenerator:O})),Xt)}}),ve.serviceTypeReferenceInfo=Yl1(j);let Ae=n?ve:Kl1(ve,c,!l),pt=e.definition.rootApiFile.contents,ct=MLu({casingsGenerator:O,rawApiFileSchema:pt}),Dt=ct?.environments._visit({singleBaseUrl:pi=>pi.environments.filter(Ft=>O4a(Ft.id,pt.environments)!=null).length===0,multipleBaseUrls:pi=>pi.environments.filter(Ft=>O4a(Ft.id,pt.environments)!=null).length===0,_other:()=>!1});ct?.environments.environments.forEach(pi=>{j.markEnvironmentForAudiences(pi,O4a(pi.id,pt.environments)??[],Dt)});let Rt=j.hasNoAudiences()?void 0:j.build(),Zt=Xl1(Ae,Rt),Vt=e.definition.rootApiFile.contents.auth!=null&&Object.values(Zt.services).every(pi=>pi.endpoints.every(Ft=>Ft.auth)),sr=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.response?.body?.type==="streaming")),Wr=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.pagination!=null)),mi=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.response?.body?.type==="fileDownload")),Yt={isAuthMandatory:Vt,hasStreamingEndpoints:sr,hasPaginatedEndpoints:Wr,hasFileDownloadEndpoints:mi,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:p!=null&&f!=null?{header:"User-Agent",value:`${f}/${p}`}:void 0}},Mr=u!=null?Ibd({readme:u,services:ve.services}):void 0,{types:Ei,services:br}=Zbd(Zt),Ii={...Zt,...Y.build(Rt),types:Ei,services:br,sdkConfig:Yt,readmeConfig:Mr};return{...Ii,dynamic:Jbd(Ii)}}function Kl1(e,t,r){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=aqn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:r??!0,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.debug(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:f}=u;a.autogeneratedExamples=[{example:f}]}return e}function Yl1(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;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function Xl1(e,t){if(t==null)return e;let r=Joi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,f])=>{let p=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>igd({filteredIr:t,exampleType:c})).filter(c=>c!==void 0),f.shape.type==="object"){for(let c of f.shape.properties)t.hasProperty(u,c.name.wireValue)&&p.push(c);return[u,{...f,shape:iB.object({...f.shape,properties:p})}]}return[u,f]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let p=f.filter(c=>t.hasWebhook(c)).map(c=>{let o=c.id;return c.payload.type==="inlinedPayload"&&o!=null&&(c.payload={...c.payload,properties:c.payload.properties.filter(l=>t.hasWebhookPayloadProperty(o,l.name.wireValue))}),c});return[u,p]})),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:Joi(e.errors,u=>t.hasError(u)),services:Ih(Joi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(p=>({...p,example:zLu({filteredIr:t,example:p.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(p=>({...p,example:p.example!=null?zLu({filteredIr:t,example:p.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(p=>t.hasQueryParameter(f.id,p.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(p=>t.hasRequestProperty(f.id,p.name.wireValue))}}:f))})),webhookGroups:n,serviceTypeReferenceInfo:Zl1(e.serviceTypeReferenceInfo,t)}}function Zl1(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}}var bgd=bo(R3a(),1),ggd=bo(L3a(),1),S4a=require("fs/promises"),mgd=bo(T6a(),1);function cJt(e){return typeof e.subpackageId=="string"}function NSe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function upi(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var NLu="__package__",IHr=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;#o=new Map;#a=new Map;#l=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return cJt(t)?t.subpackageId:NLu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=A5.SubpackageId(t);return r===NLu?this.api.rootPackage:this.api.subpackages[r]??this.#u.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=A5.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#a.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,n);this.#e.set(f,u);let p=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{p.push(`${o} ${NSe(u.path.parts)}`),p.push(`${o} ${upi(u.path.parts)}`),u.environments.forEach(l=>{p.push(`${o} ${OP(l.baseUrl,NSe(u.path.parts))}`),p.push(`${o} ${OP(l.baseUrl,upi(u.path.parts))}`);let m=ogd(l);m!=null&&(p.push(`${o} ${OP(m,NSe(u.path.parts))}`),p.push(`${o} ${OP(m,upi(u.path.parts))}`))})}),p.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#l.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,n);this.#t.set(f,u);let p=[];["GET","WSS"].forEach(o=>{p.push(`${o} ${NSe(u.path.parts)}`),p.push(`${o} ${upi(u.path.parts)}`),u.environments.forEach(l=>{p.push(`${o} ${OP(l.baseUrl,NSe(u.path.parts))}`),p.push(`${o} ${OP(l.baseUrl,upi(u.path.parts))}`);let m=ogd(l);m!=null&&(p.push(`${o} ${OP(m,NSe(u.path.parts))}`),p.push(`${o} ${OP(m,upi(u.path.parts))}`))})}),p.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.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.#o.set(i,n)}),this.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let i=cJt(t)?[...r,t.name]:r,n=i.length===0?[NLu]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#d(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#l.set(c,u)})}),t.websockets.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering websocket locator: ${c}`),this.#c.set(c,u)})}),t.webhooks.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering webhook locator: ${c}`),this.#s.set(c,u)})}),t.subpackages.forEach(u=>{this.#d(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#l}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#a}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#o.get(t)}static createEndpointId(t,r){return gc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return gc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return gc.WebhookId(`${r}.${t.id}`)}};function ogd(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 hHi=bo(R3a(),1),sgd=bo(L3a(),1);function ugd(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{}}hHi.default.extend(sgd.default);var kl1="Changelog",ef1=["summary","index","overview"],spi=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??kl1,i=[],n;for(let l of this.changelogFiles??[]){let m=Ouu(l.split("/"));if(m==null)continue;let O=ugd(m);if(O==null){let A=m.split(".")[0]?.toLowerCase();A!=null&&ef1.includes(A)&&(n=l);continue}let j=this.toRelativeFilepath(l);i.push({date:O,pageId:gc.PageId(j),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??DL(r)}),u=i.map(l=>{let m=hHi.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:m.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:m.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=FLu(u,l=>l.date,"desc"),p=n!=null?gc.PageId(this.toRelativeFilepath(n)):void 0,c=this.idgen.get(p??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:p,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}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=hHi.default.utc(a.date).year(),f=n.get(u)??[];f.push(a),n.set(u,f)}return FLu(Array.from(n.entries()).map(([a,u])=>{let f=i.append(a.toString()).get(),p=this.idgen.get(`${t}/year/${a}`);return{id:p,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(p,u,i),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=hHi.default.utc(a.date).month()+1,f=n.get(u)??[];f.push(a),n.set(u,f)}return FLu(Array.from(n.entries()).map(([a,u])=>{let f=(0,hHi.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.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}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}};function FLu(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})}var P4a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#o=new Map;#a=[];#l;#c;#s;disableEndpointPairs;constructor(t,r,i,n,a,u,f,p){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=gc.V1.ApiDefinitionId(r.id),this.#e=IHr.create(r,u),this.#s=p,this.#l=this.apiSection.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??DL(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#a=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#a=this.#y(this.#a.map(o=>this.#g(o)),this.#w(this.#e.api.rootPackage,this.#c))}get(){let t=gc.V1.followRedirects(this.#a),r=new spi(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.#c.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0}),children:this.#a,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?IHr.getSubpackageId(r):void 0;return t.map(a=>e3a(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:gc.Url(u.url)}),page:u=>this.#d(u,i),package:u=>this.#v(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#P(u,n,i)})).filter(OM)}#d(t,r){let i=gc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??DL(t.title)});return{id:this.#s.get(i),type:"page",pageId:i,title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let i=t.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(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=IHr.getSubpackageId(a),f=this.#s.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.#o.set(f,[u]);let p=t.slug??(cJt(a)?a.urlSlug:this.apiSection.slug??DL(this.apiSection.title)),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:p}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(cJt(a)?a.displayName??Hdi(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??DL(t.package),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#u(t.contents,void 0,f);return{id:this.#s.get(i??`${this.apiDefinitionId}:${DL(t.package)}`),type:"apiPackage",children:p,title:t.title??t.package,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.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let i=t.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(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(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?IHr.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(OM);this.#o.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 f=t.slug??DL(t.title),p=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,p);return{id:a,type:"apiPackage",children:c,title:t.title,slug:p.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=IHr.getSubpackageId(n),u=this.#s.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.#o.set(u,[a]);let f=cJt(n)?n.urlSlug:"",p=i.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:cJt(n)?n.displayName??Hdi(n.name):this.apiSection.title,slug:p.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}}return this.#P({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},r,i)}#P(t,r,i){let n=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.endpoints.get(A5.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let f=this.#e.getEndpointId(n);if(f==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let p=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:n.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??NSe(n.path.parts),slug:p.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.webSockets.get(A5.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#r.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#r.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??NSe(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:gc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.webhooks.get(A5.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(gc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??OP("/",...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}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(i=>i.type==="apiPackage"?i.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=gc.V1.SlugGenerator.init(t.slug),n=(this.#o.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,n);return{...t,children:u,pointsTo:void 0}}return t}#w(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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??NSe(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned: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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??NSe(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned: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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??Hdi(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})}),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=cJt(a)?r.apply(a):r,f=this.#m(n,u);f.length>0&&i.push({id:gc.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:f,title:cJt(a)?a.displayName??Hdi(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})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),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.#w(i,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>gc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:gc.V1.Url(t.button.href)}:void 0,"limit-websocket-messages-per-connection":t.limitWebsocketMessagesPerConnection!=null?t.limitWebsocketMessagesPerConnection:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],i=new Map;return t.forEach(n=>{if(n.type!=="endpoint"){r.push(n);return}let a=this.#e.endpoints.get(n.endpointId);if(a==null)throw new Error(`Endpoint ${n.endpointId} not found`);let u=`${a.method} ${NSe(a.path.parts)}`,f=i.get(u);if(i.set(u,n),f==null||f.isResponseStream===n.isResponseStream){r.push(n);return}let p=r.indexOf(f),c=n.isResponseStream?n:f,o=n.isResponseStream?f:n,l={id:gc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[p]=l}),r}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}};var cgd=bo(require("crypto"),1);function tf1(e){return cgd.default.createHash("sha256").update(e).digest("hex")}var j4a=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),tf1(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 gc.V1.NodeId(this.#n(t))}};function lgd(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 w4a=bo(u6t(),1);var tD=bo(u6t(),1);var zHr=bo(u6t(),1);function dgd(e){return e._visit({alias:t=>({type:"alias",value:nT(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:ER(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>zHr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:zHr.FernRegistry.PropertyKey(r.name.wireValue),valueType:nT(r.valueType),availability:ER(r.availability)})),extraProperties:nf1(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:zHr.FernRegistry.PropertyKey(i.name.wireValue),valueType:nT(i.valueType),availability:ER(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?ER(i.availability):void 0,additionalProperties:dd.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[zHr.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:zHr.FernRegistry.PropertyKey(n.name.wireValue),valueType:nT(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:nT(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function nT(e){return e._visit({container:t=>dd.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:nT(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:nT(r),valueType:nT(i)}),optional:r=>({type:"optional",itemType:nT(r),defaultValue:void 0}),set:r=>({type:"set",itemType:nT(r)}),literal:r=>dd.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:zHr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:dd.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>if1(t.v2),float:()=>fgd(t.v2),double:()=>fgd(t.v2),string:()=>rf1(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",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 rf1(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function if1(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 fgd(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 nf1(e){return typeof e=="boolean"?wM.unknown():typeof e=="string"?{type:"id",value:zHr.FernRegistry.TypeId(e),default:void 0}:nT(e)}function LLu(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?of1(r,t):[],webhooks:i!=null?af1(i):[],websockets:n!=null?[uf1(n,t)]:[],types:e.types.map(a=>tD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>tD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?tD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function af1(e){return e.map(t=>({description:t.docs??void 0,id:tD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Xmn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:nT(r.valueType),availability:ER(r.availability)})),payload:hf1(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function of1(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0&&n!=null)a.push(...i.userSpecifiedExamples.map(f=>RLu({autogeneratedExample:n,userSpecifiedExample:f,irEndpoint:i,ir:t})));else if(n!=null)a.push(RLu({autogeneratedExample:n,irEndpoint:i,ir:t}));else if(i.response?.body?.type==="fileDownload"){let f=aqn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let p={...RLu({autogeneratedExample:f,irEndpoint:i,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(p)}}let u={availability:ER(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:ff1(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?tD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?sf1({environmentsConfig:t.environments,endpoint:i}):void 0,id:tD.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Xmn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(f=>({description:f.docs??void 0,key:tD.FernRegistry.PropertyKey(f.name.originalName),type:nT(f.valueType),availability:void 0})),parts:[...yHi(i.basePath),...yHi(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(f=>({description:f.docs??void 0,key:tD.FernRegistry.PropertyKey(f.name.originalName),type:nT(f.valueType),availability:void 0})),parts:[...t.basePath!=null?yHi(t.basePath):[],...yHi(e.basePath),...yHi(i.path)]},queryParameters:i.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:nT(f.valueType),availability:ER(f.availability)})),headers:[...e.headers,...i.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:nT(f.valueType),availability:ER(f.availability)})),request:i.requestBody!=null?df1(i.requestBody):void 0,response:i.response!=null?pf1(i.response):void 0,errors:void 0,errorsV2:_f1(i.errors,t),examples:a};r.push(u)}return r}function uf1(e,t){return{auth:e.auth,availability:ER(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?tD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?cf1({environmentsConfig:t.environments,channel:e}):[],id:tD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Xmn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:tD.FernRegistry.PropertyKey(r.name.originalName),type:nT(r.valueType),availability:void 0})),parts:yHi(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:nT(r.valueType),description:r.docs,availability:ER(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:nT(r.valueType),availability:ER(r.availability)})),messages:e.messages.map(r=>({type:tD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:yf1(r.body),description:r.docs,availability:ER(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[tD.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:tD.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function ER(e){if(e!=null)switch(e.status){case"DEPRECATED":return tD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return tD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return tD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return tD.FernRegistry.Availability.Beta;default:sc(e.status)}}function sf1({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:tD.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:tD.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:sc(r)}}function cf1({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:tD.FernRegistry.EnvironmentId(i.id),baseUrl:lf1(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:sc(r)}}function lf1(e,t){return e.replace(/^[^:]+/,t)}function ff1(e){return dd.http.HttpMethod._visit(e,{get:()=>tD.FernRegistry.HttpMethod.Get,post:()=>tD.FernRegistry.HttpMethod.Post,put:()=>tD.FernRegistry.HttpMethod.Put,patch:()=>tD.FernRegistry.HttpMethod.Patch,delete:()=>tD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function yHi(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:tD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function df1(e){let t=dd.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??WI.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>tD.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:tD.FernRegistry.PropertyKey(i.name.wireValue),valueType:nT(i.valueType),availability:ER(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??WI.APPLICATION_JSON,shape:{type:"reference",value:nT(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:tD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:tD.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:tD.FernRegistry.PropertyKey(n.name.wireValue),valueType:nT(n.valueType),contentType:n.contentType,description:n.docs,availability:ER(n.availability)}),_other:()=>{}})).filter(OM)},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 pf1(e){if(e.body==null)return;let t,r=dd.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:nT(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:nT(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:nT(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function _f1(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:nT(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:tD.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:tD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:nT(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 RLu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(f=>{let p=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(p!=null)return{name:f.name,value:{jsonExample:p,shape:dd.ExampleTypeReferenceShape.primitive(dd.ExamplePrimitive.string({original:p}))}}}).filter(OM),a=e?.example??t.example,{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((f,p)=>(f[tD.FernRegistry.PropertyKey(p.name.originalName)]=p.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,p)=>(f[p.name.wireValue]=p.value.jsonExample,f),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((f,p)=>(f[p.name.wireValue]=p.value.jsonExample,f),{}),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:f=>{if(a.request==null)return;let p={};if(UD(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let m=c[l.key.wireValue];if(l.type==="file")p[l.key.wireValue]={type:"filename",value:typeof m=="string"?m:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(m)?m:[m]).filter(j=>typeof j=="string");p[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{p[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:I7t})}return{type:"form",value:p}},bytes:()=>{},_other:()=>{}}),responseStatusCode:dd.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:p=>p!=null?200:204,stream:p=>p.length>0?200:204,sse:p=>p.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let p=i.errors[f.errorId];if(p==null)throw new Error("Cannot find error "+f.errorId);return p.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:p=>p?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:p=>p!=null?{type:"json",value:p.jsonExample}:void 0,stream:p=>({type:"stream",value:p.map(c=>c.jsonExample)}),sse:p=>({type:"sse",value:p.map(({event:c,data:o})=>({event:c,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:f=>f.body!=null?{type:"json",value:f.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(f=>eSe._visit(f,{language:p=>({language:p.language,code:p.code,name:p.name?.originalName,description:p.docs??void 0,install:p.install}),sdk:p=>({language:p.sdk,code:p.code,name:p.name?.originalName,description:p.docs??void 0,install:void 0}),_other:()=>{}})).filter(OM)}}function hf1(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>tD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:tD.FernRegistry.PropertyKey(t.name.wireValue),valueType:nT(t.valueType),availability:ER(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:nT(e.payloadType)},description:e.docs};default:sc(e)}}function yf1(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>tD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:tD.FernRegistry.PropertyKey(t.name.wireValue),valueType:nT(t.valueType),availability:ER(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:nT(e.bodyType)};default:sc(e)}}var ULu=bo(u6t(),1);function pgd(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:ULu.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:ULu.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:sc(i)}}function FSe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:LLu(e.rootPackage,e),auth:pgd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:ER(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:nT(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[w4a.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:dgd(a.shape),availability:ER(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[w4a.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:w4a.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...LLu(a,e)}}return i}var VLu=bo(u6t(),1);var _gd=require("fs"),D4a=class{parse({absoluteFilePath:t}){let r=(0,_gd.readFileSync)(t,"utf-8"),i=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),n=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:i?.[1],packageName:n?.[1],serviceName:a?.[1]}}};var M5=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}resolveSourceOrThrow({source:t,relativeFilepath:r}){let i=this.resolveSource({source:t});if(i==null){if(fci(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r}`)}return i}resolveSource({source:t}){return fci(t)?this.resolveProtobufSource({source:t}):this.resolveOpenAPISource({source:t})}resolveProtobufSource({source:t}){let r=Sf(this.workspace.absoluteFilePath,Pc.of(t.proto));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Vua(r))return;let n=new D4a().parse({absoluteFilePath:r}),a={type:"protobuf",absoluteFilePath:r,relativeFilePath:Pc.of(t.proto),csharpNamespace:n.csharpNamespace,packageName:n.packageName,serviceName:n.serviceName};return this.sourceCache.set(r,a),a}resolveOpenAPISource({source:t}){let r=Sf(this.workspace.absoluteFilePath,Pc.of(t.openapi));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Vua(r))return;let i={type:"openapi",absoluteFilePath:r,relativeFilePath:Pc.of(t.openapi)};return this.sourceCache.set(r,i),i}};async function WLu({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let f=LH({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new M5(r,t)}),p=Oci({token:i.value}),c=FSe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await p.api.v1.register.registerApiDefinition({orgId:VLu.FernRegistry.OrgId(e),apiId:VLu.FernRegistry.ApiId(f.apiName.originalName),definition:c});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:f};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 vf1=new Kdi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function hgd(e,t,r){return TTn(ETn(FSe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),A5.ApiDefinitionId(t),vf1))}function ygd(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}function NIr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}bgd.default.extend(ggd.default);var bf1=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),vgd=0,gf1=async({ir:e})=>(vgd++,`${e.apiName.snakeCase.unsafeName}-${vgd}`),FIr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,i,n,a,u=bf1,f=gf1){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=i,this.taskContext=n,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=j4a.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await ohu({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(p=>{p.changelog?.files.forEach(c=>{let o=GI(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=await JRu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(p),context:this.taskContext});for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=await QRu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(p),context:this.taskContext});let t=ygd(this.parsedDocsConfig);for(let[p,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=mTn(c,{absolutePathToMdx:this.resolveFilepath(p),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Pc.of(p)]=l;for(let m of o)t.add(m)}let r=Array.from(t).map(p=>({absoluteFilePath:p,relativeFilePath:this.toRelativeFilepath(p)}));(await this.uploadFiles(r)).forEach(p=>{this.collectedFileIds.set(p.absoluteFilePath,p.fileId)});let n=this.getDocsBasePath();for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=HRu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,OP(n,l)])),{absolutePathToMdx:this.resolveFilepath(p),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([p,c])=>{let o=mf1(this.editThisPage,p);a[I3t.PageId(p)]={markdown:c,editThisPageUrl:o?I3t.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let p=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=ZM(this.docsWorkspace.absoluteFilePath,c);(await(0,S4a.stat)(o)).isDirectory()?(await oCe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{p.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&p.add(o)})),f=Object.fromEntries(await Promise.all([...p].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,S4a.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return ZM(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,mgd.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}getDocsBasePath(){return new URL(NIr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?I3t.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:I3t.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:I3t.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:void 0,ga4: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")}async toRootNode(){let t=gc.V1.SlugGenerator.init(gc.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=>gc.RoleId(n))}}async toRootChild(t){return q6i(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=gc.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??DL(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0}}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??DL(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:gc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?Of1(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}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(n,f,i))),u=[];return a.forEach(f=>{if(f.type==="apiReference"){u.push(f);return}if(f.type==="section"&&!f.collapsed){u.push(f);return}let p=u.length>0?u[u.length-1]:void 0,c;p?.type==="sidebarGroup"?c=p:(c={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(c)),c.children.push(f)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i){return q6i(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){let i=this.getFernWorkspaceForApiSection(t),n=lgd(t.snippetsConfiguration),a=LH({workspace:i,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new M5(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=hgd(a,u,{oauth:t.playground?.oauth});return new P4a(t,f,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new spi(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:gc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=gc.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??DL(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?gc.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),f=i.apply({urlSlug:r.slug??DL(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.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(p=>this.toNavigationChild(u,p,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}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 q6i(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 spi(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:gc.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??DL(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)}}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):I3t.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(OM),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:I3t.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 q6i(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:I3t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function mf1(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${NIr(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function Of1(e){switch(e){case"beta":return gc.V1.NavigationV1Availability.Beta;case"deprecated":return gc.V1.NavigationV1Availability.Deprecated;case"ga":return gc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return gc.V1.NavigationV1Availability.Stable;default:sc(e)}}var MCd=bo(Sgd(),1),pJu=bo(UUu(),1),TCd=bo(require("http"),1),C8a=bo(require("path"),1);var Xjd=require("events"),uFa=bo(require("fs"),1),vpi=bo(require("path"),1);var xjd=bo(require("os"),1),Bjd=300,VHr=20,Eqn=1e7,Ijd=xjd.default.platform();var nb1=Ijd==="darwin",VUu=Ijd==="win32",WHr=nb1||VUu,zjd=3e3,Njd=2e4,WUu=1250;var pJt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(pJt||(pJt={}));var ypi;(function(e){e.CHANGE="change",e.RENAME="rename"})(ypi||(ypi={}));var Aqn;(function(e){e.CHANGE="change",e.ERROR="error"})(Aqn||(Aqn={}));var vm;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(vm||(vm={}));var hk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(hk||(hk={}));var ab1=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,p=0,c=0,o=()=>{let N=Date.now(),U=N-p,k=N-c,ve=U>=t||k>=a;return[N,ve]},l=N=>{if(c=N,!u)return;let U=u;u=void 0,e.apply(void 0,U)},m=()=>{z(0)},O=()=>{f&&(m(),l(Date.now()))},j=N=>{if(c=N,i)return l(N)},A=N=>{if(n&&u)return l(N);u=void 0},T=()=>{f=void 0;let[N,U]=o();return U?A(N):B(N)},B=N=>{let U=N-p,k=N-c,ve=t-U,Y=a-k,X=Math.min(ve,Y);return z(X)},z=N=>{f&&clearTimeout(f),!(N<=0)&&(f=setTimeout(T,N))},C=(...N)=>{let[U,k]=o(),ve=!!f;if(u=N,p=U,(k||!f)&&z(t),k)return ve?l(U):j(U)};return C.cancel=m,C.flush=O,C},iFa=ab1;var $Uu=bo(require("fs"),1),aFa=bo(require("path"),1);var aT=bo(require("fs"),1),UH=require("util");var RIr=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},_Jt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var HUu=bo(require("process"),1),Fjd=HUu.default.getuid?!HUu.default.getuid():!1,Rjd=1e4,Pae=()=>{};var Mqn={isChangeErrorOk:e=>{if(!Mqn.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Fjd&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!Mqn.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!Mqn.isNodeError(e))throw e;if(!Mqn.isChangeErrorOk(e))throw e}},E4=Mqn;var JUu=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Rjd,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Ljd=new JUu;var LIr=(e,t)=>function(i){return function n(...a){return Ljd.schedule().then(u=>{let f=c=>(u(),c),p=c=>{if(u(),Date.now()>=i)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(m=>setTimeout(m,o)).then(()=>n.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,p)})}},UIr=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var ob1={attempt:{chmod:RIr((0,UH.promisify)(aT.default.chmod),E4.onChangeError),chown:RIr((0,UH.promisify)(aT.default.chown),E4.onChangeError),close:RIr((0,UH.promisify)(aT.default.close),Pae),fsync:RIr((0,UH.promisify)(aT.default.fsync),Pae),mkdir:RIr((0,UH.promisify)(aT.default.mkdir),Pae),realpath:RIr((0,UH.promisify)(aT.default.realpath),Pae),stat:RIr((0,UH.promisify)(aT.default.stat),Pae),unlink:RIr((0,UH.promisify)(aT.default.unlink),Pae),chmodSync:_Jt(aT.default.chmodSync,E4.onChangeError),chownSync:_Jt(aT.default.chownSync,E4.onChangeError),closeSync:_Jt(aT.default.closeSync,Pae),existsSync:_Jt(aT.default.existsSync,Pae),fsyncSync:_Jt(aT.default.fsync,Pae),mkdirSync:_Jt(aT.default.mkdirSync,Pae),realpathSync:_Jt(aT.default.realpathSync,Pae),statSync:_Jt(aT.default.statSync,Pae),unlinkSync:_Jt(aT.default.unlinkSync,Pae)},retry:{close:LIr((0,UH.promisify)(aT.default.close),E4.isRetriableError),fsync:LIr((0,UH.promisify)(aT.default.fsync),E4.isRetriableError),open:LIr((0,UH.promisify)(aT.default.open),E4.isRetriableError),readFile:LIr((0,UH.promisify)(aT.default.readFile),E4.isRetriableError),rename:LIr((0,UH.promisify)(aT.default.rename),E4.isRetriableError),stat:LIr((0,UH.promisify)(aT.default.stat),E4.isRetriableError),write:LIr((0,UH.promisify)(aT.default.write),E4.isRetriableError),writeFile:LIr((0,UH.promisify)(aT.default.writeFile),E4.isRetriableError),closeSync:UIr(aT.default.closeSync,E4.isRetriableError),fsyncSync:UIr(aT.default.fsyncSync,E4.isRetriableError),openSync:UIr(aT.default.openSync,E4.isRetriableError),readFileSync:UIr(aT.default.readFileSync,E4.isRetriableError),renameSync:UIr(aT.default.renameSync,E4.isRetriableError),statSync:UIr(aT.default.statSync,E4.isRetriableError),writeSync:UIr(aT.default.writeSync,E4.isRetriableError),writeFileSync:UIr(aT.default.writeFileSync,E4.isRetriableError)}},Ujd=ob1;var nFa=bo(require("fs"),1),Tqn=bo(require("path"),1);var Vjd={then:e=>{e()}};var QUu=()=>{};var GUu=()=>{let e=QUu,t=QUu,r=!1,i=!1;return{promise:new Promise((p,c)=>{e=o=>(r=!0,p(o)),t=o=>(i=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}};GUu.wrap=async e=>{let t=GUu();return await e(t),t.promise};var Wjd=GUu;var Hjd=e=>Array.isArray(e)?e:[e],Jjd=e=>typeof e=="function",Qjd=()=>{let{promise:e,resolve:t}=Wjd(),r=0,i=()=>{r+=1},n=()=>{r-=1,!r&&t()};return(()=>{i(),queueMicrotask(n)})(),{promise:e,increment:i,decrement:n}};var ub1=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Hjd(a).map(Yt=>Jjd(Yt)?Yt:Mr=>Yt.test(Mr)),f=Yt=>u.some(Mr=>Mr(Yt)),p=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,m={},O=[],j=new Set,A={},T=[],B=new Set,z={},C={},N=new Set,U={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},k={directories:o,directoriesNames:l,directoriesNamesToPaths:m,files:O,filesNames:j,filesNamesToPaths:A,symlinks:T,symlinksNames:B,symlinksNamesToPaths:z,map:C},{promise:ve,increment:Y,decrement:X}=Qjd(),Ae=0,pt=(Yt,Mr,Ei,br)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.directories.push(Mr),Yt.directoriesNames.add(Ei),o.push(Mr),l.add(Ei),m.propertyIsEnumerable(Ei)||(m[Ei]=[]),m[Ei].push(Mr),N.add(Mr),!(br>=i)&&(Ae>=n||sr(Mr,br+1)))},ct=(Yt,Mr,Ei)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.files.push(Mr),Yt.filesNames.add(Ei),O.push(Mr),j.add(Ei),A.propertyIsEnumerable(Ei)||(A[Ei]=[]),A[Ei].push(Mr),N.add(Mr))},Dt=(Yt,Mr,Ei,br)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.symlinks.push(Mr),Yt.symlinksNames.add(Ei),T.push(Mr),B.add(Ei),z.propertyIsEnumerable(Ei)||(z[Ei]=[]),z[Ei].push(Mr),N.add(Mr),r&&(br>=i||Ae>=n||Wr(Mr,br+1)))},Rt=(Yt,Mr,Ei,br,Ii)=>{p.aborted||f(Mr)||(br.isDirectory()?pt(Yt,Mr,Ei,Ii):br.isFile()?ct(Yt,Mr,Ei):br.isSymbolicLink()&&Dt(Yt,Mr,Ei,Ii))},Zt=(Yt,Mr,Ei,br)=>{if(p.aborted)return;let Ii=Mr===Tqn.default.sep?"":Tqn.default.sep,pi=Ei.name,Ft=`${Mr}${Ii}${pi}`;f(Ft)||(Ei.isDirectory()?pt(Yt,Ft,pi,br):Ei.isFile()?ct(Yt,Ft,pi):Ei.isSymbolicLink()&&Dt(Yt,Ft,pi,br))},Vt=(Yt,Mr,Ei,br)=>{for(let Ii=0,pi=Ei.length;Ii<pi;Ii++)Zt(Yt,Mr,Ei[Ii],br)},sr=(Yt,Mr)=>{p.aborted||Mr>i||Ae>=n||(Y(),nFa.default.readdir(Yt,{withFileTypes:!0},(Ei,br)=>{if(Ei||p.aborted||!br.length)return X();(c(br)||Vjd).then(()=>{let pi=C[Yt]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Vt(pi,Yt,br,Mr),X()})}))},Wr=async(Yt,Mr)=>{Y(),nFa.default.realpath(Yt,(Ei,br)=>{if(Ei||p.aborted)return X();nFa.default.stat(br,async(Ii,pi)=>{if(Ii||p.aborted)return X();let Ft=Tqn.default.basename(br),Xt=C[Yt]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Rt(Xt,br,Ft,pi,Mr),X()})})};return(async(Yt,Mr=1)=>(Yt=Tqn.default.normalize(Yt),N.add(Yt),sr(Yt,Mr),await ve,p.aborted?U:k))(e)},Gjd=ub1;var hJt={lang:{debounce:iFa,attempt:e=>{try{return e()}catch(t){return hJt.lang.castError(t)}},castArray:e=>hJt.lang.isArray(e)?e:[e],castError:e=>hJt.lang.isError(e)?e:hJt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(hJt.lang.isNaN(e))return hJt.lang.isNaN(t);if(hJt.lang.isPrimitive(e)||hJt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(aFa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?$Uu.default.realpathSync.native(e):$Uu.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===aFa.default.sep&&t.length-e.length>aFa.default.sep.length,poll:(e,t=Njd)=>Ujd.retry.stat(t)(e,{bigint:!0}).catch(hJt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await Gjd(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},Jj=hJt;var oFa=bo(require("path"),1);var KUu=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Jj.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Bjd){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(f,p)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...p]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=Jj.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(f,p="",c=!1)=>{c?await this.eventsPopulate([p],i,!0):n.add(p),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,f=r[u];return a===f||a===vm.CHANGE&&f===vm.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===vm.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===vm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??VHr:Math.min(1,this.options.depth??VHr),u=this.options.limit??Eqn,[f,p]=await Jj.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...p];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Jj.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(vm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!WHr&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(vm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(vm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(oFa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(vm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(oFa.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(vm.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===vm.ADD?this.onTargetAdd(i):r===vm.ADD_DIR?this.onTargetAddDir(i):r===vm.CHANGE?this.onTargetChange(i):r===vm.UNLINK?this.onTargetUnlink(i):r===vm.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=ypi.CHANGE,r){if(this.watcher.isClosed())return;let i=oFa.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){VUu&&t.code==="EPERM"?this.onWatcherChange(ypi.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(Aqn.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(Aqn.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(ypi.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&WHr&&this.options.native!==!1?this.options.depth??VHr:Math.min(1,this.options.depth??VHr),i=this.options.limit??Eqn,[n,a]=await Jj.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(ypi.CHANGE,f,t)}))}}},$jd=KUu;var yk={interval:100,intervalId:void 0,fns:new Map,init:()=>{yk.intervalId||(yk.intervalId=setInterval(yk.resolve,yk.interval))},reset:()=>{yk.intervalId&&(clearInterval(yk.intervalId),delete yk.intervalId)},add:(e,t)=>{yk.fns.set(e,Date.now()+t),yk.init()},remove:e=>{yk.fns.delete(e)},resolve:()=>{if(!yk.fns.size)return yk.reset();let e=Date.now();for(let[t,r]of yk.fns)r>=e||(yk.remove(t),t())}},qqn=yk;var Cqn=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=WUu){let{ino:i,targetPath:n,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(i||-1,m=>m!==n);if(l&&l!==n){if(Jj.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return f();let p=()=>{u.add.delete(i),qqn.remove(c)},c=()=>{p(),f()};qqn.add(c,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;p();let m=l();n===m?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,m,n)};u.add.set(i,o),o()}getLockUnlink(t,r=WUu){let{ino:i,targetPath:n,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,n)};if(!i)return f();let p=()=>{u.unlink.delete(i),qqn.remove(c)},c=()=>{p(),f()};qqn.add(c,r);let o=()=>(p(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,vm.ADD,pJt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,vm.ADD_DIR,pJt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,vm.UNLINK,pJt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,vm.UNLINK_DIR,pJt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};Cqn.DIR_EVENTS={add:vm.ADD_DIR,rename:vm.RENAME_DIR,unlink:vm.UNLINK_DIR};Cqn.FILE_EVENTS={add:vm.ADD,change:vm.CHANGE,rename:vm.RENAME,unlink:vm.UNLINK};var Kjd=Cqn;var YUu=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Jj.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Jj.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Jj.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Jj.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Jj.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Jj.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},XUu=YUu;var ZUu=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},Yjd=ZUu;var kUu=class{constructor(){this.inos={},this.paths=new XUu,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Jj.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Yjd(i)}reset(){this.inos={},this.paths=new XUu,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,vm.ADD,n),[vm.ADD];if(n.isDirectory())return this.updateIno(t,vm.ADD_DIR,n),[vm.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,vm.UNLINK,i),[vm.UNLINK];if(i.isDirectory())return this.updateIno(t,vm.UNLINK_DIR,i),[vm.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,vm.CHANGE,n),[vm.CHANGE]);if(n.isDirectory())return this.updateIno(t,vm.UNLINK,i),this.updateIno(t,vm.ADD_DIR,n),[vm.UNLINK,vm.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,vm.UNLINK_DIR,i),this.updateIno(t,vm.ADD,n),[vm.UNLINK_DIR,vm.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,vm.UNLINK_DIR,i),this.updateIno(t,vm.ADD_DIR,n),[vm.UNLINK_DIR,vm.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?pJt.FILE:pJt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},eVu=kUu;var tVu=class e extends Xjd.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(hk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(hk.CLOSE,n)),this._readyWait=new Promise(n=>this.on(hk.READY,n)),this._locker=new Kjd(this),this._roots=new Set,this._poller=new eVu,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Jj.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(hk.CLOSE))}error(t){if(this.isClosed())return!1;let r=Jj.lang.castError(t);return this.emit(hk.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(hk.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(hk.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Jj.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Jj.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Jj.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new $jd(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Jj.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(f=>f.handler===i&&(!f.filePath||f.filePath===n)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=vpi.default.dirname(t);for(let f=1;f<1/0;f++){if(this._watchers[u]?.find(o=>(f===1||o.options.recursive&&f<=(o.options.depth??VHr))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&WHr&&o.options.native!==!1)))return!0;if(!WHr)break;let c=vpi.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Jj.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,i,n))try{let p=!r.recursive||WHr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:uFa.default.watch(f,p),handler:i,options:r,folderPath:f,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||f)){let O={...r,ignoreInitial:!0,recursive:!1},j=vpi.default.dirname(f),A=f;await this.watchDirectories([j],O,i,A,l)}}catch(p){this.error(p)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||WHr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??VHr,f=r.limit??Eqn,[p]=await Jj.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,i,n,a);if(p.length){let o=Jj.fs.getDepth(t);for(let l of p){let m=Jj.fs.getDepth(l),O=Math.max(0,u-(m-o)),j={...r,depth:O};await this.watchDirectories([l],j,i,n,a||c)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(c,o)=>{o===t&&(p(),i())},u=new e(a),f=()=>{this._subwatchers.add(n),this.on(hk.CLOSE,p),u.watchFile(t,r,a)},p=()=>{this._subwatchers.delete(n),this.removeListener(hk.CLOSE,p),u.close()};return f()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=vpi.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new eVu,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Jj.lang.noop;if(this.pollerExists(t,r))return Jj.lang.noop;let n={...r,interval:r.pollingInterval??zjd},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(hk.CLOSE,f),uFa.default.watchFile(t,n,i)},f=()=>{this._pollers.delete(a),this.removeListener(hk.CLOSE,f),uFa.default.unwatchFile(t,i)};return Jj.lang.attempt(u),()=>Jj.lang.attempt(f)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Jj.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,p)=>p===u||!Jj.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=vpi.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Jj.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=vpi.default.dirname(t);return(await Jj.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Jj.lang.noop){if(Jj.lang.isFunction(t))return this.watch([],{},t);if(Jj.lang.isUndefined(t))return this.watch([],r,i);if(Jj.lang.isFunction(r))return this.watch(t,{},r);if(Jj.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Jj.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Jj.lang.noop&&this.on(hk.ALL,i),r.readdirMap=void 0,this.ready())}},Zjd=tVu;var vg1=bo(rwd(),1),bg1=bo(dVu(),1),gg1=bo(_Vu(),1),mg1=bo(OVu(),1),jVu=bo(kwd(),1);var wCd=bo(rRa(),1),CJt=require("fs/promises"),T8a=require("os"),sJu=bo(require("path"),1),DCd=bo(Pie(),1),SCd=bo(EAd(),1),cJu=bo(uJu(),1),pA1="etag",lJu="preview",_A1="bundle",fJu=".fern";function hA1(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu))}function q8a(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu),Pc.of(_A1))}function yA1(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu),Pc.of(pA1))}async function ECd({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,cJu.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new SCd.default.Parser().parseStringPromise(n),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],p=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=yA1();if(r){let z=await _h(c),C;if(z&&(t.debug("Reading existing ETag"),C=(await(0,CJt.readFile)(c)).toString()),C!=null&&C===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await DCd.default.dir({prefix:"fern"}),l=f_.of(o.path);t.debug(`Downloading docs preview bundle from ${sJu.default.join(e,p)}`);let m=await(0,cJu.fetcher)({url:`${sJu.default.join(e,p)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!m.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=Sf(l,Pc.of("output.zip")),j=m.body;if(j==null)return{type:"failure"};let A=Buffer.from(j);await(0,CJt.writeFile)(O,A),t.debug(`Wrote output.zip to ${O}`);let T=hA1();await _h(T)&&await(0,CJt.rm)(T,{recursive:!0}),await(0,CJt.mkdir)(T,{recursive:!0}),t.debug(`rm -rf ${T}`);let B=q8a();return await(0,CJt.mkdir)(B,{recursive:!0}),await(0,wCd.default)(O,B),await(0,CJt.writeFile)(c,f),t.debug(`Downloaded bundle to ${B}`),{type:"success"}}async function ACd({domain:e,project:t,context:r}){let i=t.docsWorkspaces,n=t.apiWorkspaces;if(i==null)throw new Error("No docs workspace found in project");let a=await Promise.all(n.map(async m=>await m.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),u=new dJu(r),f={},c=await new FIr(e,i,a,r,void 0,async m=>m.map(O=>{let j=pHt();return f[j]={type:"url",url:gc.Url(`/_local${vcu(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:j}}),async m=>u.addReferencedAPI(m)).resolve(),o=f9u({writeShape:c,files:{}}),l=p9u({dbShape:o.config});return{apis:u.getAPIsForDefinition(),config:l,files:{},filesV2:f,pages:o.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var dJu=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=pHt(),a=ETn(FSe({ir:t,snippetsConfig:r,playgroundConfig:i}),lU.ApiDefinitionId(n),new Kdi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=TTn(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}};var vA1={pages:{},apis:{},files:{},filesV2:{},config:{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 _Ju({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 C="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(C==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await ECd({bucketUrl:C,logger:i.logger,preferCached:!0})}catch(C){let N=q8a();if(C instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${C.message}`),await _h(N))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=qm(e.config._absolutePath),f=(0,pJu.default)(),p=TCd.default.createServer(f),c=new jVu.default({server:p}),o=new Set;function l(C){for(let N of o)N.send(JSON.stringify(C))}c.on("connection",function(N){o.add(N),N.on("close",function(){o.delete(N)})}),f.use((0,MCd.default)());let m=new URL(NIr(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),O=e,j,A=async()=>{i.logger.info("Reloading docs...");let C=Date.now();try{O=await t(),i.logger.info("Validating docs..."),await r(O);let N=await ACd({domain:`${m.host}${m.pathname}`,project:O,context:i});return i.logger.info(`Reload completed in ${Date.now()-C}ms`),N}catch(N){return j==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),N instanceof Error&&(i.logger.error(N.message),N instanceof Error&&N.stack&&i.logger.debug(`Stack Trace:
1976
+ ${JSON.stringify(r)}"`)}}function hbd(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=dbd({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Dxe.grpc({service:a})}function ybd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:p,sourceResolver:c,globalErrors:o,workspace:l}){let m=dHi({pathParameters:r["path-parameters"],location:Sxe.Service,file:i,variableResolver:p}),O=pbd({file:i,serviceDeclaration:r,sourceResolver:c}),j={fernFilepath:i.fernFilepath};return{availability:gae(r.availability),name:j,displayName:r["display-name"]??void 0,basePath:XBe(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([T,B])=>kBe({headerKey:T,header:B,file:i})):[],pathParameters:m,encoding:al1(O,r),transport:O,endpoints:Object.entries(r.endpoints).map(([T,B])=>{let z=dHi({pathParameters:R3t(B),location:Sxe.Endpoint,file:i,variableResolver:p}),C={...V$(B),id:"",name:i.casingsGenerator.generateName(T),displayName:B["display-name"],auth:B.auth??r.auth,idempotent:B.idempotent??r.idempotent??!1,baseUrl:B.url??r.url??e,method:B.method!=null?nl1(B.method):wne.Post,basePath:B["base-path"]!=null?XBe(B["base-path"]):void 0,path:XBe(B.path),fullPath:XBe(B["base-path"]!=null?OP(B["base-path"],B.path):i.rootApiFile["base-path"]!=null?OP(i.rootApiFile["base-path"],r["base-path"],B.path):OP(r["base-path"],B.path)),pathParameters:z,allPathParameters:B["base-path"]!=null?z:[...t,...m,...z],queryParameters:typeof B.request!="string"&&B.request?.["query-parameters"]!=null?Object.entries(B.request["query-parameters"]).map(([N,U])=>c4a({file:i,queryParameterKey:N,queryParameter:U})):[],headers:typeof B.request!="string"&&B.request?.headers!=null?Object.entries(B.request.headers).map(([N,U])=>kBe({headerKey:N,header:U,file:i})):[],requestBody:T0d({request:B.request,file:i}),sdkRequest:I0d({service:r,request:B.request,endpoint:B,endpointKey:T,file:i,typeResolver:a,propertyResolver:u}),response:ubd({endpoint:B,file:i,typeResolver:a}),errors:[...S0d({errors:B.errors,file:i}),...o],userSpecifiedExamples:B.examples!=null?B.examples.map(N=>({example:obd({service:r,endpoint:B,example:N,typeResolver:a,errorResolver:n,exampleResolver:f,variableResolver:p,file:i,workspace:l}),codeSamples:N["code-samples"]?.map(U=>z0d({codeSample:U,file:i}))})):[],autogeneratedExamples:[],pagination:fbd({propertyResolver:u,file:i,endpointName:T,endpointSchema:B}),transport:_bd({file:i,serviceTransport:O,endpointDeclaration:B,sourceResolver:c})};return C.id=FP.generateEndpointId(j,C),C})}}function dHi({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>rl1({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function rl1({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...V$(t),name:i.casingsGenerator.generateName(e),valueType:il1({parameter:t,variableResolver:n,file:i}),location:r,variable:_8i(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function il1({parameter:e,variableResolver:t,file:r}){let i=iqn({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function iqn({parameter:e,variableResolver:t,file:r}){let i=d4a({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function d4a({parameter:e,variableResolver:t,file:r}){if(_8i(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 nl1(e){switch(e){case"GET":return wne.Get;case"POST":return wne.Post;case"PUT":return wne.Put;case"PATCH":return wne.Patch;case"DELETE":return wne.Delete;default:sc(e)}}function kBe({headerKey:e,header:t,file:r}){let{name:i}=sJt({headerKey:e,header:t});return{...V$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function sJt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function al1(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:sc(e)}}var W$={};Gs(W$,{validateObjectExample:()=>ipi,validateTypeExample:()=>u4a,validateTypeReferenceExample:()=>RH});function vbd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function p4a({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function bbd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:FP.generateEndpointIdFromResolvedEndpoint(n),serviceId:FP.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:p4a({fernFilePath:n.file.fernFilepath})?void 0:FP.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 gbd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:FP.generateEndpointIdFromResolvedEndpoint(n),serviceId:FP.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:p4a({fernFilePath:n.file.fernFilepath})?void 0:FP.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},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 mbd({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=gbd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?bbd({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:f}}var nqn={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}},ALu={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 Obd(e){return{endpoint:e["get-token"].endpoint,requestProperties:ol1({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:ul1({responseProperties:e["get-token"]?.["response-properties"]})}}function Pbd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:sl1({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:cl1({responseProperties:e["refresh-token"]?.["response-properties"]})}}function ol1({requestProperties:e}){if(e==null)return nqn.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?N3t(t):nqn.requestProperties.client_id,client_secret:r!=null?N3t(r):nqn.requestProperties.client_secret,scopes:i!=null?N3t(i):nqn.requestProperties.scopes}}function ul1({responseProperties:e}){return jbd({responseProperties:e,defaultValue:nqn.responseProperties})}function sl1({requestProperties:e}){if(e==null)return ALu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?N3t(t):ALu.requestProperties.refresh_token}}function cl1({responseProperties:e}){return jbd({responseProperties:e,defaultValue:ALu.responseProperties})}function jbd({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?BIr(r):t.access_token,expires_in:i!=null?BIr(i):t.expires_in,refresh_token:n!=null?BIr(n):t.refresh_token}}function Abd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:GLr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return wwn(e.auth,{single:a=>{let u=wbd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:GLr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:GLr.Any,schemes:a.map(u=>wbd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function wbd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(f,p)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return Dgu(c,{header:o=>oH.header({docs:p,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>Sbd({file:r,docs:p,rawScheme:o}),bearer:o=>Dbd({file:r,docs:p,rawScheme:o}),oauth:o=>Ebd({file:r,docs:p,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Dbd({file:r,docs:void 0,rawScheme:void 0});case"basic":return Sbd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return Ebd({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Dbd({file:e,docs:t,rawScheme:r}){return oH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Sbd({file:e,docs:t,rawScheme:r}){return oH.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 Ebd({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return oH.oauth({docs:t,configuration:$Lr.clientCredentials(mbd({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Obd(r),refreshTokenEndpoint:Pbd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Mbd({file:e,rawApiFileSchema:t}){if(t.version!=null)return YLr.header({header:ll1({file:e,header:t.version.header}),value:fl1({file:e,versionDeclaration:t.version})})}function ll1({file:e,header:t}){return typeof t=="string"?kBe({file:e,headerKey:t,header:{type:"string"}}):kBe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function fl1({file:e,versionDeclaration:t}){return s4a({_enum:{default:t.default,enum:t.values},file:e})}function Tbd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[f,p]of Object.entries(e.messages??{}))u.push({type:f,availability:gae(p.availability),docs:p.docs,origin:p.origin,body:_l1({body:p.body,file:n}),displayName:p["display-name"]});return{availability:gae(e.availability),path:XBe(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(([f,p])=>kBe({headerKey:f,header:p,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?dHi({pathParameters:e["path-parameters"],location:Sxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([f,p])=>{let{name:c}=zIr({queryParameterKey:f,queryParameter:p}),o=n.parseTypeReference(p);return{...V$(p),name:n.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof p!="string"&&p["allow-multiple"]!=null?p["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let p=yl1({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:f.name!=null?n.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:bl1({channel:e,example:f,pathParams:p}),...p,...vl1({channel:e,example:f,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:f["query-parameters"]!=null?Object.entries(f["query-parameters"]).map(([c,o])=>{let l=e["query-parameters"]?.[c];if(l==null)throw new Error(`Query parameter ${c} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:zIr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:RT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:dl1({queryParameter:l})}}):[],messages:f.messages.map(c=>{let o=e.messages?.[c.type];if(o==null)throw new Error(`Message ${c.type} does not exist`);return{type:c.type,body:pl1({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function dl1({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?h5.exploded():h5.single()}function pl1({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!gl1(e.body))return D6t.reference(RT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!UD(t))throw new Error("Example must be an object");let u=[];for(let[f,p]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:f,property:c}).name,wireValue:f}),value:RT({example:p,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=rqn({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:FH({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:RT({example:p,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 D6t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function _l1({body:e,file:t}){return typeof e=="string"?qne.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):hl1(e)?qne.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):qne.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:z3t(e.extends??[]).map(r=>pU({typeName:r,file:t})),properties:[]})}function hl1(e){return e.type!=null}function yl1({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let f=[],p=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let m=iqn({parameter:o,variableResolver:n,file:a});return{name:c,value:RT({example:l,rawTypeBeingExemplified:m.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:m.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let c=R3t(e);for(let[o,l]of Object.entries(t["path-parameters"])){let m=c[o];if(m!=null)f.push(p({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:m,examplePathParameter:l}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:f}}function vl1({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[f,p]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:sJt({headerKey:f,header:c}).name,wireValue:f}),value:RT({example:p,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function bl1({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 gl1(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function MLu({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:t2r(i,{singleBaseUrl:()=>g6t.singleBaseUrl(ml1({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>g6t.multipleBaseUrls(Ol1({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function ml1({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>t2r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:qbd(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function Ol1({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>t2r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Ih(a.urls,u=>qbd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function qbd(e){return e.endsWith("/")?e.slice(0,-1):e}function Cbd({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let f of t.examples)u.push({name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,docs:f.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:RT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:qHr({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 xbd="content";function Bbd(e,t){if(e==null||e.strategy==="status-code")return j6t.statusCode();switch(e.strategy){case"property":return j6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:xbd,wireValue:xbd})});default:sc(e)}}function Ibd({readme:e,services:t}){let r=new TLu(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 TLu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=jl1({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:Pl1(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function Pl1(e){let t="";e.fullPath.head.length>0&&(t=OP(t,e.fullPath.head));for(let r of e.fullPath.parts)t=OP(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=OP(t,r.tail));return t.startsWith("/")?t:`/${t}`}function jl1({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 zbd({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:FP.generateWebhookId(t.fernFilepath,u),availability:gae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?Object.entries(f.headers).map(([p,c])=>kBe({headerKey:p,header:c,file:t})):[],payload:wl1({payload:f.payload,file:t}),examples:f.examples!=null?Sl1({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function wl1({payload:e,file:t}){return typeof e=="string"?Tne.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):_4a(e)?Tne.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Tne.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:z3t(e.extends).map(r=>pU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>Dl1({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?gae(i.availability):void 0,file:t})):[]})}function Dl1({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:FH({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function Sl1({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:_4a(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:RT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!UD(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:RT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function _4a(e){return e.type!=null}function pHi(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 Nbd({name:e,source:t}){return k1.userDefined({file:f4a({source:t}),name:CHr.generateName(e)})}function Fbd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=El1({type:e.proto.type});if(t!=null)return t}}function El1({type:e}){switch(e){case"google.protobuf.Any":return k1.wellKnown(F_.any());case"google.protobuf.Api":return k1.wellKnown(F_.api());case"google.protobuf.BoolValue":return k1.wellKnown(F_.boolValue());case"google.protobuf.BytesValue":return k1.wellKnown(F_.bytesValue());case"google.protobuf.DoubleValue":return k1.wellKnown(F_.doubleValue());case"google.protobuf.Duration":return k1.wellKnown(F_.duration());case"google.protobuf.Empty":return k1.wellKnown(F_.empty());case"google.protobuf.Enum":return k1.wellKnown(F_.enum());case"google.protobuf.EnumValue":return k1.wellKnown(F_.enumValue());case"google.protobuf.Field":return k1.wellKnown(F_.field());case"google.protobuf.FieldCardinality":return k1.wellKnown(F_.fieldCardinality());case"google.protobuf.FieldKind":return k1.wellKnown(F_.fieldKind());case"google.protobuf.FieldMask":return k1.wellKnown(F_.fieldMask());case"google.protobuf.FloatVlaue":return k1.wellKnown(F_.floatValue());case"google.protobuf.Int32Value":return k1.wellKnown(F_.int32Value());case"google.protobuf.Int64Value":return k1.wellKnown(F_.int64Value());case"google.protobuf.ListValue":return k1.wellKnown(F_.listValue());case"google.protobuf.Method":return k1.wellKnown(F_.method());case"google.protobuf.Mixin":return k1.wellKnown(F_.mixin());case"google.protobuf.NullValue":return k1.wellKnown(F_.nullValue());case"google.protobuf.Option":return k1.wellKnown(F_.option());case"google.protobuf.SourceContext":return k1.wellKnown(F_.sourceContext());case"google.protobuf.StringValue":return k1.wellKnown(F_.stringValue());case"google.protobuf.Struct":return k1.wellKnown(F_.struct());case"google.protobuf.Syntax":return k1.wellKnown(F_.syntax());case"google.protobuf.Timestamp":return k1.wellKnown(F_.timestamp());case"google.protobuf.Type":return k1.wellKnown(F_.type());case"google.protobuf.Uint32Value":return k1.wellKnown(F_.uint32Value());case"google.protobuf.Uint64Value":return k1.wellKnown(F_.uint64Value());case"google.protobuf.Value":return k1.wellKnown(F_.value())}}function Rbd({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=e7(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&YE(a.declaration)){let u=e7(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([p,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=n.arguments?.[u.indexOf(c)]??c),[p,o]});return iB.object({extends:z3t(a.declaration.extends).map(p=>pU({typeName:p,file:t})),properties:YTn({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Lbd({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return wxe(i)?Rbd({generic:i,file:t,typeResolver:r}):iB.alias({aliasOf:t.parseTypeReference(e),resolvedType:Al1({aliasOf:i,file:t,typeResolver:r})})}function Al1({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return sH.primitive(i.originalTypeReference.primitive);case"container":return sH.container(i.originalTypeReference.container);case"unknown":return sH.unknown();case"named":{let n=YE(i.declaration)?w6t.Object:uUr(i.declaration)?w6t.Union:A6t(i.declaration)?w6t.Enum:h8i(i.declaration)?w6t.UndiscriminatedUnion:sc(i.declaration);return sH.named({name:i.name,shape:n})}}}function Ubd({union:e,file:t}){return iB.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function Vbd(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 CLu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new qLu}){let n=f4(e,{alias:u=>{let f=typeof u=="string"?u:u.type,p=e7(f);if(p!=null){let c=new Set(p.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=e7(o.typeName)?.arguments;if(YE(o.declaration)){let m=Vbd(o.declaration);l&&m.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>Vbd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(p=>typeof p=="string"?p:p.type)),f.push(...Object.values(u.union).reduce((p,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&p.push(o),p},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,p)=>{let c=typeof p=="string"?p:p.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of n){let f=l$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:p,valueType:c})=>[...p,...c],list:p=>p,optional:p=>p,set:p=>p,named:p=>[p],literal:()=>[],unknown:()=>[]}});for(let p of f){let c=pU({typeName:p,file:t});if(!i.hasTypeNameBeenSeen(c)){i.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:p,file:t});if(wxe(o.typeName))continue;a.push(...CLu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var qLu=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 Wbd({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let f=V$(t),p=pU({typeName:e,file:r}),c=CLu({typeDeclaration:t,file:r,typeResolver:i}),o={};YE(t)&&(o=pHi(t.properties??{}));let l=Tl1({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:Bl1(t),name:p,shape:Ml1({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(c.map(m=>m.typeId)),encoding:ql1({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(m=>({name:m.name!=null?r.casingsGenerator.generateName(m.name):void 0,docs:m.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:m.value,file:r}).resolvedExample,shape:ELu({typeName:p,example:m.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(m=>m.fernFilepath))}}function Ml1({typeDeclaration:e,file:t,typeResolver:r}){return f4(e,{alias:i=>Lbd({alias:i,file:t,typeResolver:r}),object:i=>A0d({object:i,file:t}),discriminatedUnion:i=>W0d({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>Ubd({union:i,file:t}),enum:i=>iB.enum(s4a({_enum:i,file:t}))})}function Tl1({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=Fbd({encoding:t.encoding});if(a!=null)return kBr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return kBr.proto(Nbd({source:n,name:r}))}function ql1({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?Cl1(e.encoding):xl1(t)}function Cl1(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function xl1(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Bl1(e){if(typeof e!="string"&&"inline"in e)return e.inline}var Hbd="1.0.0";var h4a=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:Hbd,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:qd.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return qd.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 qd.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:sc(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return qd.ReferencedRequestBodyType.bytes();case"typeReference":return qd.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:sc(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return qd.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 qd.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return qd.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:qd.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return qd.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:qd.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:sc(r)}}convertFileUploadRequestBody({properties:t}){return qd.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 qd.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:sc(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return qd.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return qd.FileUploadRequestBodyProperty.fileArray(t.key);default:sc(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=qd.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:sc(t)}}convertContainerType(t){switch(t.type){case"list":return qd.TypeReference.list(this.convertTypeReference(t.list));case"map":return qd.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return qd.TypeReference.optional(this.convertTypeReference(t.optional));case"set":return qd.TypeReference.set(this.convertTypeReference(t.set));case"literal":return qd.TypeReference.literal(this.convertLiteral(t.literal));default:sc(t)}}convertNamedType(t){return qd.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:sc(t.shape)}}convertAlias({declaration:t,alias:r}){return qd.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return qd.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 qd.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return qd.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:sc(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return qd.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return qd.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 qd.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return qd.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return qd.LiteralType.boolean(t.boolean);case"string":return qd.LiteralType.string(t.string);default:sc(t)}}convertPrimitiveType(t){return qd.TypeReference.primitive(t.v1)}convertUnknownType(){return qd.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return qd.Auth.basic(r);case"bearer":return qd.Auth.bearer(r);case"header":return qd.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:sc(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=OP(r,t.fullPath.head));for(let i of t.fullPath.parts)r=OP(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=OP(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function Jbd(e){return new h4a(e).convert()}function Gbd({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return Fl1({fieldName:e,validation:Il1(t.v2)});case"BASE_64":return{type:"success",example:$y.base64(bP.BASE64),jsonExample:bP.BASE64};case"BOOLEAN":return{type:"success",example:$y.boolean(bP.BOOLEAN),jsonExample:bP.BOOLEAN};case"DATE":return{type:"success",example:$y.date(bP.DATE),jsonExample:bP.DATE};case"DATE_TIME":return{type:"success",example:$y.datetime({datetime:new Date(bP.DATE_TIME),raw:bP.DATE_TIME}),jsonExample:bP.DATE_TIME};case"DOUBLE":return Rl1({fieldName:e,validation:zl1(t.v2)});case"FLOAT":return{type:"success",example:$y.float(bP.FLOAT),jsonExample:bP.FLOAT};case"INTEGER":return Ll1({fieldName:e,validation:Nl1(t.v2)});case"UINT_64":return{type:"success",example:$y.uint64(bP.INT64),jsonExample:bP.INT64};case"UINT":return{type:"success",example:$y.uint(bP.UINT),jsonExample:bP.UINT};case"BIG_INTEGER":return{type:"success",example:$y.bigInteger(bP.INT64.toString()),jsonExample:`${bP.INT64}`};case"LONG":return{type:"success",example:$y.long(bP.INT64),jsonExample:bP.INT64};case"UUID":return{type:"success",example:$y.uuid(bP.UUID),jsonExample:bP.UUID};default:sc(t.v1)}}function Il1(e){if(e?.type==="string")return e.validation}function zl1(e){if(e?.type==="double")return e.validation}function Nl1(e){if(e?.type==="integer")return e.validation}function Qbd(e){if(e<=bP.SAMPLE_STRINGS.length){let t=bP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return bP.SAMPLE_STRINGS[bP.SAMPLE_STRINGS.length-1]+".".repeat(e-bP.SAMPLE_STRINGS.length)}function Fl1({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=Qbd(i);return{type:"success",example:$y.string({original:a}),jsonExample:a}}else if(n){let a=Qbd(n);return{type:"success",example:$y.string({original:a}),jsonExample:a}}}let r=e??bP.STRING;return{type:"success",example:$y.string({original:r}),jsonExample:r}}function Rl1({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$y.double(r),jsonExample:r};if(i)return{type:"success",example:$y.double(i),jsonExample:i}}return{type:"success",example:$y.double(bP.DOUBLE),jsonExample:bP.DOUBLE}}function Ll1({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:$y.integer(r),jsonExample:r};if(i)return{type:"success",example:$y.integer(i),jsonExample:i}}return{type:"success",example:$y.integer(bP.INT),jsonExample:bP.INT}}function $bd({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return BHr({containerType:t});switch(t.type){case"list":{let u=sz({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:KE.literal({literal:t.literal._visit({boolean:u=>$y.boolean(u),string:u=>$y.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 BHr({containerType:t});let u=sz({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=sz({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=sz({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),f=sz({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?BHr({containerType:t}):{type:"success",example:KE.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:sc(t)}}function BHr({containerType:e}){switch(e.type){case"list":return{type:"success",example:KE.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:KE.literal({literal:e.literal._visit({boolean:t=>$y.boolean(t),string:t=>$y.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:KE.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:KE.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:KE.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:sc(e)}}function _Hi({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 Ybd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=sz({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:p}=u;return{type:"success",example:WD.alias({value:f}),jsonExample:p}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:WD.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=Kbd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:p}=u;return{type:"success",example:WD.object(f),jsonExample:p}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let p=sz({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(p.type==="failure"){++u;continue}let{example:c,jsonExample:o}=p;return{type:"success",example:WD.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let p=f.shape._visit({noProperties:()=>({type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue}}),samePropertiesAsObject:c=>{let o=t[c.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${c.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let l=Kbd({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:m,jsonExample:O}=l;return{type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.samePropertiesAsObject({typeId:o.name.typeId,object:m})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=sz({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:m}=o;return{type:"success",example:WD.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:s4.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:m}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(p.type!=="failure")return p}}}return{type:"failure",message:"Failed to generate example for type reference"}}function Kbd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let f={},p=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=sz({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!_Hi({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:m}=o;p.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=m}return{type:"success",example:WD.object({properties:p}),jsonExample:f}}function sz({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 f=Ybd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:p,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:Wm.named({shape:p,typeName:u.name})},jsonExample:c}}case"container":{let u=$bd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=BHr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Wm.container(c)},jsonExample:o}}let{example:f,jsonExample:p}=u;return{type:"success",example:{jsonExample:p,shape:Wm.container(f)},jsonExample:p}}case"primitive":{let{jsonExample:u,example:f}=Gbd({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Wm.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Wm.unknown(u)},jsonExample:u}}}}var xLu=wM.primitive({v1:lO.String,v2:JS.string({default:void 0,validation:void 0})});function aqn({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:Ox.ok(XB.body(void 0)),docs:void 0},f=[{params:t.pathParameters,add:c=>u.endpointPathParameters.push(c)},{params:r.pathParameters,add:c=>u.servicePathParameters.push(c)},{params:e.pathParameters,add:c=>u.rootPathParameters.push(c)}];for(let c of f)for(let o of c.params){let l=sz({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(l.type==="failure")return l;let{example:m}=l;c.add({name:o.name,value:m})}for(let c of t.queryParameters){if(n&&_Hi({typeDeclarations:i,typeReference:c.valueType}))continue;let o=sz({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:c.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?h5.exploded():h5.single(),value:l})}let p=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of p)for(let o of c.params){if(n&&_Hi({typeDeclarations:i,typeReference:o.valueType}))continue;let l=sz({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(l.type==="failure")return l;let{example:m}=l;c.add({name:o.name,value:m})}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 c={},o=[];for(let l of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let m=sz({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(m.type==="failure"&&!_Hi({typeDeclarations:i,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${m.message}`};if(m.type==="failure")continue;let{example:O,jsonExample:j}=m;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=j}u.request=o$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:o}=c;u.request=o$.reference(o);break}default:sc(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 c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"streamParameter":{let c;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":c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1});break;default:sc(t.response.body.nonStreamResponse)}if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"streaming":{let c;switch(t.response.body.value.type){case"sse":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.sse([{data:{...o,jsonExample:l},event:""}]));break}case"json":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.stream([{...o,jsonExample:l}]));break}case"text":{if(c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1}),c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.stream([{...o,jsonExample:l}]));break}default:sc(t.response.body.value)}break}case"text":{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:xLu,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=Ox.ok(XB.body({...o,jsonExample:l}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:sc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Ox.error({body:void 0,error:a.declaration.name});else{let c=sz({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:o}=c;u.response=Ox.error({body:o,error:a.declaration.name})}try{return{type:"success",example:{id:l4a(u),url:Ul1(t,u),...u},jsonExample:void 0}}catch(c){return{type:"failure",message:`Parse failure with exceptions ${c}`}}}function Ul1(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 Xbd(e,t){let r=t[e];if(r==null)throw new pBr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Zbd(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,Wl1({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>Vl1({endpoint:i,ir:e}))}]))}}function Vl1({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>kbd(r,t))}}}function Wl1({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>kbd(r,t))}}}return e}function kbd(e,t){let r=BLu(e.typeId,t);return egd({objectTypeDeclaration:r,ir:t})}function BLu(e,t){let r=Xbd(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return BLu(r.shape.resolvedType.name.typeId,t)}throw new pBr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function egd({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=BLu(i.typeId,t);return egd({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}var y4a=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:f,subpackages:p,queryParameters:c,requestProperties:o,webhookPayloadProperties:l,channels:m}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=p,this.requestProperties=o,this.queryParameters=c,this.channels=m}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=FP.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=FP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=FP.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 b4a=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=Hl1(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=FP.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=FP.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=FP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&G6(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=FP.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,p=new Set;for(let c of[...t.headers,...r.headers])G6(c.valueType,u,p);for(let c of[...t.pathParameters,...r.pathParameters])G6(c.valueType,u,p);for(let c of r.queryParameters)G6(c.valueType,u,p);if(i!=null&&i.request!=null&&typeof i.request!="string"){let c=pHi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&cR._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)v4a(o,u,p);for(let o of c.properties)G6(o.valueType,u,p);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&YB(i.request.body)){let o=pHi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{G6(c,u,p)},fileUpload:({properties:c})=>{for(let o of c)Dne._visit(o,{file:Mc,bodyProperty:({valueType:l})=>{G6(l,u,p)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&T2._visit(r.response.body,{fileDownload:Mc,json:c=>{G6(c.responseBodyType,u,p)},streaming:c=>{c._visit({sse:o=>G6(o.payload,u,p),json:o=>G6(o.payload,u,p),text:Mc,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>G6(o.payload,u,p),json:o=>G6(o.payload,u,p),text:Mc,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&G6(c.nonStreamResponse.value.responseBodyType,u,p)},text:Mc,bytes:Mc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(FP.generateErrorId(c.error)),p.add(c.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:f,referencedSubpackages:p}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=FP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),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&&Tne._visit(r.payload,{inlinedPayload:f=>{for(let p of f.extends)v4a(p,a,u);for(let p of f.properties)G6(p.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!_4a(i.payload)){let p=pHi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:p}}},reference:({payloadType:f})=>{G6(f,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 f of i.messages)qne._visit(f.body,{reference:({bodyType:p})=>{G6(p,a,u)},inlinedBody:p=>{for(let c of p.extends)v4a(c,a,u);for(let c of p.properties)G6(c.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 f of this.endpointsNeededForAudience.keys()){let p=this.getEndpointNode(f);for(let c of p.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,p.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let p=this.getWebhookNode(f);this.addReferencedTypes(t,p.referencedTypes)}for(let f of this.channelsNeededForAudience.keys()){let p=this.getChannelNode(f);this.addReferencedTypes(t,p.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,p]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}c.size>0&&(i[f]=c),i[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}n[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.parametersByAudience[o];l?.forEach(m=>{c.add(m)})}a[f]=c.size>0?c:void 0}for(let[f,p]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=p.propertiesByAudience[o];l?.forEach(m=>{c.add(m)})}u[f]=c.size>0?c:void 0}}return new y4a({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(f=>{t.add(f)});else{n.allDescendants.forEach(f=>{t.add(f)});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:sc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(FP.generateSubpackageId(i))}}};function Hl1(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:sc(e)}}function G6(e,t,r){wM._visit(e,{container:i=>{Jl1(i,t,r)},named:i=>{v4a(i,t,r)},primitive:Mc,unknown:Mc,_other:Mc})}function v4a(e,t,r){t.add(FP.generateTypeId(e)),r.add(e.fernFilepath)}function Jl1(e,t,r){nB._visit(e,{list:i=>{G6(i,t,r)},map:i=>{G6(i.keyType,t,r),G6(i.valueType,t,r)},optional:i=>{G6(i,t,r)},set:i=>{G6(i,t,r)},literal:Mc,_other:Mc})}function rgd({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:$6({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?s4.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=$6({filteredIr:e,exampleTypeReference:r});return i!==void 0?s4.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function $6({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Wm.container(KE.list({...i,list:i.list.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Wm.container(KE.set({...i,set:i.set.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?$6({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Wm.container(KE.optional({optional:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Wm.container(KE.map({...i,map:i.map.map(n=>{let a=$6({filteredIr:e,exampleTypeReference:n.key}),u=$6({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=$6({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Wm.named({...r,shape:WD.enum(i)})}),object:i=>({...t,shape:Wm.named({...r,shape:WD.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:$6({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=rgd({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=$6({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Wm.named({...r,shape:WD.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function ILu({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Ql1({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function tgd({filteredIr:e,headers:t}){return t.map(r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Gl1({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=$6({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=$6({filteredIr:e,exampleTypeReference:r});return i!==void 0?o$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function $l1({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Ox.ok(XB.body(i!=null?$6({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Ox.ok(XB.stream(i.map(n=>$6({filteredIr:e,exampleTypeReference:n})).filter(OM))),sse:i=>Ox.ok(XB.sse(i.map(({event:n,data:a})=>{let u=$6({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(OM))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Ox.error({error:r,body:i!=null?$6({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function zLu({filteredIr:e,example:t}){return{...t,rootPathParameters:ILu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:ILu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:ILu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:tgd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:tgd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:Ql1({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?Gl1({filteredIr:e,requestBody:t.request}):void 0,response:$l1({filteredIr:e,response:t.response})}}function igd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=$6({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:WD.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:WD.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:$6({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=rgd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:WD.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=$6({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:WD.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var g4a=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:FP.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:Ih(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!ngd(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(!ngd(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(c=>{let o=this.subpackages[c];if(o==null)throw new Error("Subpackage ID is invalid: "+c);return o}),u=r+1,f={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},p=a.find(c=>c.name.originalName===n.originalName);if(p==null){let c=FP.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,i.subpackages.push(c),p=o}return this.getPackageForFernFilepath(t,u,p)}};function ngd(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 agd({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 f=r[i];if(f!=null)return{endpointName:n,relativeFilepath:THr({referencedIn:t,importPath:f})}}var api=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 O4(this.workspace,(n,a,u)=>{let f=fO({relativeFilepath:n,definitionFile:a,casingsGenerator:CHr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[p,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(i={endpointId:p,endpoint:c,file:f})}),Wfi(this.workspace,(n,a)=>{let u=fO({relativeFilepath:n,definitionFile:a,casingsGenerator:CHr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,p]of Object.entries(a.service?.endpoints??{}))p.method===t&&p.path===r&&(i={endpointId:f,endpoint:p,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new vci().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=agd({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var opi=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=BSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:fO({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var zSe=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(UD(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(`\\${GVt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(GVt))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(GVt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(GVt.length),exampleName:n}}};var m4a=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:Ene.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=typeof i["query-parameters"]!=null?i["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Ene.query(c4a({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:Ene.body(u)}}if(YB(i.body)){let u=jLu({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Ene.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:Ene.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return PLu({typeResolver:this.typeResolver,file:ZTn(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 MA=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=BSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=cae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=e7(i.typeName);if(u!=null){for(let f of Object.keys(n.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let p=n.types?.[f];return p!=null?{typeName:f,declaration:p,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:fO({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return l$({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:wM.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:wM.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:wM.container(nB.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:wM.container(nB.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:wM.container(nB.optional(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:wM.container(nB.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:wM.container(nB.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(f=>f.file===u.file&&f.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(oUr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let f=eqn({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||cae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:f,file:u}}};var L3t=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:IIr({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 O4a(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function LH({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,disableExamples:n,audiences:a,readme:u,packageName:f,version:p,context:c,fdrApiDefinitionId:o,includeOptionalRequestPropertyExamples:l,sourceResolver:m}){let O=oJt({generationLanguage:t,keywords:r,smartCasing:i}),j=new b4a(a),A=IIr({casingsGenerator:O,rootApiFile:e.definition.rootApiFile.contents}),T=(e.definition.rootApiFile.contents.errors??[]).map(pi=>({error:qHr({errorName:pi,file:A}),docs:void 0})),B=new MA(e),z=new api(e),C=new m4a(B,z),N=new opi(e),U=new zSe(B),k=new L3t,ve={fdrApiDefinitionId:o,apiVersion:Mbd({file:A,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:O.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:i4a(e.definition.rootApiFile.contents.docs),auth:Abd({rawApiFileSchema:e.definition.rootApiFile.contents,file:A,propertyResolver:C,endpointResolver:z}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([pi,Ft])=>kBe({headerKey:pi,header:Ft,file:A})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([pi,Ft])=>kBe({headerKey:pi,header:Ft,file:A})):[],types:{},errors:{},services:{},constants:vbd(O),environments:MLu({casingsGenerator:O,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:Bbd(e.definition.rootApiFile.contents["error-discrimination"],A),basePath:e.definition.rootApiFile.contents["base-path"]!=null?XBe(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:dHi({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:A,location:Sxe.Root,variableResolver:k}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([pi,Ft])=>({docs:typeof Ft!="string"?Ft.docs:void 0,id:pi,name:A.casingsGenerator.generateName(pi),type:A.parseTypeReference(Ft)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},Y=new g4a,X=pi=>{Y.addSubpackage(pi.fernFilepath),LD(pi.definitionFile,{imports:Mc,docs:Ft=>{Ft!=null&&Y.addDocs(pi.fernFilepath,Ft)},types:Ft=>{if(Ft!=null)for(let[Xt,ei]of Object.entries(Ft)){if(wxe(Xt))continue;let ai=Wbd({typeName:Xt,typeDeclaration:ei,file:pi,typeResolver:B,exampleResolver:U,sourceResolver:m,workspace:e}),hn=ai.typeDeclaration;n&&(hn.userProvidedExamples=[],hn.autogeneratedExamples=[]);let cn=ai.descendantFilepaths,ia=FP.generateTypeId(hn.name);ve.types[ia]=hn,Y.addType(ia,hn),j.addType({declaredTypeName:hn.name,descendantTypeIds:hn.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:ai.propertiesByAudience,descendantFilepaths:cn}),j.markTypeForAudiences(hn.name,E0d(ei))}},errors:Ft=>{if(Ft==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[ei,ai]of Object.entries(Ft)){let hn=Cbd({errorName:ei,errorDeclaration:ai,file:pi,typeResolver:B,exampleResolver:U,workspace:e}),cn=FP.generateErrorId(hn.name);ve.errors[cn]=hn,Y.addError(cn,hn),j.addError(hn)}},service:Ft=>{if(Ft==null)return;let Xt=ybd({rootDefaultUrl:pi.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:ve.pathParameters,serviceDefinition:Ft,file:pi,errorResolver:N,typeResolver:B,propertyResolver:C,exampleResolver:U,sourceResolver:m,globalErrors:T,variableResolver:k,workspace:e}),ei=FP.generateServiceId(Xt.name);ve.services[ei]=Xt,Y.addService(ei,Xt);let ai={};Xt.endpoints.forEach(hn=>{n&&(hn.autogeneratedExamples=[],hn.userSpecifiedExamples=[]);let cn=Ft.endpoints[hn.name.originalName];j.addEndpoint(Xt,hn,cn),ai[hn.name.originalName]=hn}),Ft.audiences!=null&&j.markEndpointForAudience(Xt.name,Xt.endpoints,Ft.audiences),Object.entries(Ft.endpoints).map(([hn,cn])=>{let ia=ai[hn];ia!=null&&cn.audiences!=null&&j.markEndpointForAudience(Xt.name,[ia],cn.audiences)})},webhooks:Ft=>{if(Ft==null)return;let Xt=FP.generateWebhookGroupId(pi.fernFilepath),ei=zbd({webhooks:Ft,file:pi,typeResolver:B,exampleResolver:U,workspace:e}),ai={};for(let hn of ei)ai[hn.name.originalName]=hn;Object.entries(Ft).forEach(([hn,cn])=>{let ia=ai[hn];ia!=null&&(j.addWebhook(pi,ia,cn),cn.audiences!=null&&j.markWebhookForAudiences(pi,ia,cn.audiences))}),ve.webhookGroups[Xt]=ei,Y.addWebhookGroup(Xt,pi.fernFilepath)},channel:Ft=>{if(Ft==null)return;let Xt=FP.generateWebSocketChannelId(pi.fernFilepath),ei=Tbd({channel:Ft,file:pi,variableResolver:k,typeResolver:B,exampleResolver:U,workspace:e});j.addChannel(pi,Xt,ei,Ft),Ft.audiences!=null&&j.markChannelForAudiences(pi,Xt,Ft.audiences),ve.websocketChannels!=null&&(ve.websocketChannels[Xt]=ei,Y.addWebSocketChannel(Xt,pi.fernFilepath))}})};O4(e,(pi,Ft,Xt)=>{X(fO({relativeFilepath:pi,definitionFile:Ft,casingsGenerator:O,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Xt.defaultUrl}))}),Wfi(e,(pi,Ft)=>{if(Ft.navigation!=null)if(typeof Ft.navigation=="string")Y.addPackageRedirection({from:bae({relativeFilepath:pi,casingsGenerator:O}),to:bae({relativeFilepath:M6(tCe(pi),Q0.of(Ft.navigation)),casingsGenerator:O})});else{let Xt=Ft.navigation.map(ei=>FP.generateSubpackageId(bae({relativeFilepath:M6(tCe(pi),Q0.of(ei)),casingsGenerator:O})));pi===HE?Y.sortRootPackage(Xt):Y.sortSubpackage(FP.generateSubpackageId(bae({relativeFilepath:pi,casingsGenerator:O})),Xt)}}),ve.serviceTypeReferenceInfo=Yl1(j);let Ae=n?ve:Kl1(ve,c,!l),pt=e.definition.rootApiFile.contents,ct=MLu({casingsGenerator:O,rawApiFileSchema:pt}),Dt=ct?.environments._visit({singleBaseUrl:pi=>pi.environments.filter(Ft=>O4a(Ft.id,pt.environments)!=null).length===0,multipleBaseUrls:pi=>pi.environments.filter(Ft=>O4a(Ft.id,pt.environments)!=null).length===0,_other:()=>!1});ct?.environments.environments.forEach(pi=>{j.markEnvironmentForAudiences(pi,O4a(pi.id,pt.environments)??[],Dt)});let Rt=j.hasNoAudiences()?void 0:j.build(),Zt=Xl1(Ae,Rt),Vt=e.definition.rootApiFile.contents.auth!=null&&Object.values(Zt.services).every(pi=>pi.endpoints.every(Ft=>Ft.auth)),sr=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.response?.body?.type==="streaming")),Wr=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.pagination!=null)),mi=Object.values(Zt.services).some(pi=>pi.endpoints.some(Ft=>Ft.response?.body?.type==="fileDownload")),Yt={isAuthMandatory:Vt,hasStreamingEndpoints:sr,hasPaginatedEndpoints:Wr,hasFileDownloadEndpoints:mi,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:p!=null&&f!=null?{header:"User-Agent",value:`${f}/${p}`}:void 0}},Mr=u!=null?Ibd({readme:u,services:ve.services}):void 0,{types:Ei,services:br}=Zbd(Zt),Ii={...Zt,...Y.build(Rt),types:Ei,services:br,sdkConfig:Yt,readmeConfig:Mr};return{...Ii,dynamic:Jbd(Ii)}}function Kl1(e,t,r){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=aqn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:r??!0,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.debug(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:f}=u;a.autogeneratedExamples=[{example:f}]}return e}function Yl1(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;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function Xl1(e,t){if(t==null)return e;let r=Joi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,f])=>{let p=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>igd({filteredIr:t,exampleType:c})).filter(c=>c!==void 0),f.shape.type==="object"){for(let c of f.shape.properties)t.hasProperty(u,c.name.wireValue)&&p.push(c);return[u,{...f,shape:iB.object({...f.shape,properties:p})}]}return[u,f]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let p=f.filter(c=>t.hasWebhook(c)).map(c=>{let o=c.id;return c.payload.type==="inlinedPayload"&&o!=null&&(c.payload={...c.payload,properties:c.payload.properties.filter(l=>t.hasWebhookPayloadProperty(o,l.name.wireValue))}),c});return[u,p]})),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:Joi(e.errors,u=>t.hasError(u)),services:Ih(Joi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(p=>({...p,example:zLu({filteredIr:t,example:p.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(p=>({...p,example:p.example!=null?zLu({filteredIr:t,example:p.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(p=>t.hasQueryParameter(f.id,p.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(p=>t.hasRequestProperty(f.id,p.name.wireValue))}}:f))})),webhookGroups:n,serviceTypeReferenceInfo:Zl1(e.serviceTypeReferenceInfo,t)}}function Zl1(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}}var bgd=bo(R3a(),1),ggd=bo(L3a(),1),S4a=require("fs/promises"),mgd=bo(T6a(),1);function cJt(e){return typeof e.subpackageId=="string"}function NSe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function upi(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var NLu="__package__",IHr=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;#o=new Map;#a=new Map;#l=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return cJt(t)?t.subpackageId:NLu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=A5.SubpackageId(t);return r===NLu?this.api.rootPackage:this.api.subpackages[r]??this.#u.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=A5.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#a.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,n);this.#e.set(f,u);let p=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{p.push(`${o} ${NSe(u.path.parts)}`),p.push(`${o} ${upi(u.path.parts)}`),u.environments.forEach(l=>{p.push(`${o} ${OP(l.baseUrl,NSe(u.path.parts))}`),p.push(`${o} ${OP(l.baseUrl,upi(u.path.parts))}`);let m=ogd(l);m!=null&&(p.push(`${o} ${OP(m,NSe(u.path.parts))}`),p.push(`${o} ${OP(m,upi(u.path.parts))}`))})}),p.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#l.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,n);this.#t.set(f,u);let p=[];["GET","WSS"].forEach(o=>{p.push(`${o} ${NSe(u.path.parts)}`),p.push(`${o} ${upi(u.path.parts)}`),u.environments.forEach(l=>{p.push(`${o} ${OP(l.baseUrl,NSe(u.path.parts))}`),p.push(`${o} ${OP(l.baseUrl,upi(u.path.parts))}`);let m=ogd(l);m!=null&&(p.push(`${o} ${OP(m,NSe(u.path.parts))}`),p.push(`${o} ${OP(m,upi(u.path.parts))}`))})}),p.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.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.#o.set(i,n)}),this.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let i=cJt(t)?[...r,t.name]:r,n=i.length===0?[NLu]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#d(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#l.set(c,u)})}),t.websockets.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering websocket locator: ${c}`),this.#c.set(c,u)})}),t.webhooks.forEach(u=>{let f=[...i,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering webhook locator: ${c}`),this.#s.set(c,u)})}),t.subpackages.forEach(u=>{this.#d(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#l}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#a}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#o.get(t)}static createEndpointId(t,r){return gc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return gc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return gc.WebhookId(`${r}.${t.id}`)}};function ogd(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 hHi=bo(R3a(),1),sgd=bo(L3a(),1);function ugd(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{}}hHi.default.extend(sgd.default);var kl1="Changelog",ef1=["summary","index","overview"],spi=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??kl1,i=[],n;for(let l of this.changelogFiles??[]){let m=Ouu(l.split("/"));if(m==null)continue;let O=ugd(m);if(O==null){let A=m.split(".")[0]?.toLowerCase();A!=null&&ef1.includes(A)&&(n=l);continue}let j=this.toRelativeFilepath(l);i.push({date:O,pageId:gc.PageId(j),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??DL(r)}),u=i.map(l=>{let m=hHi.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:m.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:m.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=FLu(u,l=>l.date,"desc"),p=n!=null?gc.PageId(this.toRelativeFilepath(n)):void 0,c=this.idgen.get(p??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:p,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}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=hHi.default.utc(a.date).year(),f=n.get(u)??[];f.push(a),n.set(u,f)}return FLu(Array.from(n.entries()).map(([a,u])=>{let f=i.append(a.toString()).get(),p=this.idgen.get(`${t}/year/${a}`);return{id:p,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(p,u,i),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=hHi.default.utc(a.date).month()+1,f=n.get(u)??[];f.push(a),n.set(u,f)}return FLu(Array.from(n.entries()).map(([a,u])=>{let f=(0,hHi.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.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}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}};function FLu(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})}var P4a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#o=new Map;#a=[];#l;#c;#s;disableEndpointPairs;constructor(t,r,i,n,a,u,f,p){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=gc.V1.ApiDefinitionId(r.id),this.#e=IHr.create(r,u),this.#s=p,this.#l=this.apiSection.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??DL(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#a=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#a=this.#y(this.#a.map(o=>this.#g(o)),this.#w(this.#e.api.rootPackage,this.#c))}get(){let t=gc.V1.followRedirects(this.#a),r=new spi(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.#c.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0}),children:this.#a,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?IHr.getSubpackageId(r):void 0;return t.map(a=>e3a(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:gc.Url(u.url)}),page:u=>this.#d(u,i),package:u=>this.#v(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#P(u,n,i)})).filter(OM)}#d(t,r){let i=gc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??DL(t.title)});return{id:this.#s.get(i),type:"page",pageId:i,title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let i=t.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(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=IHr.getSubpackageId(a),f=this.#s.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.#o.set(f,[u]);let p=t.slug??(cJt(a)?a.urlSlug:this.apiSection.slug??DL(this.apiSection.title)),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:p}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(cJt(a)?a.displayName??Hdi(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??DL(t.package),f=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#u(t.contents,void 0,f);return{id:this.#s.get(i??`${this.apiDefinitionId}:${DL(t.package)}`),type:"apiPackage",children:p,title:t.title??t.package,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.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let i=t.overviewAbsolutePath!=null?gc.V1.PageId(this.toRelativeFilepath(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(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?IHr.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(OM);this.#o.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 f=t.slug??DL(t.title),p=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,p);return{id:a,type:"apiPackage",children:c,title:t.title,slug:p.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=IHr.getSubpackageId(n),u=this.#s.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.#o.set(u,[a]);let f=cJt(n)?n.urlSlug:"",p=i.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:cJt(n)?n.displayName??Hdi(n.name):this.apiSection.title,slug:p.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}}return this.#P({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},r,i)}#P(t,r,i){let n=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.endpoints.get(A5.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let f=this.#e.getEndpointId(n);if(f==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let p=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:n.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??NSe(n.path.parts),slug:p.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.webSockets.get(A5.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#r.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#r.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??NSe(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:gc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(A5.SubpackageId(r))?.webhooks.get(A5.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(gc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??OP("/",...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}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(i=>i.type==="apiPackage"?i.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=gc.V1.SlugGenerator.init(t.slug),n=(this.#o.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,n);return{...t,children:u,pointsTo:void 0}}return t}#w(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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??NSe(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned: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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??NSe(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:gc.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned: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:gc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??Hdi(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})}),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=cJt(a)?r.apply(a):r,f=this.#m(n,u);f.length>0&&i.push({id:gc.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:f,title:cJt(a)?a.displayName??Hdi(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})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),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.#w(i,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>gc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:gc.V1.Url(t.button.href)}:void 0,"limit-websocket-messages-per-connection":t.limitWebsocketMessagesPerConnection!=null?t.limitWebsocketMessagesPerConnection:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],i=new Map;return t.forEach(n=>{if(n.type!=="endpoint"){r.push(n);return}let a=this.#e.endpoints.get(n.endpointId);if(a==null)throw new Error(`Endpoint ${n.endpointId} not found`);let u=`${a.method} ${NSe(a.path.parts)}`,f=i.get(u);if(i.set(u,n),f==null||f.isResponseStream===n.isResponseStream){r.push(n);return}let p=r.indexOf(f),c=n.isResponseStream?n:f,o=n.isResponseStream?f:n,l={id:gc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[p]=l}),r}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}};var cgd=bo(require("crypto"),1);function tf1(e){return cgd.default.createHash("sha256").update(e).digest("hex")}var j4a=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),tf1(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 gc.V1.NodeId(this.#n(t))}};function lgd(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 w4a=bo(u6t(),1);var tD=bo(u6t(),1);var zHr=bo(u6t(),1);function dgd(e){return e._visit({alias:t=>({type:"alias",value:nT(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:ER(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>zHr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:zHr.FernRegistry.PropertyKey(r.name.wireValue),valueType:nT(r.valueType),availability:ER(r.availability)})),extraProperties:nf1(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:zHr.FernRegistry.PropertyKey(i.name.wireValue),valueType:nT(i.valueType),availability:ER(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?ER(i.availability):void 0,additionalProperties:dd.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[zHr.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:zHr.FernRegistry.PropertyKey(n.name.wireValue),valueType:nT(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:nT(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function nT(e){return e._visit({container:t=>dd.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:nT(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:nT(r),valueType:nT(i)}),optional:r=>({type:"optional",itemType:nT(r),defaultValue:void 0}),set:r=>({type:"set",itemType:nT(r)}),literal:r=>dd.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:zHr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:dd.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>if1(t.v2),float:()=>fgd(t.v2),double:()=>fgd(t.v2),string:()=>rf1(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",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 rf1(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function if1(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 fgd(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 nf1(e){return typeof e=="boolean"?e?wM.unknown():void 0:typeof e=="string"?{type:"id",value:zHr.FernRegistry.TypeId(e),default:void 0}:nT(e)}function LLu(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?of1(r,t):[],webhooks:i!=null?af1(i):[],websockets:n!=null?[uf1(n,t)]:[],types:e.types.map(a=>tD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>tD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?tD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function af1(e){return e.map(t=>({description:t.docs??void 0,id:tD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Xmn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:nT(r.valueType),availability:ER(r.availability)})),payload:hf1(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function of1(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0&&n!=null)a.push(...i.userSpecifiedExamples.map(f=>RLu({autogeneratedExample:n,userSpecifiedExample:f,irEndpoint:i,ir:t})));else if(n!=null)a.push(RLu({autogeneratedExample:n,irEndpoint:i,ir:t}));else if(i.response?.body?.type==="fileDownload"){let f=aqn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let p={...RLu({autogeneratedExample:f,irEndpoint:i,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(p)}}let u={availability:ER(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:ff1(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?tD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?sf1({environmentsConfig:t.environments,endpoint:i}):void 0,id:tD.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Xmn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(f=>({description:f.docs??void 0,key:tD.FernRegistry.PropertyKey(f.name.originalName),type:nT(f.valueType),availability:void 0})),parts:[...yHi(i.basePath),...yHi(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(f=>({description:f.docs??void 0,key:tD.FernRegistry.PropertyKey(f.name.originalName),type:nT(f.valueType),availability:void 0})),parts:[...t.basePath!=null?yHi(t.basePath):[],...yHi(e.basePath),...yHi(i.path)]},queryParameters:i.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:nT(f.valueType),availability:ER(f.availability)})),headers:[...e.headers,...i.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:nT(f.valueType),availability:ER(f.availability)})),request:i.requestBody!=null?df1(i.requestBody):void 0,response:i.response!=null?pf1(i.response):void 0,errors:void 0,errorsV2:_f1(i.errors,t),examples:a};r.push(u)}return r}function uf1(e,t){return{auth:e.auth,availability:ER(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?tD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?cf1({environmentsConfig:t.environments,channel:e}):[],id:tD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Xmn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:tD.FernRegistry.PropertyKey(r.name.originalName),type:nT(r.valueType),availability:void 0})),parts:yHi(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:nT(r.valueType),description:r.docs,availability:ER(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:nT(r.valueType),availability:ER(r.availability)})),messages:e.messages.map(r=>({type:tD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:yf1(r.body),description:r.docs,availability:ER(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[tD.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:tD.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function ER(e){if(e!=null)switch(e.status){case"DEPRECATED":return tD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return tD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return tD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return tD.FernRegistry.Availability.Beta;default:sc(e.status)}}function sf1({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:tD.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:tD.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:sc(r)}}function cf1({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:tD.FernRegistry.EnvironmentId(i.id),baseUrl:lf1(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:sc(r)}}function lf1(e,t){return e.replace(/^[^:]+/,t)}function ff1(e){return dd.http.HttpMethod._visit(e,{get:()=>tD.FernRegistry.HttpMethod.Get,post:()=>tD.FernRegistry.HttpMethod.Post,put:()=>tD.FernRegistry.HttpMethod.Put,patch:()=>tD.FernRegistry.HttpMethod.Patch,delete:()=>tD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function yHi(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:tD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function df1(e){let t=dd.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??WI.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>tD.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:tD.FernRegistry.PropertyKey(i.name.wireValue),valueType:nT(i.valueType),availability:ER(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??WI.APPLICATION_JSON,shape:{type:"reference",value:nT(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:tD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:tD.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:tD.FernRegistry.PropertyKey(n.name.wireValue),valueType:nT(n.valueType),contentType:n.contentType,description:n.docs,availability:ER(n.availability)}),_other:()=>{}})).filter(OM)},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 pf1(e){if(e.body==null)return;let t,r=dd.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:nT(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:nT(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:nT(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function _f1(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:nT(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:tD.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:tD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:nT(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 RLu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(f=>{let p=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(p!=null)return{name:f.name,value:{jsonExample:p,shape:dd.ExampleTypeReferenceShape.primitive(dd.ExamplePrimitive.string({original:p}))}}}).filter(OM),a=e?.example??t.example,{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((f,p)=>(f[tD.FernRegistry.PropertyKey(p.name.originalName)]=p.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,p)=>(f[p.name.wireValue]=p.value.jsonExample,f),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((f,p)=>(f[p.name.wireValue]=p.value.jsonExample,f),{}),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:f=>{if(a.request==null)return;let p={};if(UD(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let m=c[l.key.wireValue];if(l.type==="file")p[l.key.wireValue]={type:"filename",value:typeof m=="string"?m:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(m)?m:[m]).filter(j=>typeof j=="string");p[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{p[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:I7t})}return{type:"form",value:p}},bytes:()=>{},_other:()=>{}}),responseStatusCode:dd.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:p=>p!=null?200:204,stream:p=>p.length>0?200:204,sse:p=>p.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let p=i.errors[f.errorId];if(p==null)throw new Error("Cannot find error "+f.errorId);return p.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:p=>p?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:p=>p!=null?{type:"json",value:p.jsonExample}:void 0,stream:p=>({type:"stream",value:p.map(c=>c.jsonExample)}),sse:p=>({type:"sse",value:p.map(({event:c,data:o})=>({event:c,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:f=>f.body!=null?{type:"json",value:f.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(f=>eSe._visit(f,{language:p=>({language:p.language,code:p.code,name:p.name?.originalName,description:p.docs??void 0,install:p.install}),sdk:p=>({language:p.sdk,code:p.code,name:p.name?.originalName,description:p.docs??void 0,install:void 0}),_other:()=>{}})).filter(OM)}}function hf1(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>tD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:tD.FernRegistry.PropertyKey(t.name.wireValue),valueType:nT(t.valueType),availability:ER(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:nT(e.payloadType)},description:e.docs};default:sc(e)}}function yf1(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>tD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:tD.FernRegistry.PropertyKey(t.name.wireValue),valueType:nT(t.valueType),availability:ER(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:nT(e.bodyType)};default:sc(e)}}var ULu=bo(u6t(),1);function pgd(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:ULu.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:ULu.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:sc(i)}}function FSe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:LLu(e.rootPackage,e),auth:pgd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:ER(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:nT(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[w4a.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:dgd(a.shape),availability:ER(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[w4a.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:w4a.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...LLu(a,e)}}return i}var VLu=bo(u6t(),1);var _gd=require("fs"),D4a=class{parse({absoluteFilePath:t}){let r=(0,_gd.readFileSync)(t,"utf-8"),i=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),n=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:i?.[1],packageName:n?.[1],serviceName:a?.[1]}}};var M5=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}resolveSourceOrThrow({source:t,relativeFilepath:r}){let i=this.resolveSource({source:t});if(i==null){if(fci(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r}`)}return i}resolveSource({source:t}){return fci(t)?this.resolveProtobufSource({source:t}):this.resolveOpenAPISource({source:t})}resolveProtobufSource({source:t}){let r=Sf(this.workspace.absoluteFilePath,Pc.of(t.proto));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Vua(r))return;let n=new D4a().parse({absoluteFilePath:r}),a={type:"protobuf",absoluteFilePath:r,relativeFilePath:Pc.of(t.proto),csharpNamespace:n.csharpNamespace,packageName:n.packageName,serviceName:n.serviceName};return this.sourceCache.set(r,a),a}resolveOpenAPISource({source:t}){let r=Sf(this.workspace.absoluteFilePath,Pc.of(t.openapi));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Vua(r))return;let i={type:"openapi",absoluteFilePath:r,relativeFilePath:Pc.of(t.openapi)};return this.sourceCache.set(r,i),i}};async function WLu({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let f=LH({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new M5(r,t)}),p=Oci({token:i.value}),c=FSe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await p.api.v1.register.registerApiDefinition({orgId:VLu.FernRegistry.OrgId(e),apiId:VLu.FernRegistry.ApiId(f.apiName.originalName),definition:c});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:f};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 vf1=new Kdi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function hgd(e,t,r){return TTn(ETn(FSe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),A5.ApiDefinitionId(t),vf1))}function ygd(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}function NIr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}bgd.default.extend(ggd.default);var bf1=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),vgd=0,gf1=async({ir:e})=>(vgd++,`${e.apiName.snakeCase.unsafeName}-${vgd}`),FIr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,i,n,a,u=bf1,f=gf1){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=i,this.taskContext=n,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=j4a.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await ohu({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(p=>{p.changelog?.files.forEach(c=>{let o=GI(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=await JRu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(p),context:this.taskContext});for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=await QRu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(p),context:this.taskContext});let t=ygd(this.parsedDocsConfig);for(let[p,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=mTn(c,{absolutePathToMdx:this.resolveFilepath(p),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Pc.of(p)]=l;for(let m of o)t.add(m)}let r=Array.from(t).map(p=>({absoluteFilePath:p,relativeFilePath:this.toRelativeFilepath(p)}));(await this.uploadFiles(r)).forEach(p=>{this.collectedFileIds.set(p.absoluteFilePath,p.fileId)});let n=this.getDocsBasePath();for(let[p,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pc.of(p)]=HRu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,OP(n,l)])),{absolutePathToMdx:this.resolveFilepath(p),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([p,c])=>{let o=mf1(this.editThisPage,p);a[I3t.PageId(p)]={markdown:c,editThisPageUrl:o?I3t.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let p=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=ZM(this.docsWorkspace.absoluteFilePath,c);(await(0,S4a.stat)(o)).isDirectory()?(await oCe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{p.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&p.add(o)})),f=Object.fromEntries(await Promise.all([...p].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,S4a.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return ZM(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return GI(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,mgd.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}getDocsBasePath(){return new URL(NIr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?I3t.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:I3t.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:I3t.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:void 0,ga4: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")}async toRootNode(){let t=gc.V1.SlugGenerator.init(gc.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=>gc.RoleId(n))}}async toRootChild(t){return q6i(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=gc.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??DL(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0}}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??DL(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:gc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?Of1(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}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(n,f,i))),u=[];return a.forEach(f=>{if(f.type==="apiReference"){u.push(f);return}if(f.type==="section"&&!f.collapsed){u.push(f);return}let p=u.length>0?u[u.length-1]:void 0,c;p?.type==="sidebarGroup"?c=p:(c={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(c)),c.children.push(f)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i){return q6i(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){let i=this.getFernWorkspaceForApiSection(t),n=lgd(t.snippetsConfiguration),a=LH({workspace:i,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new M5(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=hgd(a,u,{oauth:t.playground?.oauth});return new P4a(t,f,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new spi(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:gc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=gc.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??DL(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?gc.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),f=i.apply({urlSlug:r.slug??DL(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.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(p=>this.toNavigationChild(u,p,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}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 q6i(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 spi(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:gc.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??DL(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)}}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):I3t.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(OM),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:I3t.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 q6i(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:I3t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function mf1(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${NIr(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function Of1(e){switch(e){case"beta":return gc.V1.NavigationV1Availability.Beta;case"deprecated":return gc.V1.NavigationV1Availability.Deprecated;case"ga":return gc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return gc.V1.NavigationV1Availability.Stable;default:sc(e)}}var MCd=bo(Sgd(),1),pJu=bo(UUu(),1),TCd=bo(require("http"),1),C8a=bo(require("path"),1);var Xjd=require("events"),uFa=bo(require("fs"),1),vpi=bo(require("path"),1);var xjd=bo(require("os"),1),Bjd=300,VHr=20,Eqn=1e7,Ijd=xjd.default.platform();var nb1=Ijd==="darwin",VUu=Ijd==="win32",WHr=nb1||VUu,zjd=3e3,Njd=2e4,WUu=1250;var pJt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(pJt||(pJt={}));var ypi;(function(e){e.CHANGE="change",e.RENAME="rename"})(ypi||(ypi={}));var Aqn;(function(e){e.CHANGE="change",e.ERROR="error"})(Aqn||(Aqn={}));var vm;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(vm||(vm={}));var hk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(hk||(hk={}));var ab1=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,p=0,c=0,o=()=>{let N=Date.now(),U=N-p,k=N-c,ve=U>=t||k>=a;return[N,ve]},l=N=>{if(c=N,!u)return;let U=u;u=void 0,e.apply(void 0,U)},m=()=>{z(0)},O=()=>{f&&(m(),l(Date.now()))},j=N=>{if(c=N,i)return l(N)},A=N=>{if(n&&u)return l(N);u=void 0},T=()=>{f=void 0;let[N,U]=o();return U?A(N):B(N)},B=N=>{let U=N-p,k=N-c,ve=t-U,Y=a-k,X=Math.min(ve,Y);return z(X)},z=N=>{f&&clearTimeout(f),!(N<=0)&&(f=setTimeout(T,N))},C=(...N)=>{let[U,k]=o(),ve=!!f;if(u=N,p=U,(k||!f)&&z(t),k)return ve?l(U):j(U)};return C.cancel=m,C.flush=O,C},iFa=ab1;var $Uu=bo(require("fs"),1),aFa=bo(require("path"),1);var aT=bo(require("fs"),1),UH=require("util");var RIr=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},_Jt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var HUu=bo(require("process"),1),Fjd=HUu.default.getuid?!HUu.default.getuid():!1,Rjd=1e4,Pae=()=>{};var Mqn={isChangeErrorOk:e=>{if(!Mqn.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Fjd&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!Mqn.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!Mqn.isNodeError(e))throw e;if(!Mqn.isChangeErrorOk(e))throw e}},E4=Mqn;var JUu=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Rjd,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Ljd=new JUu;var LIr=(e,t)=>function(i){return function n(...a){return Ljd.schedule().then(u=>{let f=c=>(u(),c),p=c=>{if(u(),Date.now()>=i)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(m=>setTimeout(m,o)).then(()=>n.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,p)})}},UIr=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var ob1={attempt:{chmod:RIr((0,UH.promisify)(aT.default.chmod),E4.onChangeError),chown:RIr((0,UH.promisify)(aT.default.chown),E4.onChangeError),close:RIr((0,UH.promisify)(aT.default.close),Pae),fsync:RIr((0,UH.promisify)(aT.default.fsync),Pae),mkdir:RIr((0,UH.promisify)(aT.default.mkdir),Pae),realpath:RIr((0,UH.promisify)(aT.default.realpath),Pae),stat:RIr((0,UH.promisify)(aT.default.stat),Pae),unlink:RIr((0,UH.promisify)(aT.default.unlink),Pae),chmodSync:_Jt(aT.default.chmodSync,E4.onChangeError),chownSync:_Jt(aT.default.chownSync,E4.onChangeError),closeSync:_Jt(aT.default.closeSync,Pae),existsSync:_Jt(aT.default.existsSync,Pae),fsyncSync:_Jt(aT.default.fsync,Pae),mkdirSync:_Jt(aT.default.mkdirSync,Pae),realpathSync:_Jt(aT.default.realpathSync,Pae),statSync:_Jt(aT.default.statSync,Pae),unlinkSync:_Jt(aT.default.unlinkSync,Pae)},retry:{close:LIr((0,UH.promisify)(aT.default.close),E4.isRetriableError),fsync:LIr((0,UH.promisify)(aT.default.fsync),E4.isRetriableError),open:LIr((0,UH.promisify)(aT.default.open),E4.isRetriableError),readFile:LIr((0,UH.promisify)(aT.default.readFile),E4.isRetriableError),rename:LIr((0,UH.promisify)(aT.default.rename),E4.isRetriableError),stat:LIr((0,UH.promisify)(aT.default.stat),E4.isRetriableError),write:LIr((0,UH.promisify)(aT.default.write),E4.isRetriableError),writeFile:LIr((0,UH.promisify)(aT.default.writeFile),E4.isRetriableError),closeSync:UIr(aT.default.closeSync,E4.isRetriableError),fsyncSync:UIr(aT.default.fsyncSync,E4.isRetriableError),openSync:UIr(aT.default.openSync,E4.isRetriableError),readFileSync:UIr(aT.default.readFileSync,E4.isRetriableError),renameSync:UIr(aT.default.renameSync,E4.isRetriableError),statSync:UIr(aT.default.statSync,E4.isRetriableError),writeSync:UIr(aT.default.writeSync,E4.isRetriableError),writeFileSync:UIr(aT.default.writeFileSync,E4.isRetriableError)}},Ujd=ob1;var nFa=bo(require("fs"),1),Tqn=bo(require("path"),1);var Vjd={then:e=>{e()}};var QUu=()=>{};var GUu=()=>{let e=QUu,t=QUu,r=!1,i=!1;return{promise:new Promise((p,c)=>{e=o=>(r=!0,p(o)),t=o=>(i=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}};GUu.wrap=async e=>{let t=GUu();return await e(t),t.promise};var Wjd=GUu;var Hjd=e=>Array.isArray(e)?e:[e],Jjd=e=>typeof e=="function",Qjd=()=>{let{promise:e,resolve:t}=Wjd(),r=0,i=()=>{r+=1},n=()=>{r-=1,!r&&t()};return(()=>{i(),queueMicrotask(n)})(),{promise:e,increment:i,decrement:n}};var ub1=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Hjd(a).map(Yt=>Jjd(Yt)?Yt:Mr=>Yt.test(Mr)),f=Yt=>u.some(Mr=>Mr(Yt)),p=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,m={},O=[],j=new Set,A={},T=[],B=new Set,z={},C={},N=new Set,U={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},k={directories:o,directoriesNames:l,directoriesNamesToPaths:m,files:O,filesNames:j,filesNamesToPaths:A,symlinks:T,symlinksNames:B,symlinksNamesToPaths:z,map:C},{promise:ve,increment:Y,decrement:X}=Qjd(),Ae=0,pt=(Yt,Mr,Ei,br)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.directories.push(Mr),Yt.directoriesNames.add(Ei),o.push(Mr),l.add(Ei),m.propertyIsEnumerable(Ei)||(m[Ei]=[]),m[Ei].push(Mr),N.add(Mr),!(br>=i)&&(Ae>=n||sr(Mr,br+1)))},ct=(Yt,Mr,Ei)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.files.push(Mr),Yt.filesNames.add(Ei),O.push(Mr),j.add(Ei),A.propertyIsEnumerable(Ei)||(A[Ei]=[]),A[Ei].push(Mr),N.add(Mr))},Dt=(Yt,Mr,Ei,br)=>{N.has(Mr)||Ae>=n||(Ae+=1,Yt.symlinks.push(Mr),Yt.symlinksNames.add(Ei),T.push(Mr),B.add(Ei),z.propertyIsEnumerable(Ei)||(z[Ei]=[]),z[Ei].push(Mr),N.add(Mr),r&&(br>=i||Ae>=n||Wr(Mr,br+1)))},Rt=(Yt,Mr,Ei,br,Ii)=>{p.aborted||f(Mr)||(br.isDirectory()?pt(Yt,Mr,Ei,Ii):br.isFile()?ct(Yt,Mr,Ei):br.isSymbolicLink()&&Dt(Yt,Mr,Ei,Ii))},Zt=(Yt,Mr,Ei,br)=>{if(p.aborted)return;let Ii=Mr===Tqn.default.sep?"":Tqn.default.sep,pi=Ei.name,Ft=`${Mr}${Ii}${pi}`;f(Ft)||(Ei.isDirectory()?pt(Yt,Ft,pi,br):Ei.isFile()?ct(Yt,Ft,pi):Ei.isSymbolicLink()&&Dt(Yt,Ft,pi,br))},Vt=(Yt,Mr,Ei,br)=>{for(let Ii=0,pi=Ei.length;Ii<pi;Ii++)Zt(Yt,Mr,Ei[Ii],br)},sr=(Yt,Mr)=>{p.aborted||Mr>i||Ae>=n||(Y(),nFa.default.readdir(Yt,{withFileTypes:!0},(Ei,br)=>{if(Ei||p.aborted||!br.length)return X();(c(br)||Vjd).then(()=>{let pi=C[Yt]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Vt(pi,Yt,br,Mr),X()})}))},Wr=async(Yt,Mr)=>{Y(),nFa.default.realpath(Yt,(Ei,br)=>{if(Ei||p.aborted)return X();nFa.default.stat(br,async(Ii,pi)=>{if(Ii||p.aborted)return X();let Ft=Tqn.default.basename(br),Xt=C[Yt]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Rt(Xt,br,Ft,pi,Mr),X()})})};return(async(Yt,Mr=1)=>(Yt=Tqn.default.normalize(Yt),N.add(Yt),sr(Yt,Mr),await ve,p.aborted?U:k))(e)},Gjd=ub1;var hJt={lang:{debounce:iFa,attempt:e=>{try{return e()}catch(t){return hJt.lang.castError(t)}},castArray:e=>hJt.lang.isArray(e)?e:[e],castError:e=>hJt.lang.isError(e)?e:hJt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(hJt.lang.isNaN(e))return hJt.lang.isNaN(t);if(hJt.lang.isPrimitive(e)||hJt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(aFa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?$Uu.default.realpathSync.native(e):$Uu.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===aFa.default.sep&&t.length-e.length>aFa.default.sep.length,poll:(e,t=Njd)=>Ujd.retry.stat(t)(e,{bigint:!0}).catch(hJt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await Gjd(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},Jj=hJt;var oFa=bo(require("path"),1);var KUu=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Jj.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Bjd){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(f,p)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...p]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=Jj.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(f,p="",c=!1)=>{c?await this.eventsPopulate([p],i,!0):n.add(p),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,f=r[u];return a===f||a===vm.CHANGE&&f===vm.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===vm.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===vm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??VHr:Math.min(1,this.options.depth??VHr),u=this.options.limit??Eqn,[f,p]=await Jj.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...p];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Jj.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(vm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!WHr&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(vm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(vm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(oFa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(vm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(oFa.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(vm.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===vm.ADD?this.onTargetAdd(i):r===vm.ADD_DIR?this.onTargetAddDir(i):r===vm.CHANGE?this.onTargetChange(i):r===vm.UNLINK?this.onTargetUnlink(i):r===vm.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=ypi.CHANGE,r){if(this.watcher.isClosed())return;let i=oFa.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){VUu&&t.code==="EPERM"?this.onWatcherChange(ypi.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(Aqn.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(Aqn.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(ypi.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&WHr&&this.options.native!==!1?this.options.depth??VHr:Math.min(1,this.options.depth??VHr),i=this.options.limit??Eqn,[n,a]=await Jj.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(ypi.CHANGE,f,t)}))}}},$jd=KUu;var yk={interval:100,intervalId:void 0,fns:new Map,init:()=>{yk.intervalId||(yk.intervalId=setInterval(yk.resolve,yk.interval))},reset:()=>{yk.intervalId&&(clearInterval(yk.intervalId),delete yk.intervalId)},add:(e,t)=>{yk.fns.set(e,Date.now()+t),yk.init()},remove:e=>{yk.fns.delete(e)},resolve:()=>{if(!yk.fns.size)return yk.reset();let e=Date.now();for(let[t,r]of yk.fns)r>=e||(yk.remove(t),t())}},qqn=yk;var Cqn=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=WUu){let{ino:i,targetPath:n,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(i||-1,m=>m!==n);if(l&&l!==n){if(Jj.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return f();let p=()=>{u.add.delete(i),qqn.remove(c)},c=()=>{p(),f()};qqn.add(c,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;p();let m=l();n===m?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,m,n)};u.add.set(i,o),o()}getLockUnlink(t,r=WUu){let{ino:i,targetPath:n,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,n)};if(!i)return f();let p=()=>{u.unlink.delete(i),qqn.remove(c)},c=()=>{p(),f()};qqn.add(c,r);let o=()=>(p(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,vm.ADD,pJt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,vm.ADD_DIR,pJt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,vm.UNLINK,pJt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,vm.UNLINK_DIR,pJt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};Cqn.DIR_EVENTS={add:vm.ADD_DIR,rename:vm.RENAME_DIR,unlink:vm.UNLINK_DIR};Cqn.FILE_EVENTS={add:vm.ADD,change:vm.CHANGE,rename:vm.RENAME,unlink:vm.UNLINK};var Kjd=Cqn;var YUu=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Jj.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Jj.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Jj.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Jj.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Jj.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Jj.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},XUu=YUu;var ZUu=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},Yjd=ZUu;var kUu=class{constructor(){this.inos={},this.paths=new XUu,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Jj.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Yjd(i)}reset(){this.inos={},this.paths=new XUu,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,vm.ADD,n),[vm.ADD];if(n.isDirectory())return this.updateIno(t,vm.ADD_DIR,n),[vm.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,vm.UNLINK,i),[vm.UNLINK];if(i.isDirectory())return this.updateIno(t,vm.UNLINK_DIR,i),[vm.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,vm.CHANGE,n),[vm.CHANGE]);if(n.isDirectory())return this.updateIno(t,vm.UNLINK,i),this.updateIno(t,vm.ADD_DIR,n),[vm.UNLINK,vm.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,vm.UNLINK_DIR,i),this.updateIno(t,vm.ADD,n),[vm.UNLINK_DIR,vm.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,vm.UNLINK_DIR,i),this.updateIno(t,vm.ADD_DIR,n),[vm.UNLINK_DIR,vm.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?pJt.FILE:pJt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},eVu=kUu;var tVu=class e extends Xjd.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(hk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(hk.CLOSE,n)),this._readyWait=new Promise(n=>this.on(hk.READY,n)),this._locker=new Kjd(this),this._roots=new Set,this._poller=new eVu,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Jj.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(hk.CLOSE))}error(t){if(this.isClosed())return!1;let r=Jj.lang.castError(t);return this.emit(hk.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(hk.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(hk.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Jj.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Jj.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Jj.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new $jd(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Jj.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(f=>f.handler===i&&(!f.filePath||f.filePath===n)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=vpi.default.dirname(t);for(let f=1;f<1/0;f++){if(this._watchers[u]?.find(o=>(f===1||o.options.recursive&&f<=(o.options.depth??VHr))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&WHr&&o.options.native!==!1)))return!0;if(!WHr)break;let c=vpi.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Jj.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,i,n))try{let p=!r.recursive||WHr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:uFa.default.watch(f,p),handler:i,options:r,folderPath:f,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||f)){let O={...r,ignoreInitial:!0,recursive:!1},j=vpi.default.dirname(f),A=f;await this.watchDirectories([j],O,i,A,l)}}catch(p){this.error(p)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||WHr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??VHr,f=r.limit??Eqn,[p]=await Jj.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,i,n,a);if(p.length){let o=Jj.fs.getDepth(t);for(let l of p){let m=Jj.fs.getDepth(l),O=Math.max(0,u-(m-o)),j={...r,depth:O};await this.watchDirectories([l],j,i,n,a||c)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(c,o)=>{o===t&&(p(),i())},u=new e(a),f=()=>{this._subwatchers.add(n),this.on(hk.CLOSE,p),u.watchFile(t,r,a)},p=()=>{this._subwatchers.delete(n),this.removeListener(hk.CLOSE,p),u.close()};return f()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=vpi.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new eVu,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Jj.lang.noop;if(this.pollerExists(t,r))return Jj.lang.noop;let n={...r,interval:r.pollingInterval??zjd},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(hk.CLOSE,f),uFa.default.watchFile(t,n,i)},f=()=>{this._pollers.delete(a),this.removeListener(hk.CLOSE,f),uFa.default.unwatchFile(t,i)};return Jj.lang.attempt(u),()=>Jj.lang.attempt(f)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Jj.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,p)=>p===u||!Jj.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=vpi.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Jj.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=vpi.default.dirname(t);return(await Jj.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Jj.lang.noop){if(Jj.lang.isFunction(t))return this.watch([],{},t);if(Jj.lang.isUndefined(t))return this.watch([],r,i);if(Jj.lang.isFunction(r))return this.watch(t,{},r);if(Jj.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Jj.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Jj.lang.noop&&this.on(hk.ALL,i),r.readdirMap=void 0,this.ready())}},Zjd=tVu;var vg1=bo(rwd(),1),bg1=bo(dVu(),1),gg1=bo(_Vu(),1),mg1=bo(OVu(),1),jVu=bo(kwd(),1);var wCd=bo(rRa(),1),CJt=require("fs/promises"),T8a=require("os"),sJu=bo(require("path"),1),DCd=bo(Pie(),1),SCd=bo(EAd(),1),cJu=bo(uJu(),1),pA1="etag",lJu="preview",_A1="bundle",fJu=".fern";function hA1(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu))}function q8a(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu),Pc.of(_A1))}function yA1(){return Sf(f_.of((0,T8a.homedir)()),Pc.of(fJu),Pc.of(lJu),Pc.of(pA1))}async function ECd({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,cJu.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new SCd.default.Parser().parseStringPromise(n),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],p=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=yA1();if(r){let z=await _h(c),C;if(z&&(t.debug("Reading existing ETag"),C=(await(0,CJt.readFile)(c)).toString()),C!=null&&C===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await DCd.default.dir({prefix:"fern"}),l=f_.of(o.path);t.debug(`Downloading docs preview bundle from ${sJu.default.join(e,p)}`);let m=await(0,cJu.fetcher)({url:`${sJu.default.join(e,p)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!m.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=Sf(l,Pc.of("output.zip")),j=m.body;if(j==null)return{type:"failure"};let A=Buffer.from(j);await(0,CJt.writeFile)(O,A),t.debug(`Wrote output.zip to ${O}`);let T=hA1();await _h(T)&&await(0,CJt.rm)(T,{recursive:!0}),await(0,CJt.mkdir)(T,{recursive:!0}),t.debug(`rm -rf ${T}`);let B=q8a();return await(0,CJt.mkdir)(B,{recursive:!0}),await(0,wCd.default)(O,B),await(0,CJt.writeFile)(c,f),t.debug(`Downloaded bundle to ${B}`),{type:"success"}}async function ACd({domain:e,project:t,context:r}){let i=t.docsWorkspaces,n=t.apiWorkspaces;if(i==null)throw new Error("No docs workspace found in project");let a=await Promise.all(n.map(async m=>await m.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),u=new dJu(r),f={},c=await new FIr(e,i,a,r,void 0,async m=>m.map(O=>{let j=pHt();return f[j]={type:"url",url:gc.Url(`/_local${vcu(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:j}}),async m=>u.addReferencedAPI(m)).resolve(),o=f9u({writeShape:c,files:{}}),l=p9u({dbShape:o.config});return{apis:u.getAPIsForDefinition(),config:l,files:{},filesV2:f,pages:o.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var dJu=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=pHt(),a=ETn(FSe({ir:t,snippetsConfig:r,playgroundConfig:i}),lU.ApiDefinitionId(n),new Kdi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=TTn(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}};var vA1={pages:{},apis:{},files:{},filesV2:{},config:{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 _Ju({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 C="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(C==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await ECd({bucketUrl:C,logger:i.logger,preferCached:!0})}catch(C){let N=q8a();if(C instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${C.message}`),await _h(N))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=qm(e.config._absolutePath),f=(0,pJu.default)(),p=TCd.default.createServer(f),c=new jVu.default({server:p}),o=new Set;function l(C){for(let N of o)N.send(JSON.stringify(C))}c.on("connection",function(N){o.add(N),N.on("close",function(){o.delete(N)})}),f.use((0,MCd.default)());let m=new URL(NIr(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),O=e,j,A=async()=>{i.logger.info("Reloading docs...");let C=Date.now();try{O=await t(),i.logger.info("Validating docs..."),await r(O);let N=await ACd({domain:`${m.host}${m.pathname}`,project:O,context:i});return i.logger.info(`Reload completed in ${Date.now()-C}ms`),N}catch(N){return j==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),N instanceof Error&&(i.logger.error(N.message),N instanceof Error&&N.stack&&i.logger.debug(`Stack Trace:
1977
1977
  ${N.stack}`)),j}};j=await A();let T=O.apiWorkspaces.flatMap(C=>C.getAbsoluteFilePaths()),B=a?f_.of(C8a.default.resolve(a)):q8a();new Zjd([u,...T],{recursive:!0,ignoreInitial:!0,debounce:1e3,renameDetection:!0}).on("all",async(C,N,U)=>{i.logger.info(Ic.dim(`[${C}] ${N}`)),l({version:1,type:"startReload"});let k=await A();k!=null&&(j=k),l({version:1,type:"finishReload"})}),f.post("/v2/registry/docs/load-with-url",async(C,N)=>{try{let U=j??vA1,k={baseUrl:{domain:m.host,basePath:m.pathname},definition:U,lightModeEnabled:U.config.colorsV3?.type!=="dark",orgId:gc.OrgId(e.config.organization)};N.send(k)}catch(U){i.logger.error("Error loading docs",U.message),N.status(500).send()}}),f.get(/^\/_local\/(.*)/,(C,N)=>N.sendFile(`/${C.params[0]}`)),f.get("/",(C,N,U)=>C.headers.upgrade==="websocket"?c.handleUpgrade(C,C.socket,Buffer.alloc(0),k=>{c.emit("connection",k,C)}):U()),f.use("/_next",pJu.default.static(C8a.default.join(B,"/_next"))),f.use("*",async(C,N)=>N.sendFile(C8a.default.join(B,"/[[...slug]].html"))),f.listen(n),i.logger.info(`Running server on http://localhost:${n}`),await new Promise(()=>{})}var QH={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function xx(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function a2e({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(GVt)&&t.exampleTypeReference?.(e,r);else if(UD(e))for(let i of Object.values(e))a2e({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)a2e({example:i,visitor:t,nodePath:r})}function K3t(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function qCd({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),LD(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":Mc,"display-name":Mc,availability:Mc,headers:i=>{CCd({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:Mc,auth:Mc,"path-parameters":i=>{ICn({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];bA1({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:Mc,transport:Mc,source:Mc})}function bA1({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=K3t(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),LD(t,{docs:xx(i,n),"display-name":Mc,availability:Mc,"base-path":Mc,path:Mc,idempotent:Mc,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{ICn({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let f=[...n,"request"];if(typeof u=="string"){a(u,f,{location:"requestReference"});return}LD(u,{name:Mc,docs:xx(i,f),"path-parameters":p=>{ICn({pathParameters:p,visitor:i,nodePath:[...f,"path-parameters"]})},"query-parameters":p=>{if(p!=null)for(let[c,o]of Object.entries(p)){let l=[...f,"query-parameters",c];i.queryParameter?.({queryParameterKey:c,queryParameter:o},l),typeof o=="string"?a(o,l):LD(o,{name:Mc,docs:xx(i,l),availability:Mc,type:m=>{a(m,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":Mc,audiences:Mc,encoding:Mc,default:Mc,validation:Mc})}},"content-type":Mc,headers:p=>{CCd({headers:p,visitor:i,nodePath:[...f,"headers"]})},body:p=>{if(p==null)return;let c=[...f,"body"];typeof p=="string"?a(p,c,{location:"requestReference"}):YB(p)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:p},c),LD(p,{extends:o=>{if(o==null)return;let l=typeof o=="string"?[o]:o;for(let m of l){let O=[...c,"extends",m];i.extension?.(m,O),a(m,O)}},properties:o=>{if(o!=null)for(let[l,m]of Object.entries(o)){let O=[...c,"properties",l];typeof m=="string"?a(m,O,{location:QH.InlinedRequestProperty}):LD(m,{name:Mc,docs:xx(i,O),availability:Mc,type:j=>{a(j,[...O,"type"],{location:QH.InlinedRequestProperty,_default:m.default,validation:m.validation})},"content-type":Mc,audiences:Mc,encoding:Mc,default:Mc,validation:Mc})}},"extra-properties":Mc})):(xx(i,c)(p.docs),a(p.type,c))}})},audiences:Mc,method:Mc,auth:Mc,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:QH.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:QH.StreamingResponse}))},response:u=>{if(u==null)return;let f=[...n,"response"];typeof u=="string"?a(u,f,{location:QH.Response}):LD(u,{docs:xx(i,f),type:p=>{a(p,[...f,"type"],{location:QH.Response})},property:Mc,"status-code":Mc})},errors:u=>{if(u!=null)for(let f of u){let p=[...n,"errors",typeof f=="string"?f:f.error];typeof f=="string"?i.errorReference?.(f,p):LD(f,{docs:xx(i,p),error:c=>{i.errorReference?.(c,[...p,"error"])}})}},examples:u=>{if(u!=null)for(let[f,p]of u.entries())gA1({nodePathForExample:[...n,{key:"examples",arrayIndex:f}],visitor:i,service:r,endpoint:t,example:p})},pagination:Mc,source:Mc,transport:Mc})}function gA1({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))a2e({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))a2e({example:o,visitor:t,nodePath:u});let f=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},f),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))a2e({example:o,visitor:t,nodePath:f});let p=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},p),n.request!=null&&a2e({example:n.request,visitor:t,nodePath:p});let c=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},c),n.response!=null&&yci(i,n.response,{body:o=>{o.body!=null&&a2e({example:o.body,visitor:t,nodePath:c}),o.error!=null&&t.errorReference?.(o.error,[...c,"error"])},stream:o=>{for(let l of o.stream)a2e({example:l,visitor:t,nodePath:c})},events:o=>{for(let{data:l}of o.stream)a2e({example:l,visitor:t,nodePath:c})}}),n["code-samples"]!=null)for(let[o,l]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:l},[...e,{key:"code-samples",arrayIndex:o}])}function ICn({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=K3t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),_8i(a)?typeof a=="string"?t.variableReference?.(a,u):LD(a,{docs:xx(t,u),variable:f=>t.variableReference?.(f,[...u,"variable"]),availability:Mc}):typeof a=="string"?i(a,u):LD(a,{docs:xx(t,u),type:f=>{i(f,[...u,"type"],{_default:a.default,validation:a.validation})},availability:Mc,encoding:Mc,default:Mc,validation:Mc,name:Mc,audiences:Mc})}}function CCd({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=K3t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):LD(a,{name:Mc,availability:Mc,type:f=>{i(f,u,{_default:a.default,validation:a.validation})},docs:xx(t,u),audiences:Mc,encoding:Mc,env:Mc,default:Mc,validation:Mc})}}function xCd({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),hJu({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function hJu({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=K3t(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[f,p]of u.entries()){let c=[...i,{key:"examples",arrayIndex:f}];r.exampleType?.({typeName:e,typeDeclaration:t,example:p},c),a2e({example:p.value,nodePath:c,visitor:r})}};f4(t,{alias:u=>{typeof u=="string"?n(u,i):LD(u,{type:f=>{n(f,[...i,"type"])},docs:xx(r,i),availability:Mc,audiences:Mc,examples:a,validation:Mc,encoding:Mc,source:Mc,inline:Mc})},object:u=>{LD(u,{docs:xx(r,i),extends:f=>{if(f==null)return;let p=typeof f=="string"?[f]:f;for(let c of p){let o=[...i,"extends",c];r.extension?.(c,o),n(c,o)}},properties:f=>{if(f!=null)for(let[p,c]of Object.entries(f)){let o=[...i,"properties",p];typeof c=="string"?n(c,o):LD(c,{name:Mc,docs:xx(r,o),availability:Mc,type:l=>{n(l,[...o,"type"],{_default:c.default,validation:c.validation})},audiences:Mc,encoding:Mc,default:Mc,validation:Mc})}},"extra-properties":Mc,availability:Mc,audiences:Mc,encoding:Mc,source:Mc,examples:a,inline:Mc})},discriminatedUnion:u=>{LD(u,{docs:xx(r,i),discriminant:Mc,extends:f=>{if(f==null)return;let p=typeof f=="string"?[f]:f;for(let c of p){let o=[...i,"extends",c];r.extension?.(c,o),n(c,o)}},union:f=>{for(let[p,c]of Object.entries(f)){let o=[...i,"union",p];typeof c=="string"?n(c,o):LD(c,{docs:xx(r,o),name:Mc,key:Mc,type:l=>{typeof l=="string"&&n(l,[...i,"type"])},"display-name":Mc,availability:Mc})}},"base-properties":Mc,availability:Mc,audiences:Mc,encoding:Mc,source:Mc,examples:a,inline:Mc})},undiscriminatedUnion:u=>{LD(u,{docs:xx(r,i),discriminated:Mc,union:f=>{for(let[p,c]of f.entries()){let o=[...i,`union[${p}]`];typeof c!="string"&&LD(c,{docs:xx(r,o),type:l=>{n(l,[...i,"type"])},"display-name":Mc})}},availability:Mc,audiences:Mc,encoding:Mc,source:Mc,examples:a,inline:Mc})},enum:u=>{LD(u,{docs:xx(r,i),enum:f=>{for(let p of f){let c=[...i,typeof p=="string"?p:p.name??p.value];typeof p!="string"&&LD(p,{docs:xx(r,c),name:Mc,value:Mc,casing:Mc})}},availability:Mc,audiences:Mc,default:Mc,encoding:Mc,source:Mc,examples:a,inline:Mc})}})}function BCd({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),mA1({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function mA1({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=K3t(r);typeof t=="string"?n(t,i):LD(t,{docs:xx(r,i),"status-code":Mc,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):hJu({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let f=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},f)}}})}function ICd({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function zCd({webhook:e,visitor:t,nodePathForWebhook:r}){let i=K3t(t);LD(e,{"display-name":Mc,method:Mc,examples:Mc,headers:n=>{OA1({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(PA1(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),LD(n,{name:Mc,extends:f=>{if(f==null)return;let p=typeof f=="string"?[f]:f;for(let c of p){let o=[...u,"extends",c];t.extension?.(c,o),i(c,o)}},properties:f=>{if(f!=null)for(let[p,c]of Object.entries(f)){let o=[...u,"properties",p];typeof c=="string"?i(c,o,{location:QH.InlinedRequestProperty}):LD(c,{name:Mc,docs:xx(t,o),availability:Mc,type:l=>{i(l,[...o,"type"],{_default:c.default,validation:c.validation,location:QH.InlinedRequestProperty})},audiences:Mc,encoding:Mc,default:Mc,validation:Mc})}}})},audiences:Mc,availability:Mc,docs:xx(t,r)})}function OA1({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=K3t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):LD(a,{name:Mc,availability:Mc,type:f=>{i(f,u,{_default:a.default,validation:a.validation})},docs:xx(t,u),audiences:Mc,encoding:Mc,env:Mc,default:Mc,validation:Mc})}}function PA1(e){return e.type!=null}function GH(e,t){LD(e,{docs:xx(t,[]),imports:r=>{ICd({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{xCd({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&qCd({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))zCd({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:Mc,errors:r=>{BCd({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function yJu(e,t){LD(e,{docs:Mc,imports:Mc,types:Mc,service:Mc,webhooks:Mc,errors:Mc,channel:Mc,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function vJu(e,t){t.file?.(e,[]),LD(e,{version:Mc,name:Mc,"default-url":Mc,"display-name":Mc,imports:Mc,auth:Mc,"idempotency-headers":Mc,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{xbu(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:Mc,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Mc,headers:Mc,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Mc,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":Mc,"path-parameters":r=>{ICn({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var x8a=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function NCd({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(f,p)=>{for(let c of r){let o=c.definitionFile?.[a];if(o!=null){let l=o(f,{relativeFilepath:e,contents:t});i(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:p,message:m.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function FCd({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(f,p)=>{for(let c of r){let o=c.packageMarker?.[a];if(o!=null){let l=o(f,{relativeFilepath:e,contents:t});i(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:p,message:m.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function RCd({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(f,p)=>{for(let c of r){let o=c.rootApiFile?.[a];if(o!=null){let l=o(f,{relativeFilepath:e,contents:t});i(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:p,message:m.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var bJu={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(uIr(e.definition)),r=new Set;return t.forEach(i=>{let n=Sf(e.definition.absoluteFilePath,Pc.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],f=Sf(e.definition.absoluteFilePath,qm(a),Pc.of(n));return r.has(f)||u.push({severity:"error",message:`Import ${Ic.bold(i)} points to non-existent path ${Ic.bold(n)}.`}),u}}}}};function B8a(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(p8i(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var gJu={name:"matching-environment-urls",create:({workspace:e})=>{let t=B8a(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"error",message:`Environment ${r} is missing URL for ${Ic.bold(u)}`})};return t2r(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let f of t)u.urls[f]==null&&a(f)}}),n}}}}};var mJu={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=jA1(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=THr({referencedIn:i,importPath:Pc.of(r)});return n.filter(({chainWithoutStartingFilepath:f})=>f.length===0||f[0]===a).map(f=>({severity:"error",message:f.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[f.startingFilepath,...f.chainWithoutStartingFilepath,f.startingFilepath].join(" -> ")}`}))}}}}};function jA1(e){let t={};for(let r of B7t(e))t[r]=LCd(r,[r],e);return t}function LCd(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=THr({referencedIn:e,importPath:Pc.of(a)});t.includes(u)?t[0]===u&&t[0]===wA1(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...LCd(u,[...t,u],r))}return i}function wA1(e){return e.reduce((t,r)=>r<t?r:t)}var TM=oJt({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var I8a=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new MA(t)}isTypeComplex(t,r){let i=fO({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:TM,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:sc(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:sc(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),uUr(t.declaration))return!0;if(A6t(t.declaration))return!1;if(YE(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(h8i(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}sc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return F3t({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:sc(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!0;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:sc(t)}}};var OJu={name:"no-complex-query-params",create:({workspace:e})=>{let t=new I8a(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"error",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var PJu={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===a4a?[{severity:"error",message:`Path parameter ${Ic.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function zCn({service:e,endpoint:t}){return e["base-path"]+t.path}var z8a=class{root=new jJu;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return zCn({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},jJu=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var wJu={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new z8a;return O4(e,(r,i)=>{GH(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${zCn({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(f=>` - ${f.relativeFilepath} -> ${f.endpointId} ${Ic.dim(zCn({service:f.service,endpoint:f.endpoint}))}`)].join(`
1978
1978
  `)}]}}}}};var DJu={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:i,relativeFilepath:n})=>{let a=DA1({endpoint:t,service:r,relativeFilepath:n,definitionFile:i,workspace:e}),u=[];for(let[f,p]of Object.entries(a))p.length<=1||u.push({severity:"error",message:`Multiple request properties have the name ${Ic.bold(f)}. This is not suitable for code generation. Use the "name" property to deconflict.
1979
1979
  `+p.map(c=>` - ${SA1(c)}`).join(`