fern-api 0.45.0-rc26 → 0.45.0-rc28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +5 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1818,7 +1818,7 @@ ${l.indent}`:""}${ytl(o)}:${f.indent?" ":""}`;return u=!1,c=!0,f.objectItem=void
|
|
|
1818
1818
|
`}),r.replaceAll(/\n$/g,"")}function o21(e){return e?nl.green(w8r.radioOn):w8r.radioOff}var Kga=Xo(dDe(),1);function TOf(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var svi=class extends LF{_run(t){this.done=t;let r=FH(this.rl),n=r.line.pipe((0,Kga.map)(this.filterInput.bind(this))),i=this.handleSubmitEvents(n);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,Kga.takeUntil)(i.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),n="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(n=`
|
|
1819
1819
|
`+nl.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?nl.cyan(TOf(t,this.opt.mask)):nl.italic.dim("[hidden]"):this.opt.mask?TOf(t,this.opt.mask):nl.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 n1f=Xo(r1f(),1),i1f=Xo(dDe(),1);var bvi=class extends LF{_run(t){this.done=t,this.editorResult=new i1f.Subject;let r=FH(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?nl.dim("Received"):nl.dim("Press <enter> to launch your preferred editor."),t&&(r=nl.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),(0,n1f.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 d1f=Xo(u1f(),1);var l1f=Xo(require("readline"),1),f1f=Xo(c1f(),1),Brn=class{constructor(t){this.rl||=l1f.default.createInterface(Y21(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 Y21(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new f1f.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var gvi=class extends Brn{constructor(t={}){super(t),this.log=(0,d1f.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return evi(this.rl,this.bottomBar.split(`
|
|
1820
1820
|
`).length),this}updateBottomBar(t){return evi(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+`
|
|
1821
|
-
`}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&&Qga(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var P1f=Xo(h1f(),1),w1f=Xo(Jhu(),1),j1f=Xo(m1f(),1),$C=Xo(dDe(),1),D1f=Xo(s0i(),1);var hma=Xo(dDe(),1),O1f=Xo(s0i(),1),yma=function(e,t,r){return typeof e[t]!="function"?(0,hma.of)(e):(0,hma.from)((0,O1f.default)(e[t])(r).then(n=>(e[t]=n,e)))};var mvi={isPlainObject:P1f.default,set:j1f.default,get:w1f.default},d3n=class extends Brn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=mvi.isPlainObject(r)?{...r}:{},mvi.isPlainObject(t)&&(t=Object.values(t).every(i=>mvi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,$C.from)(t):t;return this.process=n.pipe((0,$C.concatMap)(this.processQuestion.bind(this)),(0,$C.publish)()),this.process.connect(),this.process.pipe((0,$C.reduce)((i,a)=>(mvi.set(i,a.name,a.answer),i),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,$C.defer)(()=>(0,$C.of)(t).pipe((0,$C.concatMap)(this.setDefaultType.bind(this)),(0,$C.concatMap)(this.filterIfRunnable.bind(this)),(0,$C.concatMap)(()=>yma(t,"message",this.answers)),(0,$C.concatMap)(()=>yma(t,"default",this.answers)),(0,$C.concatMap)(()=>yma(t,"choices",this.answers)),(0,$C.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,$C.defer)(()=>(0,$C.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,$C.defer)(()=>(0,$C.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&mvi.get(this.answers,t.name)!==void 0)return(0,$C.empty)();if(t.when===!1)return(0,$C.empty)();if(typeof t.when!="function")return(0,$C.of)(t);let{answers:r}=this;return(0,$C.defer)(()=>(0,$C.from)((0,D1f.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,$C.filter)(n=>n!=null)))}};function S1f(e){let t=function(r,n){let i;try{i=new d3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",rvi),this.registerPrompt("input",Arn),this.registerPrompt("number",nvi),this.registerPrompt("confirm",ivi),this.registerPrompt("rawlist",avi),this.registerPrompt("expand",ovi),this.registerPrompt("checkbox",uvi),this.registerPrompt("password",svi),this.registerPrompt("editor",bvi)},t.restoreDefaultPrompts(),t}var W0u=S1f();function _q1(e,t){W0u.registerPrompt(e,t)}function hq1(){W0u.restoreDefaultPrompts()}var yq1={prompt:W0u,ui:{BottomBar:gvi,Prompt:d3n},createPromptModule:S1f,registerPrompt:_q1,restoreDefaultPrompts:hq1,Separator:rae},vma=yq1;var B1f=Xo(E1f()),N1f=Xo(nlu()),Q0u=function(e,t){return Q0u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},Q0u(e,t)};function p3n(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Q0u(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var Gg=function(){return Gg=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Gg.apply(this,arguments)};function vq1(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function gC(e,t,r,n){function i(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function f(o){try{c(n.next(o))}catch(l){u(l)}}function d(o){try{c(n.throw(o))}catch(l){u(l)}}function c(o){o.done?a(o.value):i(o.value).then(f,d)}c((n=n.apply(e,t||[])).next())})}function mC(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(c){return function(o){return d([c,o])}}function d(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(o){c=[6,o],i=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function z1f(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,a;n<i;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var J0u="3.1.2",pw;(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"})(pw||(pw={}));function bq1(e,t){if(!e)throw new Error(t)}function gq1(e){return e?.replace(/\/+$/,"")}function mq1(e,t){return t===void 0&&(t={}),gC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return mC(this,function(g){switch(g.label){case 0:r=t.retryCount,n=r===void 0?3:r,i=t.retryDelay,a=i===void 0?5e3:i,u=t.retryCheck,f=u===void 0?function(){return!0}:u,d=null,c=0,g.label=1;case 1:return c<n+1?c>0?[4,new Promise(function(O){return setTimeout(O,a)})]:[3,3]:[3,7];case 2:g.sent(),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,e()];case 4:return o=g.sent(),[2,o];case 5:if(l=g.sent(),d=l,!f(l))throw l;return[3,6];case 6:return c++,[3,1];case 7:throw d}})})}function G0u(e){var t=new Date().getTime(),r=e&&e.performance&&e.performance.now&&e.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var i=Math.random()*16;return t>0?(i=(t+i)%16|0,t=Math.floor(t/16)):(i=(r+i)%16|0,r=Math.floor(r/16)),(n==="x"?i:i&3|8).toString(16)})}function Oq1(){return new Date().getTime()}function A1f(){return new Date().toISOString()}function R1f(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Pvi=String.fromCharCode,M1f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bma={};function Pq1(e,t){if(!bma[e]){bma[e]={};for(var r=0;r<e.length;r++)bma[e][e.charAt(r)]=r}return bma[e][t]}var wvi={compressToBase64:function(e){if(e==null)return"";var t=wvi._compress(e,6,function(r){return M1f.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:wvi._decompress(e.length,32,function(t){return Pq1(M1f,e.charAt(t))})},compress:function(e){return wvi._compress(e,16,function(t){return Pvi(t)})},_compress:function(e,t,r){if(e==null)return"";var n={},i={},a=[],u,f,d="",c="",o="",l=2,g=3,O=2,P=0,j=0,M;for(M=0;M<e.length;M+=1)if(d=e.charAt(M),Object.prototype.hasOwnProperty.call(n,d)||(n[d]=g++,i[d]=!0),c=o+d,Object.prototype.hasOwnProperty.call(n,c))o=c;else{if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),n[c]=g++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;for(;;)if(P=P<<1,j==t-1){a.push(r(P));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:wvi._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){var n=[],i=[],a={val:r(0),position:t,index:1},u=4,f=4,d=3,c="",o,l,g,O,P,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,P=Math.pow(2,2),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Pvi(g);break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Pvi(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,P=Math.pow(2,d),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(M=g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Pvi(g),M=f-1,u--;break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Pvi(g),M=f-1,u--;break;case 2:return i.join("")}if(u==0&&(u=Math.pow(2,d),d++),n[M])c=n[M];else if(M===f)c=l+l.charAt(0);else return null;i.push(c),n[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,d),d++)}}},wq1=function(){function e(){this.events={},this.events={}}return e.prototype.on=function(t,r){var n=this;return this.events[t]||(this.events[t]=[]),this.events[t].push(r),function(){n.events[t]=n.events[t].filter(function(i){return i!==r})}},e.prototype.emit=function(t,r){for(var n=0,i=this.events[t]||[];n<i.length;n++){var a=i[n];a(r)}for(var u=0,f=this.events["*"]||[];u<f.length;u++){var a=f[u];a(t,r)}},e}(),jq1=function(e){p3n(t,e);function t(r){var n=e.call(this,"HTTP error while fetching PostHog: "+r.status)||this;return n.response=r,n.name="PostHogFetchHttpError",n}return t}(Error),Dq1=function(e){p3n(t,e);function t(r){var n=e.call(this,"Network error while fetching PostHog",r instanceof Error?{cause:r}:{})||this;return n.error=r,n.name="PostHogFetchNetworkError",n}return t}(Error);function x1f(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var F1f=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new wq1,bq1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=gq1(r?.host||"https://app.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.flushInterval=(n=r?.flushInterval)!==null&&n!==void 0?n:1e4,this.captureMode=r?.captureMode||"form",this._optoutOverride=r?.enable===!1,this._retryOptions={retryCount:(i=r?.fetchRetryCount)!==null&&i!==void 0?i:3,retryDelay:(a=r?.fetchRetryDelay)!==null&&a!==void 0?a:3e3,retryCheck:x1f},this.requestTimeout=(u=r?.requestTimeout)!==null&&u!==void 0?u:1e4,this.disableGeoip=(f=r?.disableGeoip)!==null&&f!==void 0?f:!0}return e.prototype.getCommonEventProperties=function(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}},Object.defineProperty(e.prototype,"optedOut",{get:function(){var t,r;return(r=(t=this.getPersistedProperty(pw.OptedOut))!==null&&t!==void 0?t:this._optoutOverride)!==null&&r!==void 0?r:!1},enumerable:!1,configurable:!0}),e.prototype.optIn=function(){this.setPersistedProperty(pw.OptedOut,!1)},e.prototype.optOut=function(){this.setPersistedProperty(pw.OptedOut,!0)},e.prototype.on=function(t,r){return this._events.on(t,r)},e.prototype.debug=function(t){var r;t===void 0&&(t=!0),(r=this.removeDebugCallback)===null||r===void 0||r.call(this),this.debugMode=t,t&&(this.removeDebugCallback=this.on("*",function(n,i){return console.log("PostHog Debug",n,i)}))},e.prototype.buildPayload=function(t){return{distinct_id:t.distinct_id,event:t.event,properties:Gg(Gg({},t.properties||{}),this.getCommonEventProperties())}},e.prototype.identifyStateless=function(t,r,n){var i=Gg({},this.buildPayload({distinct_id:t,event:"$identify",properties:r}));return this.enqueue("identify",i,n),this},e.prototype.captureStateless=function(t,r,n,i){var a=this.buildPayload({distinct_id:t,event:r,properties:n});return this.enqueue("capture",a,i),this},e.prototype.aliasStateless=function(t,r,n,i){var a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:Gg(Gg({},n||{}),{distinct_id:r,alias:t})});return this.enqueue("alias",a,i),this},e.prototype.groupIdentifyStateless=function(t,r,n,i,a,u){var f=this.buildPayload({distinct_id:a||"$".concat(t,"_").concat(r),event:"$groupidentify",properties:Gg({$group_type:t,$group_key:r,$group_set:n||{}},u||{})});return this.enqueue("capture",f,i),this},e.prototype.getDecide=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f;return mC(this,function(d){return u="".concat(this.host,"/decide/?v=3"),f={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gg({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i},a))},[2,this.fetchWithRetry(u,f).then(function(c){return c.json()}).catch(function(c){console.error("Error fetching feature flags",c)})]})})},e.prototype.getFeatureFlagStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0&&(d=!1),[2,d]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagPayloadsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0?[2,null]:[2,this._parsePayload(d)]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f=this;return mC(this,function(d){switch(d.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return u=d.sent().payloads,u?[2,Object.fromEntries(Object.entries(u).map(function(c){var o=c[0],l=c[1];return[o,f._parsePayload(l)]}))]:[2,u]}})})},e.prototype._parsePayload=function(t){try{return JSON.parse(t)}catch{return t}},e.prototype.getFeatureFlagsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return[2,u.sent().flags]}})})},e.prototype.getFeatureFlagsAndPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f,d,c;return mC(this,function(o){switch(o.label){case 0:return u={},(a??this.disableGeoip)&&(u.geoip_disable=!0),[4,this.getDecide(t,r,n,i,u)];case 1:return f=o.sent(),d=f?.featureFlags,c=f?.featureFlagPayloads,[2,{flags:d,payloads:c}]}})})},e.prototype.enqueue=function(t,r,n){var i=this,a;if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.enable()");return}var u=Gg(Gg({},r),{type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:A1f()}),f=(a=n?.disableGeoip)!==null&&a!==void 0?a:this.disableGeoip;f&&(u.properties||(u.properties={}),u.properties.$geoip_disable=!0),u.distinctId&&(u.distinct_id=u.distinctId,delete u.distinctId);var d=this.getPersistedProperty(pw.Queue)||[];d.push({message:u}),this.setPersistedProperty(pw.Queue,d),this._events.emit(t,u),d.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=R1f(function(){return i.flush()},this.flushInterval))},e.prototype.flushAsync=function(){var t=this;return new Promise(function(r,n){t.flush(function(i,a){return i?n(i):r(a)})})},e.prototype.flush=function(t){var r=this;this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);var n=this.getPersistedProperty(pw.Queue)||[];if(!n.length)return t?.();var i=n.splice(0,this.flushAt);this.setPersistedProperty(pw.Queue,n);var a=i.map(function(O){return O.message}),u={api_key:this.apiKey,batch:a,sent_at:A1f()},f=G0u(),d=function(O){O&&r._events.emit("error",O),t?.(O,a),delete r.pendingPromises[f],r._events.emit("flush",a)};this.getCustomUserAgent();var c=JSON.stringify(u),o=this.captureMode==="form"?"".concat(this.host,"/e/?ip=1&_=").concat(Oq1(),"&v=").concat(this.getLibraryVersion()):"".concat(this.host,"/batch/"),l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"data=".concat(encodeURIComponent(wvi.compressToBase64(c)),"&compression=lz64")}:{method:"POST",headers:{"Content-Type":"application/json"},body:c},g=this.fetchWithRetry(o,l);this.pendingPromises[f]=g,g.then(function(){return d()}).catch(function(O){d(O)})},e.prototype.fetchWithRetry=function(t,r,n){var i,a;return gC(this,void 0,void 0,function(){var u=this;return mC(this,function(f){switch(f.label){case 0:return(i=(a=AbortSignal).timeout)!==null&&i!==void 0||(a.timeout=function(c){var o=new AbortController;return setTimeout(function(){return o.abort()},c),o.signal}),[4,mq1(function(){return gC(u,void 0,void 0,function(){var d,c;return mC(this,function(o){switch(o.label){case 0:d=null,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.fetch(t,Gg({signal:AbortSignal.timeout(this.requestTimeout)},r))];case 2:return d=o.sent(),[3,4];case 3:throw c=o.sent(),new Dq1(c);case 4:if(d.status<200||d.status>=400)throw new jq1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return gC(this,void 0,void 0,function(){var t;return mC(this,function(r){switch(r.label){case 0:clearTimeout(this._flushTimer),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.flushAsync()];case 2:return r.sent(),[4,Promise.all(Object.values(this.pendingPromises).map(function(n){return n.catch(function(){})}))];case 3:return r.sent(),[3,5];case 4:if(t=r.sent(),!x1f(t))throw t;return console.error("Error while shutting down PostHog",t),[3,5];case 5:return[2]}})})},e.prototype.shutdown=function(){this.shutdownAsync()},e}();(function(e){p3n(t,e);function t(r,n){var i=this,a,u,f,d=(a=n?.disableGeoip)!==null&&a!==void 0?a:!1;return i=e.call(this,r,Gg(Gg({},n),{disableGeoip:d}))||this,i.flagCallReported={},i.sessionProps={},i.sendFeatureFlagEvent=(u=n?.sendFeatureFlagEvent)!==null&&u!==void 0?u:!0,i._sessionExpirationTimeSeconds=(f=n?.sessionExpirationTimeSeconds)!==null&&f!==void 0?f:1800,i}return t.prototype.setupBootstrap=function(r){var n,i,a,u;if(!((n=r?.bootstrap)===null||n===void 0)&&n.distinctId&&(!((i=r?.bootstrap)===null||i===void 0)&&i.isIdentifiedId?this.setPersistedProperty(pw.DistinctId,r.bootstrap.distinctId):this.setPersistedProperty(pw.AnonymousId,r.bootstrap.distinctId)),!((a=r?.bootstrap)===null||a===void 0)&&a.featureFlags){var f=Object.keys(((u=r.bootstrap)===null||u===void 0?void 0:u.featureFlags)||{}).filter(function(d){var c,o;return!!(!((o=(c=r.bootstrap)===null||c===void 0?void 0:c.featureFlags)===null||o===void 0)&&o[d])}).reduce(function(d,c){var o,l;return d[c]=((l=(o=r.bootstrap)===null||o===void 0?void 0:o.featureFlags)===null||l===void 0?void 0:l[c])||!1,d},{});this.setKnownFeatureFlags(f),r?.bootstrap.featureFlagPayloads&&this.setKnownFeatureFlagPayloads(r?.bootstrap.featureFlagPayloads)}},Object.defineProperty(t.prototype,"props",{get:function(){return this._props||(this._props=this.getPersistedProperty(pw.Props)),this._props||{}},set:function(r){this._props=r},enumerable:!1,configurable:!0}),t.prototype.clearProps=function(){this.props=void 0,this.sessionProps={}},t.prototype.on=function(r,n){return this._events.on(r,n)},t.prototype.reset=function(r){var n=z1f([pw.Queue],r||[],!0);this.clearProps();for(var i=0,a=Object.keys(pw);i<a.length;i++){var u=a[i];n.includes(pw[u])||this.setPersistedProperty(pw[u],null)}},t.prototype.getCommonEventProperties=function(){var r=this.getFeatureFlags(),n={};if(r)for(var i=0,a=Object.entries(r);i<a.length;i++){var u=a[i],f=u[0],d=u[1];n["$feature/".concat(f)]=d}return Gg(Gg({$active_feature_flags:r?Object.keys(r):void 0},n),e.prototype.getCommonEventProperties.call(this))},t.prototype.enrichProperties=function(r){return Gg(Gg(Gg(Gg(Gg({},this.props),this.sessionProps),r||{}),this.getCommonEventProperties()),{$session_id:this.getSessionId()})},t.prototype.getSessionId=function(){var r=this.getPersistedProperty(pw.SessionId),n=this.getPersistedProperty(pw.SessionLastTimestamp)||0;return(!r||Date.now()-n>this._sessionExpirationTimeSeconds*1e3)&&(r=G0u(globalThis),this.setPersistedProperty(pw.SessionId,r)),this.setPersistedProperty(pw.SessionLastTimestamp,Date.now()),r},t.prototype.resetSessionId=function(){this.setPersistedProperty(pw.SessionId,null)},t.prototype.getAnonymousId=function(){var r=this.getPersistedProperty(pw.AnonymousId);return r||(r=G0u(globalThis),this.setPersistedProperty(pw.AnonymousId,r)),r},t.prototype.getDistinctId=function(){return this.getPersistedProperty(pw.DistinctId)||this.getAnonymousId()},t.prototype.unregister=function(r){delete this.props[r],this.setPersistedProperty(pw.Props,this.props)},t.prototype.register=function(r){this.props=Gg(Gg({},this.props),r),this.setPersistedProperty(pw.Props,this.props)},t.prototype.registerForSession=function(r){this.sessionProps=Gg(Gg({},this.sessionProps),r)},t.prototype.unregisterForSession=function(r){delete this.sessionProps[r]},t.prototype.identify=function(r,n,i){var a=this.getDistinctId();r=r||a,n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(Gg(Gg({},n),{$anon_distinct_id:this.getAnonymousId(),$set:n}));return r!==a&&(this.setPersistedProperty(pw.AnonymousId,a),this.setPersistedProperty(pw.DistinctId,r),this.reloadFeatureFlags()),e.prototype.identifyStateless.call(this,r,u,i),this},t.prototype.capture=function(r,n,i){var a=this.getDistinctId();n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(n);return e.prototype.captureStateless.call(this,a,r,u,i),this},t.prototype.alias=function(r){var n=this.getDistinctId(),i=this.enrichProperties({});return e.prototype.aliasStateless.call(this,r,n,i),this},t.prototype.autocapture=function(r,n,i,a){i===void 0&&(i={});var u=this.getDistinctId(),f={distinct_id:u,event:"$autocapture",properties:Gg(Gg({},this.enrichProperties(i)),{$event_type:r,$elements:n})};return this.enqueue("autocapture",f,a),this},t.prototype.groups=function(r){var n=this.props.$groups||{};return this.register({$groups:Gg(Gg({},n),r)}),Object.keys(r).find(function(i){return n[i]!==r[i]})&&this.reloadFeatureFlags(),this},t.prototype.group=function(r,n,i,a){var u;return this.groups((u={},u[r]=n,u)),i&&this.groupIdentify(r,n,i,a),this},t.prototype.groupIdentify=function(r,n,i,a){var u=this.getDistinctId(),f=this.enrichProperties({});return e.prototype.groupIdentifyStateless.call(this,r,n,i,a,u,f),this},t.prototype.personProperties=function(r){var n=this.getPersistedProperty(pw.PersonProperties)||{};return this.setPersistedProperty(pw.PersonProperties,Gg(Gg({},n),r)),this},t.prototype.groupProperties=function(r){var n=this.getPersistedProperty(pw.GroupProperties)||{};return Object.keys(n).length!==0&&Object.keys(n).forEach(function(i){n[i]=Gg(Gg({},n[i]),r[i]),delete r[i]}),this.setPersistedProperty(pw.GroupProperties,Gg(Gg({},n),r)),this},t.prototype.decideAsync=function(r){return r===void 0&&(r=!0),this._decideResponsePromise?this._decideResponsePromise:this._decideAsync(r)},t.prototype._decideAsync=function(r){return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return mC(this,function(c){return n=this.getDistinctId(),i=this.props.$groups||{},a=this.getPersistedProperty(pw.PersonProperties)||{},u=this.getPersistedProperty(pw.GroupProperties)||{},f={$anon_distinct_id:r?this.getAnonymousId():void 0},this._decideResponsePromise=e.prototype.getDecide.call(this,n,i,a,u,f).then(function(o){if(o?.featureFlags){var l=o.featureFlags,g=o.featureFlagPayloads;if(o.errorsWhileComputingFlags){var O=d.getPersistedProperty(pw.FeatureFlags),P=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},P),o.featureFlagPayloads)}d.setKnownFeatureFlags(l),d.setKnownFeatureFlagPayloads(g)}return o}).finally(function(){d._decideResponsePromise=void 0}),[2,this._decideResponsePromise]})})},t.prototype.setKnownFeatureFlags=function(r){this.setPersistedProperty(pw.FeatureFlags,r),this._events.emit("featureflags",r)},t.prototype.setKnownFeatureFlagPayloads=function(r){this.setPersistedProperty(pw.FeatureFlagPayloads,r)},t.prototype.getFeatureFlag=function(r){var n=this.getFeatureFlags();if(n){var i=n[r];return i===void 0&&(i=!1),this.sendFeatureFlagEvent&&!this.flagCallReported[r]&&(this.flagCallReported[r]=!0,this.capture("$feature_flag_called",{$feature_flag:r,$feature_flag_response:i})),i}},t.prototype.getFeatureFlagPayload=function(r){var n=this.getFeatureFlagPayloads();if(n){var i=n[r];return i===void 0?null:this._parsePayload(i)}},t.prototype.getFeatureFlagPayloads=function(){var r=this,n=this.getPersistedProperty(pw.FeatureFlagPayloads);return n&&Object.fromEntries(Object.entries(n).map(function(i){var a=i[0],u=i[1];return[a,r._parsePayload(u)]}))},t.prototype.getFeatureFlags=function(){var r=this.getPersistedProperty(pw.FeatureFlags),n=this.getPersistedProperty(pw.OverrideFeatureFlags);if(!n)return r;r=r||{};for(var i in n)n[i]?r[i]=n[i]:delete r[i];return r},t.prototype.getFeatureFlagsAndPayloads=function(){var r=this.getFeatureFlags(),n=this.getFeatureFlagPayloads();return{flags:r,payloads:n}},t.prototype.isFeatureEnabled=function(r){var n=this.getFeatureFlag(r);if(n!==void 0)return!!n},t.prototype.reloadFeatureFlags=function(r){this.decideAsync().then(function(n){r?.(void 0,n?.featureFlags)}).catch(function(n){r?.(n,void 0),r||console.log("[PostHog] Error reloading feature flags",n)})},t.prototype.reloadFeatureFlagsAsync=function(r){var n;return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){return mC(this,function(i){switch(i.label){case 0:return[4,this.decideAsync(r)];case 1:return[2,(n=i.sent())===null||n===void 0?void 0:n.featureFlags]}})})},t.prototype.onFeatureFlags=function(r){var n=this;return this.on("featureflags",function(){return gC(n,void 0,void 0,function(){var i;return mC(this,function(a){return i=this.getFeatureFlags(),i&&r(i),[2]})})})},t.prototype.onFeatureFlag=function(r,n){var i=this;return this.on("featureflags",function(){return gC(i,void 0,void 0,function(){var a;return mC(this,function(u){return a=this.getFeatureFlag(r),a!==void 0&&n(a),[2]})})})},t.prototype.overrideFeatureFlag=function(r){return r===null?this.setPersistedProperty(pw.OverrideFeatureFlags,null):this.setPersistedProperty(pw.OverrideFeatureFlags,r)},t})(F1f);var Sq1=function(){function e(){this._memoryStorage={}}return e.prototype.getProperty=function(t){return this._memoryStorage[t]},e.prototype.setProperty=function(t,r){this._memoryStorage[t]=r!==null?r:void 0},e}(),L1f=function(e,t){return gC(void 0,void 0,void 0,function(){var r;return mC(this,function(n){switch(n.label){case 0:return[4,N1f.default.request({url:e,headers:t.headers,method:t.method.toLowerCase(),data:t.body,signal:t.signal,validateStatus:function(){return!0}})];case 1:return r=n.sent(),[2,{status:r.status,text:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})},json:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})}}]}})})},Eq1=1152921504606847e3,T1f=function(e){p3n(t,e);function t(r){var n=e.call(this)||this;return Error.captureStackTrace(n,n.constructor),n.name="ClientError",n.message=r,Object.setPrototypeOf(n,t.prototype),n}return t}(Error),nk=function(e){p3n(t,e);function t(r){var n=e.call(this,r)||this;return n.name=n.constructor.name,Error.captureStackTrace(n,n.constructor),Object.setPrototypeOf(n,t.prototype),n}return t}(Error),Aq1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=vq1(t,["pollingInterval","personalApiKey","projectApiKey","timeout","host"]);this.debugMode=!1,this.pollingInterval=r,this.personalApiKey=n,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=a,this.projectApiKey=i,this.host=u,this.poller=void 0,this.fetch=f.fetch||L1f,this.loadFeatureFlags()}return e.prototype.debug=function(t){t===void 0&&(t=!0),this.debugMode=t},e.prototype.getFeatureFlag=function(t,r,n,i,a){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f,d,c,o;return mC(this,function(l){switch(l.label){case 0:return[4,this.loadFeatureFlags()];case 1:if(l.sent(),u=void 0,f=void 0,!this.loadedSuccessfullyOnce)return[2,u];for(d=0,c=this.featureFlags;d<c.length;d++)if(o=c[d],t===o.key){f=o;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,n,i,a),this.debugMode&&console.debug("Successfully computed flag locally: ".concat(t," -> ").concat(u))}catch(g){g instanceof nk?this.debugMode&&console.debug("InconclusiveMatchError when computing flag locally: ".concat(t,": ").concat(g)):g instanceof Error&&console.error("Error computing flag locally: ".concat(t,": ").concat(g))}return[2,u]}})})},e.prototype.computeFeatureFlagPayloadLocally=function(t,r){var n,i,a,u,f,d,c,o;return gC(this,void 0,void 0,function(){var l;return mC(this,function(g){switch(g.label){case 0:return[4,this.loadFeatureFlags()];case 1:return g.sent(),l=void 0,this.loadedSuccessfullyOnce?(typeof r=="boolean"?l=(u=(a=(i=(n=this.featureFlagsByKey)===null||n===void 0?void 0:n[t])===null||i===void 0?void 0:i.filters)===null||a===void 0?void 0:a.payloads)===null||u===void 0?void 0:u[r.toString()]:typeof r=="string"&&(l=(o=(c=(d=(f=this.featureFlagsByKey)===null||f===void 0?void 0:f[t])===null||d===void 0?void 0:d.filters)===null||c===void 0?void 0:c.payloads)===null||o===void 0?void 0:o[r]),l===void 0?[2,null]:[2,l]):[2,void 0]}})})},e.prototype.getAllFlagsAndPayloads=function(t,r,n,i){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var a,u,f,d=this;return mC(this,function(c){switch(c.label){case 0:return[4,this.loadFeatureFlags()];case 1:return c.sent(),a={},u={},f=this.featureFlags.length==0,this.featureFlags.map(function(o){return gC(d,void 0,void 0,function(){var l,g,O;return mC(this,function(P){switch(P.label){case 0:return P.trys.push([0,2,,3]),l=this.computeFlagLocally(o,t,r,n,i),a[o.key]=l,[4,this.computeFeatureFlagPayloadLocally(o.key,l)];case 1:return g=P.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=P.sent(),O instanceof nk||O instanceof Error&&console.error("Error computing flag locally: ".concat(o.key,": ").concat(O)),f=!0,[3,3];case 3:return[2]}})})}),[2,{response:a,payloads:u,fallbackToDecide:f}]}})})},e.prototype.computeFlagLocally=function(t,r,n,i,a){if(n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),t.ensure_experience_continuity)throw new nk("Flag has experience continuity enabled");if(!t.active)return!1;var u=t.filters||{},f=u.aggregation_group_type_index;if(f!=null){var d=this.groupTypeMapping[String(f)];if(!d)throw console.warn("[FEATURE FLAGS] Unknown group type index ".concat(f," for feature flag ").concat(t.key)),new nk("Flag has unknown group type index");if(!(d in n))return console.warn("[FEATURE FLAGS] Can't compute group feature flag: ".concat(t.key," without group names passed in")),!1;var c=a[d];return this.matchFeatureFlagProperties(t,n[d],c)}else return this.matchFeatureFlagProperties(t,r,i)},e.prototype.matchFeatureFlagProperties=function(t,r,n){for(var i,a=t.filters||{},u=a.groups||[],f=!1,d=void 0,c=z1f([],u,!0).sort(function(M,q){var B=!!M.variant,I=!!q.variant;return B&&I?0:B?-1:I?1:0}),o=function(M){try{if(l.isConditionMatch(t,r,M,n)){var q=M.variant,B=((i=a.multivariate)===null||i===void 0?void 0:i.variants)||[];return q&&B.some(function(I){return I.key===q})?d=q:d=l.getMatchingVariant(t,r)||!0,"break"}}catch(I){if(I instanceof nk)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var P=O[g],j=o(P);if(j==="break")break}if(d!==void 0)return d;if(f)throw new nk("Can't determine if feature flag is enabled or not with given properties");return!1},e.prototype.isConditionMatch=function(t,r,n,i){var a=n.rollout_percentage;if((n.properties||[]).length>0){for(var u=0,f=n.properties;u<f.length;u++){var d=f[u],c=d.type,o=!1;if(c==="cohort"?o=V1f(d,i,this.cohorts):o=U1f(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&C1f(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=C1f(t.key,r,"variant"),i=this.variantLookupTable(t).find(function(a){return n>=a.valueMin&&n<a.valueMax});if(i)return i.key},e.prototype.variantLookupTable=function(t){var r,n=[],i=0,a=0,u=t.filters||{},f=((r=u.multivariate)===null||r===void 0?void 0:r.variants)||[];return f.forEach(function(d){a=i+d.rollout_percentage/100,n.push({valueMin:i,valueMax:a,key:d.key}),i=a}),n},e.prototype.loadFeatureFlags=function(t){return t===void 0&&(t=!1),gC(this,void 0,void 0,function(){return mC(this,function(r){switch(r.label){case 0:return!this.loadedSuccessfullyOnce||t?[4,this._loadFeatureFlags()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}})})},e.prototype._loadFeatureFlags=function(){return gC(this,void 0,void 0,function(){var t,r,n,i=this;return mC(this,function(a){switch(a.label){case 0:this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(function(){return i._loadFeatureFlags()},this.pollingInterval),a.label=1;case 1:return a.trys.push([1,4,,5]),[4,this._requestFeatureFlagDefinitions()];case 2:if(t=a.sent(),t&&t.status===401)throw new T1f("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");return t&&t.status!==200?[2]:[4,t.json()];case 3:return r=a.sent(),"flags"in r||console.error("Invalid response when getting feature flags: ".concat(JSON.stringify(r))),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce(function(u,f){return u[f.key]=f,u},{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0,[3,5];case 4:if(n=a.sent(),n instanceof T1f)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return gC(this,void 0,void 0,function(){var t,r,n,i,a;return mC(this,function(u){switch(u.label){case 0:t="".concat(this.host,"/api/feature_flag/local_evaluation?token=").concat(this.projectApiKey,"&send_cohorts"),r={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.personalApiKey),"user-agent":"posthog-node/".concat(J0u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=R1f(function(){i.abort()},this.timeout),r.signal=i.signal),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.fetch(t,r)];case 2:return[2,u.sent()];case 3:throw a=u.sent(),a;case 4:return clearTimeout(n),[7];case 5:return[2]}})})},e.prototype.stopPoller=function(){clearTimeout(this.poller)},e}();function C1f(e,t,r){r===void 0&&(r="");var n=(0,B1f.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/Eq1}function U1f(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new nk("Operator is_not_set is not supported")}else throw new nk("Property ".concat(r," not found in propertyValues"));var a=t[r];switch(i){case"exact":return Array.isArray(n)?n.indexOf(a)!==-1:n===a;case"is_not":return Array.isArray(n)?n.indexOf(a)===-1:n!==a;case"is_set":return r in t;case"icontains":return String(a).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(n).toLowerCase());case"regex":return q1f(String(n))&&String(a).match(String(n))!==null;case"not_regex":return q1f(String(n))&&String(a).match(String(n))===null;case"gt":return typeof a==typeof n&&a>n;case"gte":return typeof a==typeof n&&a>=n;case"lt":return typeof a==typeof n&&a<n;case"lte":return typeof a==typeof n&&a<=n;case"is_date_after":case"is_date_before":var u=I1f(n),f=I1f(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function V1f(e,t,r){var n=String(e.value);if(!(n in r))throw new nk("can't match cohort without a given cohort property value");var i=r[n];return W1f(i,t,r)}function W1f(e,t,r){if(!e)return!0;var n=e.type,i=e.values;if(!i||i.length===0)return!0;var a=!1;if("values"in i[0]){for(var u=0,f=i;u<f.length;u++){var d=f[u];try{var c=W1f(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new nk("Can't match cohort without a given cohort property value");return n==="AND"}else{for(var o=0,l=i;o<l.length;o++){var d=l[o];try{var c=void 0;d.type==="cohort"?c=V1f(d,t,r):c=U1f(d,t);var g=d.negation||!1;if(n==="AND"){if(!c&&!g||c&&g)return!1}else if(c&&!g||!c&&g)return!0}catch(P){if(P instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(P)),a=!0;else throw P}}if(a)throw new nk("can't match cohort without a given cohort property value");return n==="AND"}}function q1f(e){try{return new RegExp(e),!0}catch{return!1}}function I1f(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){var t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new nk("".concat(e," is in an invalid date format"))}else throw new nk("The date provided ".concat(e," must be a string, number, or date object"))}var Mq1=30*1e3,xq1=50*1e3,gma=function(e){p3n(t,e);function t(r,n){n===void 0&&(n={});var i=this,a;return n.captureMode=n?.captureMode||"json",i=e.call(this,r,n)||this,i._memoryStorage=new Sq1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new Aq1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:Mq1,personalApiKey:n.personalApiKey,projectApiKey:r,timeout:(a=n.requestTimeout)!==null&&a!==void 0?a:1e4,host:i.host,fetch:n.fetch})),i.distinctIdHasSentFlagCalls={},i.maxCacheSize=n.maxCacheSize||xq1,i}return t.prototype.getPersistedProperty=function(r){return this._memoryStorage.getProperty(r)},t.prototype.setPersistedProperty=function(r,n){return this._memoryStorage.setProperty(r,n)},t.prototype.fetch=function(r,n){return this.options.fetch?this.options.fetch(r,n):L1f(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return J0u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(J0u)},t.prototype.enable=function(){return e.prototype.optIn.call(this)},t.prototype.disable=function(){return e.prototype.optOut.call(this)},t.prototype.debug=function(r){var n;r===void 0&&(r=!0),e.prototype.debug.call(this,r),(n=this.featureFlagsPoller)===null||n===void 0||n.debug(r)},t.prototype.capture=function(r){var n=this,i=r.distinctId,a=r.event,u=r.properties,f=r.groups,d=r.sendFeatureFlags,c=r.timestamp,o=r.disableGeoip,l=function(g){e.prototype.captureStateless.call(n,i,a,g,{timestamp:c,disableGeoip:o})};d?e.prototype.getFeatureFlagsStateless.call(this,i,f,void 0,void 0,o).then(function(g){var O={};if(g)for(var P=0,j=Object.entries(g);P<j.length;P++){var M=j[P],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(F){return g?.[F]!==!1}),C=Gg({$active_feature_flags:I||void 0},O);l(Gg(Gg(Gg({},u),{$groups:f}),C))}):l(Gg(Gg({},u),{$groups:f}))},t.prototype.identify=function(r){var n=r.distinctId,i=r.properties,a=r.disableGeoip,u=i?.$set||i;e.prototype.identifyStateless.call(this,n,{$set:u},{disableGeoip:a})},t.prototype.alias=function(r){e.prototype.aliasStateless.call(this,r.alias,r.distinctId,void 0,{disableGeoip:r.disableGeoip})},t.prototype.getFeatureFlag=function(r,n,i){var a;return gC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,P,j,M,q;return mC(this,function(B){switch(B.label){case 0:return u=i||{},f=u.groups,d=u.personProperties,c=u.groupProperties,o=u.disableGeoip,l=i||{},g=l.onlyEvaluateLocally,O=l.sendFeatureFlagEvents,g==null&&(g=!1),O==null&&(O=!0),[4,(a=this.featureFlagsPoller)===null||a===void 0?void 0:a.getFeatureFlag(r,n,f,d,c)];case 1:return P=B.sent(),j=P!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:P=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(P),O&&(!(n in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[n].includes(M))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[n])?this.distinctIdHasSentFlagCalls[n].push(M):this.distinctIdHasSentFlagCalls[n]=[M],this.capture({distinctId:n,event:"$feature_flag_called",properties:(q={$feature_flag:r,$feature_flag_response:P,locally_evaluated:j},q["$feature/".concat(r)]=P,q),groups:f,disableGeoip:o})),[2,P]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return gC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return f=a||{},d=f.groups,c=f.personProperties,o=f.groupProperties,l=f.disableGeoip,g=a||{},O=g.onlyEvaluateLocally,g.sendFeatureFlagEvents,P=void 0,i?[3,2]:[4,this.getFeatureFlag(r,n,Gg(Gg({},a),{onlyEvaluateLocally:!0}))];case 1:i=M.sent(),M.label=2;case 2:return i?[4,(u=this.featureFlagsPoller)===null||u===void 0?void 0:u.computeFeatureFlagPayloadLocally(r,i)]:[3,4];case 3:P=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=P!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:P=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(P)]}catch{return[2,P]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return gC(this,void 0,void 0,function(){var a;return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlag(r,n,i)];case 1:return a=u.sent(),a===void 0?[2,void 0]:[2,!!a||!1]}})})},t.prototype.getAllFlags=function(r,n){return gC(this,void 0,void 0,function(){var i;return mC(this,function(a){switch(a.label){case 0:return[4,this.getAllFlagsAndPayloads(r,n)];case 1:return i=a.sent(),[2,i.featureFlags]}})})},t.prototype.getAllFlagsAndPayloads=function(r,n){var i;return gC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return a=n||{},u=a.groups,f=a.personProperties,d=a.groupProperties,c=a.disableGeoip,o=(n||{}).onlyEvaluateLocally,o==null&&(o=!1),[4,(i=this.featureFlagsPoller)===null||i===void 0?void 0:i.getAllFlagsAndPayloads(r,u,f,d)];case 1:return l=M.sent(),g={},O={},P=!0,l&&(g=l.response,O=l.payloads,P=l.fallbackToDecide),P&&!o?[4,e.prototype.getFeatureFlagsAndPayloadsStateless.call(this,r,u,f,d,c)]:[3,3];case 2:j=M.sent(),g=Gg(Gg({},g),j.flags||{}),O=Gg(Gg({},O),j.payloads||{}),M.label=3;case 3:return[2,{featureFlags:g,featureFlagPayloads:O}]}})})},t.prototype.groupIdentify=function(r){var n=r.groupType,i=r.groupKey,a=r.properties,u=r.distinctId,f=r.disableGeoip;e.prototype.groupIdentifyStateless.call(this,n,i,a,{disableGeoip:f},u)},t.prototype.reloadFeatureFlags=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){switch(n.label){case 0:return[4,(r=this.featureFlagsPoller)===null||r===void 0?void 0:r.loadFeatureFlags(!0)];case 1:return n.sent(),[2]}})})},t.prototype.shutdown=function(){this.shutdownAsync()},t.prototype.shutdownAsync=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(F1f);var mma=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gma(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.45.0-rc26",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var jvi=class{async sendEvent(){}async identify(){}async flush(){}};var _3n=require("fs/promises"),G1f=require("os"),$1f=require("path");var H1f=Xo(require("crypto")),Pma=new Uint8Array(256),Oma=Pma.length;function $0u(){return Oma>Pma.length-16&&(H1f.default.randomFillSync(Pma),Oma=0),Pma.slice(Oma,Oma+=16)}var VH=[];for(let e=0;e<256;++e)VH.push((e+256).toString(16).slice(1));function Q1f(e,t=0){return VH[e[t+0]]+VH[e[t+1]]+VH[e[t+2]]+VH[e[t+3]]+"-"+VH[e[t+4]]+VH[e[t+5]]+"-"+VH[e[t+6]]+VH[e[t+7]]+"-"+VH[e[t+8]]+VH[e[t+9]]+"-"+VH[e[t+10]]+VH[e[t+11]]+VH[e[t+12]]+VH[e[t+13]]+VH[e[t+14]]+VH[e[t+15]]}var J1f=Xo(require("crypto")),K0u={randomUUID:J1f.default.randomUUID};function Tq1(e,t,r){if(K0u.randomUUID&&!t&&!e)return K0u.randomUUID();e=e||{};let n=e.random||(e.rng||$0u)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Q1f(n)}var izr=Tq1;var Cq1="id",qq1=".fern",Dvi=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new gma(r),this.userId=t==null?void 0:nfu(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.45.0-rc26",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(y_.of((0,G1f.homedir)()),Ms.of(qq1),Ms.of(Cq1));await Wh(t)||(await(0,_3n.mkdir)((0,$1f.dirname)(t),{recursive:!0}),await(0,_3n.writeFile)(t,izr())),this.persistedDistinctId=(await(0,_3n.readFile)(t)).toString()}return this.persistedDistinctId}};var Y0u;async function h3n(){return Y0u==null&&(Y0u=await Iq1()),Y0u}async function Iq1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new jvi;let r=await K_a();return r!=null?new Dvi({token:r,posthogApiKey:e}):await $_a()!=null?new mma({posthogApiKey:e}):new Dvi({token:void 0,posthogApiKey:e})}catch{return new jvi}}function Svi(e,t){return function(){return e.apply(t,arguments)}}var{toString:Bq1}=Object.prototype,{getPrototypeOf:k0u}=Object,jma=(e=>t=>{let r=Bq1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),dIt=e=>(e=e.toLowerCase(),t=>jma(t)===e),Dma=e=>t=>typeof t===e,{isArray:y3n}=Array,Evi=Dma("undefined");function Nq1(e){return e!==null&&!Evi(e)&&e.constructor!==null&&!Evi(e.constructor)&&pDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var X1f=dIt("ArrayBuffer");function zq1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&X1f(e.buffer),t}var Rq1=Dma("string"),pDe=Dma("function"),Z1f=Dma("number"),Sma=e=>e!==null&&typeof e=="object",Fq1=e=>e===!0||e===!1,wma=e=>{if(jma(e)!=="object")return!1;let t=k0u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Lq1=dIt("Date"),Uq1=dIt("File"),Vq1=dIt("Blob"),Wq1=dIt("FileList"),Hq1=e=>Sma(e)&&pDe(e.pipe),Qq1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||pDe(e.append)&&((t=jma(e))==="formdata"||t==="object"&&pDe(e.toString)&&e.toString()==="[object FormData]"))},Jq1=dIt("URLSearchParams"),[Gq1,$q1,Kq1,Yq1]=["ReadableStream","Request","Response","Headers"].map(dIt),Xq1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Avi(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),y3n(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,f;for(n=0;n<u;n++)f=a[n],t.call(null,e[f],f,e)}}function k1f(e,t){t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var Nrn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ewf=e=>!Evi(e)&&e!==Nrn;function Z0u(){let{caseless:e}=ewf(this)&&this||{},t={},r=(n,i)=>{let a=e&&k1f(t,i)||i;wma(t[a])&&wma(n)?t[a]=Z0u(t[a],n):wma(n)?t[a]=Z0u({},n):y3n(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Avi(arguments[n],r);return t}var Zq1=(e,t,r,{allOwnKeys:n}={})=>(Avi(t,(i,a)=>{r&&pDe(i)?e[a]=Svi(i,r):e[a]=i},{allOwnKeys:n}),e),kq1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),e61=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},t61=(e,t,r,n)=>{let i,a,u,f={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)u=i[a],(!n||n(u,e,t))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&k0u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},r61=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},n61=e=>{if(!e)return null;if(y3n(e))return e;let t=e.length;if(!Z1f(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},i61=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&k0u(Uint8Array)),a61=(e,t)=>{let n=(e&&e[Symbol.iterator]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},o61=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},u61=dIt("HTMLFormElement"),s61=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),K1f=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),c61=dIt("RegExp"),twf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};Avi(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},l61=e=>{twf(e,(t,r)=>{if(pDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(pDe(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},f61=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return y3n(e)?n(e):n(String(e).split(t)),r},d61=()=>{},p61=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,X0u="abcdefghijklmnopqrstuvwxyz",Y1f="0123456789",rwf={DIGIT:Y1f,ALPHA:X0u,ALPHA_DIGIT:X0u+X0u.toUpperCase()+Y1f},_61=(e=16,t=rwf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function h61(e){return!!(e&&pDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var y61=e=>{let t=new Array(10),r=(n,i)=>{if(Sma(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=y3n(n)?[]:{};return Avi(n,(u,f)=>{let d=r(u,i+1);!Evi(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},v61=dIt("AsyncFunction"),b61=e=>e&&(Sma(e)||pDe(e))&&pDe(e.then)&&pDe(e.catch),nwf=((e,t)=>e?setImmediate:t?((r,n)=>(Nrn.addEventListener("message",({source:i,data:a})=>{i===Nrn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Nrn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",pDe(Nrn.postMessage)),g61=typeof queueMicrotask<"u"?queueMicrotask.bind(Nrn):typeof process<"u"&&process.nextTick||nwf,Jl={isArray:y3n,isArrayBuffer:X1f,isBuffer:Nq1,isFormData:Qq1,isArrayBufferView:zq1,isString:Rq1,isNumber:Z1f,isBoolean:Fq1,isObject:Sma,isPlainObject:wma,isReadableStream:Gq1,isRequest:$q1,isResponse:Kq1,isHeaders:Yq1,isUndefined:Evi,isDate:Lq1,isFile:Uq1,isBlob:Vq1,isRegExp:c61,isFunction:pDe,isStream:Hq1,isURLSearchParams:Jq1,isTypedArray:i61,isFileList:Wq1,forEach:Avi,merge:Z0u,extend:Zq1,trim:Xq1,stripBOM:kq1,inherits:e61,toFlatObject:t61,kindOf:jma,kindOfTest:dIt,endsWith:r61,toArray:n61,forEachEntry:a61,matchAll:o61,isHTMLForm:u61,hasOwnProperty:K1f,hasOwnProp:K1f,reduceDescriptors:twf,freezeMethods:l61,toObjectSet:f61,toCamelCase:s61,noop:d61,toFiniteNumber:p61,findKey:k1f,global:Nrn,isContextDefined:ewf,ALPHABET:rwf,generateString:_61,isSpecCompliantForm:h61,toJSONObject:y61,isAsyncFn:v61,isThenable:b61,setImmediate:nwf,asap:g61};function v3n(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Jl.inherits(v3n,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 iwf=v3n.prototype,awf={};["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=>{awf[e]={value:e}});Object.defineProperties(v3n,awf);Object.defineProperty(iwf,"isAxiosError",{value:!0});v3n.from=(e,t,r,n,i,a)=>{let u=Object.create(iwf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),v3n.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ny=v3n;var owf=Xo(aNr(),1),Ema=owf.default;function evu(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function swf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function uwf(e,t,r){return e?e.concat(t).map(function(i,a){return i=swf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function m61(e){return Jl.isArray(e)&&!e.some(evu)}var O61=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function P61(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(Ema||FormData),r=Jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(j,M){return!Jl.isUndefined(M[j])});let n=r.metaTokens,i=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Jl.isSpecCompliantForm(t);if(!Jl.isFunction(i))throw new TypeError("visitor must be a function");function c(P){if(P===null)return"";if(Jl.isDate(P))return P.toISOString();if(!d&&Jl.isBlob(P))throw new Ny("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(P)||Jl.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function o(P,j,M){let q=P;if(P&&!M&&typeof P=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),P=JSON.stringify(P);else if(Jl.isArray(P)&&m61(P)||(Jl.isFileList(P)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(P)))return j=swf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?uwf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return evu(P)?!0:(t.append(uwf(M,j,a),c(P)),!1)}let l=[],g=Object.assign(O61,{defaultVisitor:o,convertValue:c,isVisitable:evu});function O(P,j){if(!Jl.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(P),Jl.forEach(P,function(q,B){(!(Jl.isUndefined(q)||q===null)&&i.call(t,q,Jl.isString(B)?B.trim():B,j,g))===!0&&O(q,j?j.concat(B):[B])}),l.pop()}}if(!Jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var azr=P61;function cwf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function lwf(e,t){this._pairs=[],e&&azr(e,this,t)}var fwf=lwf.prototype;fwf.append=function(t,r){this._pairs.push([t,r])};fwf.toString=function(t){let r=t?function(n){return t.call(this,n,cwf)}:cwf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var dwf=lwf;function w61(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function zrn(e,t,r){if(!t)return e;let n=r&&r.encode||w61,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new dwf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var tvu=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.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(n){n!==null&&t(n)})}},rvu=tvu;var b3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pwf=Xo(require("url"),1),_wf=pwf.default.URLSearchParams;var hwf={isNode:!0,classes:{URLSearchParams:_wf,FormData:Ema,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var avu={};kc(avu,{hasBrowserEnv:()=>ivu,hasStandardBrowserEnv:()=>j61,hasStandardBrowserWebWorkerEnv:()=>D61,navigator:()=>nvu,origin:()=>S61});var ivu=typeof window<"u"&&typeof document<"u",nvu=typeof navigator=="object"&&navigator||void 0,j61=ivu&&(!nvu||["ReactNative","NativeScript","NS"].indexOf(nvu.product)<0),D61=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",S61=ivu&&window.location.href||"http://localhost";var b6={...avu,...hwf};function ovu(e,t){return azr(e,new b6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return b6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function E61(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function A61(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function M61(e){function t(r,n,i,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),d=a>=r.length;return u=!u&&Jl.isArray(i)?i.length:u,d?(Jl.hasOwnProp(i,u)?i[u]=[i[u],n]:i[u]=n,!f):((!i[u]||!Jl.isObject(i[u]))&&(i[u]=[]),t(r,n,i[u],a)&&Jl.isArray(i[u])&&(i[u]=A61(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(E61(n),i,r,0)}),r}return null}var Ama=M61;function x61(e,t,r){if(Jl.isString(e))try{return(t||JSON.parse)(e),Jl.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var uvu={transitional:b3n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Jl.isObject(t);if(a&&Jl.isHTMLForm(t)&&(t=new FormData(t)),Jl.isFormData(t))return i?JSON.stringify(Ama(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(n.indexOf("application/x-www-form-urlencoded")>-1)return ovu(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return azr(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),x61(t)):t}],transformResponse:[function(t){let r=this.transitional||uvu.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Jl.isResponse(t)||Jl.isReadableStream(t))return t;if(t&&Jl.isString(t)&&(n&&!this.responseType||i)){let u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?Ny.from(f,Ny.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:b6.classes.FormData,Blob:b6.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=>{uvu.headers[e]={}});var g3n=uvu;var T61=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"]),ywf=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1821
|
+
`}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&&Qga(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var P1f=Xo(h1f(),1),w1f=Xo(Jhu(),1),j1f=Xo(m1f(),1),$C=Xo(dDe(),1),D1f=Xo(s0i(),1);var hma=Xo(dDe(),1),O1f=Xo(s0i(),1),yma=function(e,t,r){return typeof e[t]!="function"?(0,hma.of)(e):(0,hma.from)((0,O1f.default)(e[t])(r).then(n=>(e[t]=n,e)))};var mvi={isPlainObject:P1f.default,set:j1f.default,get:w1f.default},d3n=class extends Brn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=mvi.isPlainObject(r)?{...r}:{},mvi.isPlainObject(t)&&(t=Object.values(t).every(i=>mvi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,$C.from)(t):t;return this.process=n.pipe((0,$C.concatMap)(this.processQuestion.bind(this)),(0,$C.publish)()),this.process.connect(),this.process.pipe((0,$C.reduce)((i,a)=>(mvi.set(i,a.name,a.answer),i),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,$C.defer)(()=>(0,$C.of)(t).pipe((0,$C.concatMap)(this.setDefaultType.bind(this)),(0,$C.concatMap)(this.filterIfRunnable.bind(this)),(0,$C.concatMap)(()=>yma(t,"message",this.answers)),(0,$C.concatMap)(()=>yma(t,"default",this.answers)),(0,$C.concatMap)(()=>yma(t,"choices",this.answers)),(0,$C.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,$C.defer)(()=>(0,$C.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,$C.defer)(()=>(0,$C.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&mvi.get(this.answers,t.name)!==void 0)return(0,$C.empty)();if(t.when===!1)return(0,$C.empty)();if(typeof t.when!="function")return(0,$C.of)(t);let{answers:r}=this;return(0,$C.defer)(()=>(0,$C.from)((0,D1f.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,$C.filter)(n=>n!=null)))}};function S1f(e){let t=function(r,n){let i;try{i=new d3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",rvi),this.registerPrompt("input",Arn),this.registerPrompt("number",nvi),this.registerPrompt("confirm",ivi),this.registerPrompt("rawlist",avi),this.registerPrompt("expand",ovi),this.registerPrompt("checkbox",uvi),this.registerPrompt("password",svi),this.registerPrompt("editor",bvi)},t.restoreDefaultPrompts(),t}var W0u=S1f();function _q1(e,t){W0u.registerPrompt(e,t)}function hq1(){W0u.restoreDefaultPrompts()}var yq1={prompt:W0u,ui:{BottomBar:gvi,Prompt:d3n},createPromptModule:S1f,registerPrompt:_q1,restoreDefaultPrompts:hq1,Separator:rae},vma=yq1;var B1f=Xo(E1f()),N1f=Xo(nlu()),Q0u=function(e,t){return Q0u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},Q0u(e,t)};function p3n(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Q0u(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var Gg=function(){return Gg=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Gg.apply(this,arguments)};function vq1(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function gC(e,t,r,n){function i(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function f(o){try{c(n.next(o))}catch(l){u(l)}}function d(o){try{c(n.throw(o))}catch(l){u(l)}}function c(o){o.done?a(o.value):i(o.value).then(f,d)}c((n=n.apply(e,t||[])).next())})}function mC(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(c){return function(o){return d([c,o])}}function d(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(o){c=[6,o],i=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function z1f(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,a;n<i;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var J0u="3.1.2",pw;(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"})(pw||(pw={}));function bq1(e,t){if(!e)throw new Error(t)}function gq1(e){return e?.replace(/\/+$/,"")}function mq1(e,t){return t===void 0&&(t={}),gC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return mC(this,function(g){switch(g.label){case 0:r=t.retryCount,n=r===void 0?3:r,i=t.retryDelay,a=i===void 0?5e3:i,u=t.retryCheck,f=u===void 0?function(){return!0}:u,d=null,c=0,g.label=1;case 1:return c<n+1?c>0?[4,new Promise(function(O){return setTimeout(O,a)})]:[3,3]:[3,7];case 2:g.sent(),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,e()];case 4:return o=g.sent(),[2,o];case 5:if(l=g.sent(),d=l,!f(l))throw l;return[3,6];case 6:return c++,[3,1];case 7:throw d}})})}function G0u(e){var t=new Date().getTime(),r=e&&e.performance&&e.performance.now&&e.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var i=Math.random()*16;return t>0?(i=(t+i)%16|0,t=Math.floor(t/16)):(i=(r+i)%16|0,r=Math.floor(r/16)),(n==="x"?i:i&3|8).toString(16)})}function Oq1(){return new Date().getTime()}function A1f(){return new Date().toISOString()}function R1f(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Pvi=String.fromCharCode,M1f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bma={};function Pq1(e,t){if(!bma[e]){bma[e]={};for(var r=0;r<e.length;r++)bma[e][e.charAt(r)]=r}return bma[e][t]}var wvi={compressToBase64:function(e){if(e==null)return"";var t=wvi._compress(e,6,function(r){return M1f.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:wvi._decompress(e.length,32,function(t){return Pq1(M1f,e.charAt(t))})},compress:function(e){return wvi._compress(e,16,function(t){return Pvi(t)})},_compress:function(e,t,r){if(e==null)return"";var n={},i={},a=[],u,f,d="",c="",o="",l=2,g=3,O=2,P=0,j=0,M;for(M=0;M<e.length;M+=1)if(d=e.charAt(M),Object.prototype.hasOwnProperty.call(n,d)||(n[d]=g++,i[d]=!0),c=o+d,Object.prototype.hasOwnProperty.call(n,c))o=c;else{if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),n[c]=g++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;for(;;)if(P=P<<1,j==t-1){a.push(r(P));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:wvi._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){var n=[],i=[],a={val:r(0),position:t,index:1},u=4,f=4,d=3,c="",o,l,g,O,P,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,P=Math.pow(2,2),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Pvi(g);break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Pvi(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,P=Math.pow(2,d),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(M=g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Pvi(g),M=f-1,u--;break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Pvi(g),M=f-1,u--;break;case 2:return i.join("")}if(u==0&&(u=Math.pow(2,d),d++),n[M])c=n[M];else if(M===f)c=l+l.charAt(0);else return null;i.push(c),n[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,d),d++)}}},wq1=function(){function e(){this.events={},this.events={}}return e.prototype.on=function(t,r){var n=this;return this.events[t]||(this.events[t]=[]),this.events[t].push(r),function(){n.events[t]=n.events[t].filter(function(i){return i!==r})}},e.prototype.emit=function(t,r){for(var n=0,i=this.events[t]||[];n<i.length;n++){var a=i[n];a(r)}for(var u=0,f=this.events["*"]||[];u<f.length;u++){var a=f[u];a(t,r)}},e}(),jq1=function(e){p3n(t,e);function t(r){var n=e.call(this,"HTTP error while fetching PostHog: "+r.status)||this;return n.response=r,n.name="PostHogFetchHttpError",n}return t}(Error),Dq1=function(e){p3n(t,e);function t(r){var n=e.call(this,"Network error while fetching PostHog",r instanceof Error?{cause:r}:{})||this;return n.error=r,n.name="PostHogFetchNetworkError",n}return t}(Error);function x1f(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var F1f=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new wq1,bq1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=gq1(r?.host||"https://app.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.flushInterval=(n=r?.flushInterval)!==null&&n!==void 0?n:1e4,this.captureMode=r?.captureMode||"form",this._optoutOverride=r?.enable===!1,this._retryOptions={retryCount:(i=r?.fetchRetryCount)!==null&&i!==void 0?i:3,retryDelay:(a=r?.fetchRetryDelay)!==null&&a!==void 0?a:3e3,retryCheck:x1f},this.requestTimeout=(u=r?.requestTimeout)!==null&&u!==void 0?u:1e4,this.disableGeoip=(f=r?.disableGeoip)!==null&&f!==void 0?f:!0}return e.prototype.getCommonEventProperties=function(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}},Object.defineProperty(e.prototype,"optedOut",{get:function(){var t,r;return(r=(t=this.getPersistedProperty(pw.OptedOut))!==null&&t!==void 0?t:this._optoutOverride)!==null&&r!==void 0?r:!1},enumerable:!1,configurable:!0}),e.prototype.optIn=function(){this.setPersistedProperty(pw.OptedOut,!1)},e.prototype.optOut=function(){this.setPersistedProperty(pw.OptedOut,!0)},e.prototype.on=function(t,r){return this._events.on(t,r)},e.prototype.debug=function(t){var r;t===void 0&&(t=!0),(r=this.removeDebugCallback)===null||r===void 0||r.call(this),this.debugMode=t,t&&(this.removeDebugCallback=this.on("*",function(n,i){return console.log("PostHog Debug",n,i)}))},e.prototype.buildPayload=function(t){return{distinct_id:t.distinct_id,event:t.event,properties:Gg(Gg({},t.properties||{}),this.getCommonEventProperties())}},e.prototype.identifyStateless=function(t,r,n){var i=Gg({},this.buildPayload({distinct_id:t,event:"$identify",properties:r}));return this.enqueue("identify",i,n),this},e.prototype.captureStateless=function(t,r,n,i){var a=this.buildPayload({distinct_id:t,event:r,properties:n});return this.enqueue("capture",a,i),this},e.prototype.aliasStateless=function(t,r,n,i){var a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:Gg(Gg({},n||{}),{distinct_id:r,alias:t})});return this.enqueue("alias",a,i),this},e.prototype.groupIdentifyStateless=function(t,r,n,i,a,u){var f=this.buildPayload({distinct_id:a||"$".concat(t,"_").concat(r),event:"$groupidentify",properties:Gg({$group_type:t,$group_key:r,$group_set:n||{}},u||{})});return this.enqueue("capture",f,i),this},e.prototype.getDecide=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f;return mC(this,function(d){return u="".concat(this.host,"/decide/?v=3"),f={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gg({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i},a))},[2,this.fetchWithRetry(u,f).then(function(c){return c.json()}).catch(function(c){console.error("Error fetching feature flags",c)})]})})},e.prototype.getFeatureFlagStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0&&(d=!1),[2,d]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagPayloadsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0?[2,null]:[2,this._parsePayload(d)]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f=this;return mC(this,function(d){switch(d.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return u=d.sent().payloads,u?[2,Object.fromEntries(Object.entries(u).map(function(c){var o=c[0],l=c[1];return[o,f._parsePayload(l)]}))]:[2,u]}})})},e.prototype._parsePayload=function(t){try{return JSON.parse(t)}catch{return t}},e.prototype.getFeatureFlagsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return[2,u.sent().flags]}})})},e.prototype.getFeatureFlagsAndPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f,d,c;return mC(this,function(o){switch(o.label){case 0:return u={},(a??this.disableGeoip)&&(u.geoip_disable=!0),[4,this.getDecide(t,r,n,i,u)];case 1:return f=o.sent(),d=f?.featureFlags,c=f?.featureFlagPayloads,[2,{flags:d,payloads:c}]}})})},e.prototype.enqueue=function(t,r,n){var i=this,a;if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.enable()");return}var u=Gg(Gg({},r),{type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:A1f()}),f=(a=n?.disableGeoip)!==null&&a!==void 0?a:this.disableGeoip;f&&(u.properties||(u.properties={}),u.properties.$geoip_disable=!0),u.distinctId&&(u.distinct_id=u.distinctId,delete u.distinctId);var d=this.getPersistedProperty(pw.Queue)||[];d.push({message:u}),this.setPersistedProperty(pw.Queue,d),this._events.emit(t,u),d.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=R1f(function(){return i.flush()},this.flushInterval))},e.prototype.flushAsync=function(){var t=this;return new Promise(function(r,n){t.flush(function(i,a){return i?n(i):r(a)})})},e.prototype.flush=function(t){var r=this;this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);var n=this.getPersistedProperty(pw.Queue)||[];if(!n.length)return t?.();var i=n.splice(0,this.flushAt);this.setPersistedProperty(pw.Queue,n);var a=i.map(function(O){return O.message}),u={api_key:this.apiKey,batch:a,sent_at:A1f()},f=G0u(),d=function(O){O&&r._events.emit("error",O),t?.(O,a),delete r.pendingPromises[f],r._events.emit("flush",a)};this.getCustomUserAgent();var c=JSON.stringify(u),o=this.captureMode==="form"?"".concat(this.host,"/e/?ip=1&_=").concat(Oq1(),"&v=").concat(this.getLibraryVersion()):"".concat(this.host,"/batch/"),l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"data=".concat(encodeURIComponent(wvi.compressToBase64(c)),"&compression=lz64")}:{method:"POST",headers:{"Content-Type":"application/json"},body:c},g=this.fetchWithRetry(o,l);this.pendingPromises[f]=g,g.then(function(){return d()}).catch(function(O){d(O)})},e.prototype.fetchWithRetry=function(t,r,n){var i,a;return gC(this,void 0,void 0,function(){var u=this;return mC(this,function(f){switch(f.label){case 0:return(i=(a=AbortSignal).timeout)!==null&&i!==void 0||(a.timeout=function(c){var o=new AbortController;return setTimeout(function(){return o.abort()},c),o.signal}),[4,mq1(function(){return gC(u,void 0,void 0,function(){var d,c;return mC(this,function(o){switch(o.label){case 0:d=null,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.fetch(t,Gg({signal:AbortSignal.timeout(this.requestTimeout)},r))];case 2:return d=o.sent(),[3,4];case 3:throw c=o.sent(),new Dq1(c);case 4:if(d.status<200||d.status>=400)throw new jq1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return gC(this,void 0,void 0,function(){var t;return mC(this,function(r){switch(r.label){case 0:clearTimeout(this._flushTimer),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.flushAsync()];case 2:return r.sent(),[4,Promise.all(Object.values(this.pendingPromises).map(function(n){return n.catch(function(){})}))];case 3:return r.sent(),[3,5];case 4:if(t=r.sent(),!x1f(t))throw t;return console.error("Error while shutting down PostHog",t),[3,5];case 5:return[2]}})})},e.prototype.shutdown=function(){this.shutdownAsync()},e}();(function(e){p3n(t,e);function t(r,n){var i=this,a,u,f,d=(a=n?.disableGeoip)!==null&&a!==void 0?a:!1;return i=e.call(this,r,Gg(Gg({},n),{disableGeoip:d}))||this,i.flagCallReported={},i.sessionProps={},i.sendFeatureFlagEvent=(u=n?.sendFeatureFlagEvent)!==null&&u!==void 0?u:!0,i._sessionExpirationTimeSeconds=(f=n?.sessionExpirationTimeSeconds)!==null&&f!==void 0?f:1800,i}return t.prototype.setupBootstrap=function(r){var n,i,a,u;if(!((n=r?.bootstrap)===null||n===void 0)&&n.distinctId&&(!((i=r?.bootstrap)===null||i===void 0)&&i.isIdentifiedId?this.setPersistedProperty(pw.DistinctId,r.bootstrap.distinctId):this.setPersistedProperty(pw.AnonymousId,r.bootstrap.distinctId)),!((a=r?.bootstrap)===null||a===void 0)&&a.featureFlags){var f=Object.keys(((u=r.bootstrap)===null||u===void 0?void 0:u.featureFlags)||{}).filter(function(d){var c,o;return!!(!((o=(c=r.bootstrap)===null||c===void 0?void 0:c.featureFlags)===null||o===void 0)&&o[d])}).reduce(function(d,c){var o,l;return d[c]=((l=(o=r.bootstrap)===null||o===void 0?void 0:o.featureFlags)===null||l===void 0?void 0:l[c])||!1,d},{});this.setKnownFeatureFlags(f),r?.bootstrap.featureFlagPayloads&&this.setKnownFeatureFlagPayloads(r?.bootstrap.featureFlagPayloads)}},Object.defineProperty(t.prototype,"props",{get:function(){return this._props||(this._props=this.getPersistedProperty(pw.Props)),this._props||{}},set:function(r){this._props=r},enumerable:!1,configurable:!0}),t.prototype.clearProps=function(){this.props=void 0,this.sessionProps={}},t.prototype.on=function(r,n){return this._events.on(r,n)},t.prototype.reset=function(r){var n=z1f([pw.Queue],r||[],!0);this.clearProps();for(var i=0,a=Object.keys(pw);i<a.length;i++){var u=a[i];n.includes(pw[u])||this.setPersistedProperty(pw[u],null)}},t.prototype.getCommonEventProperties=function(){var r=this.getFeatureFlags(),n={};if(r)for(var i=0,a=Object.entries(r);i<a.length;i++){var u=a[i],f=u[0],d=u[1];n["$feature/".concat(f)]=d}return Gg(Gg({$active_feature_flags:r?Object.keys(r):void 0},n),e.prototype.getCommonEventProperties.call(this))},t.prototype.enrichProperties=function(r){return Gg(Gg(Gg(Gg(Gg({},this.props),this.sessionProps),r||{}),this.getCommonEventProperties()),{$session_id:this.getSessionId()})},t.prototype.getSessionId=function(){var r=this.getPersistedProperty(pw.SessionId),n=this.getPersistedProperty(pw.SessionLastTimestamp)||0;return(!r||Date.now()-n>this._sessionExpirationTimeSeconds*1e3)&&(r=G0u(globalThis),this.setPersistedProperty(pw.SessionId,r)),this.setPersistedProperty(pw.SessionLastTimestamp,Date.now()),r},t.prototype.resetSessionId=function(){this.setPersistedProperty(pw.SessionId,null)},t.prototype.getAnonymousId=function(){var r=this.getPersistedProperty(pw.AnonymousId);return r||(r=G0u(globalThis),this.setPersistedProperty(pw.AnonymousId,r)),r},t.prototype.getDistinctId=function(){return this.getPersistedProperty(pw.DistinctId)||this.getAnonymousId()},t.prototype.unregister=function(r){delete this.props[r],this.setPersistedProperty(pw.Props,this.props)},t.prototype.register=function(r){this.props=Gg(Gg({},this.props),r),this.setPersistedProperty(pw.Props,this.props)},t.prototype.registerForSession=function(r){this.sessionProps=Gg(Gg({},this.sessionProps),r)},t.prototype.unregisterForSession=function(r){delete this.sessionProps[r]},t.prototype.identify=function(r,n,i){var a=this.getDistinctId();r=r||a,n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(Gg(Gg({},n),{$anon_distinct_id:this.getAnonymousId(),$set:n}));return r!==a&&(this.setPersistedProperty(pw.AnonymousId,a),this.setPersistedProperty(pw.DistinctId,r),this.reloadFeatureFlags()),e.prototype.identifyStateless.call(this,r,u,i),this},t.prototype.capture=function(r,n,i){var a=this.getDistinctId();n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(n);return e.prototype.captureStateless.call(this,a,r,u,i),this},t.prototype.alias=function(r){var n=this.getDistinctId(),i=this.enrichProperties({});return e.prototype.aliasStateless.call(this,r,n,i),this},t.prototype.autocapture=function(r,n,i,a){i===void 0&&(i={});var u=this.getDistinctId(),f={distinct_id:u,event:"$autocapture",properties:Gg(Gg({},this.enrichProperties(i)),{$event_type:r,$elements:n})};return this.enqueue("autocapture",f,a),this},t.prototype.groups=function(r){var n=this.props.$groups||{};return this.register({$groups:Gg(Gg({},n),r)}),Object.keys(r).find(function(i){return n[i]!==r[i]})&&this.reloadFeatureFlags(),this},t.prototype.group=function(r,n,i,a){var u;return this.groups((u={},u[r]=n,u)),i&&this.groupIdentify(r,n,i,a),this},t.prototype.groupIdentify=function(r,n,i,a){var u=this.getDistinctId(),f=this.enrichProperties({});return e.prototype.groupIdentifyStateless.call(this,r,n,i,a,u,f),this},t.prototype.personProperties=function(r){var n=this.getPersistedProperty(pw.PersonProperties)||{};return this.setPersistedProperty(pw.PersonProperties,Gg(Gg({},n),r)),this},t.prototype.groupProperties=function(r){var n=this.getPersistedProperty(pw.GroupProperties)||{};return Object.keys(n).length!==0&&Object.keys(n).forEach(function(i){n[i]=Gg(Gg({},n[i]),r[i]),delete r[i]}),this.setPersistedProperty(pw.GroupProperties,Gg(Gg({},n),r)),this},t.prototype.decideAsync=function(r){return r===void 0&&(r=!0),this._decideResponsePromise?this._decideResponsePromise:this._decideAsync(r)},t.prototype._decideAsync=function(r){return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return mC(this,function(c){return n=this.getDistinctId(),i=this.props.$groups||{},a=this.getPersistedProperty(pw.PersonProperties)||{},u=this.getPersistedProperty(pw.GroupProperties)||{},f={$anon_distinct_id:r?this.getAnonymousId():void 0},this._decideResponsePromise=e.prototype.getDecide.call(this,n,i,a,u,f).then(function(o){if(o?.featureFlags){var l=o.featureFlags,g=o.featureFlagPayloads;if(o.errorsWhileComputingFlags){var O=d.getPersistedProperty(pw.FeatureFlags),P=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},P),o.featureFlagPayloads)}d.setKnownFeatureFlags(l),d.setKnownFeatureFlagPayloads(g)}return o}).finally(function(){d._decideResponsePromise=void 0}),[2,this._decideResponsePromise]})})},t.prototype.setKnownFeatureFlags=function(r){this.setPersistedProperty(pw.FeatureFlags,r),this._events.emit("featureflags",r)},t.prototype.setKnownFeatureFlagPayloads=function(r){this.setPersistedProperty(pw.FeatureFlagPayloads,r)},t.prototype.getFeatureFlag=function(r){var n=this.getFeatureFlags();if(n){var i=n[r];return i===void 0&&(i=!1),this.sendFeatureFlagEvent&&!this.flagCallReported[r]&&(this.flagCallReported[r]=!0,this.capture("$feature_flag_called",{$feature_flag:r,$feature_flag_response:i})),i}},t.prototype.getFeatureFlagPayload=function(r){var n=this.getFeatureFlagPayloads();if(n){var i=n[r];return i===void 0?null:this._parsePayload(i)}},t.prototype.getFeatureFlagPayloads=function(){var r=this,n=this.getPersistedProperty(pw.FeatureFlagPayloads);return n&&Object.fromEntries(Object.entries(n).map(function(i){var a=i[0],u=i[1];return[a,r._parsePayload(u)]}))},t.prototype.getFeatureFlags=function(){var r=this.getPersistedProperty(pw.FeatureFlags),n=this.getPersistedProperty(pw.OverrideFeatureFlags);if(!n)return r;r=r||{};for(var i in n)n[i]?r[i]=n[i]:delete r[i];return r},t.prototype.getFeatureFlagsAndPayloads=function(){var r=this.getFeatureFlags(),n=this.getFeatureFlagPayloads();return{flags:r,payloads:n}},t.prototype.isFeatureEnabled=function(r){var n=this.getFeatureFlag(r);if(n!==void 0)return!!n},t.prototype.reloadFeatureFlags=function(r){this.decideAsync().then(function(n){r?.(void 0,n?.featureFlags)}).catch(function(n){r?.(n,void 0),r||console.log("[PostHog] Error reloading feature flags",n)})},t.prototype.reloadFeatureFlagsAsync=function(r){var n;return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){return mC(this,function(i){switch(i.label){case 0:return[4,this.decideAsync(r)];case 1:return[2,(n=i.sent())===null||n===void 0?void 0:n.featureFlags]}})})},t.prototype.onFeatureFlags=function(r){var n=this;return this.on("featureflags",function(){return gC(n,void 0,void 0,function(){var i;return mC(this,function(a){return i=this.getFeatureFlags(),i&&r(i),[2]})})})},t.prototype.onFeatureFlag=function(r,n){var i=this;return this.on("featureflags",function(){return gC(i,void 0,void 0,function(){var a;return mC(this,function(u){return a=this.getFeatureFlag(r),a!==void 0&&n(a),[2]})})})},t.prototype.overrideFeatureFlag=function(r){return r===null?this.setPersistedProperty(pw.OverrideFeatureFlags,null):this.setPersistedProperty(pw.OverrideFeatureFlags,r)},t})(F1f);var Sq1=function(){function e(){this._memoryStorage={}}return e.prototype.getProperty=function(t){return this._memoryStorage[t]},e.prototype.setProperty=function(t,r){this._memoryStorage[t]=r!==null?r:void 0},e}(),L1f=function(e,t){return gC(void 0,void 0,void 0,function(){var r;return mC(this,function(n){switch(n.label){case 0:return[4,N1f.default.request({url:e,headers:t.headers,method:t.method.toLowerCase(),data:t.body,signal:t.signal,validateStatus:function(){return!0}})];case 1:return r=n.sent(),[2,{status:r.status,text:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})},json:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})}}]}})})},Eq1=1152921504606847e3,T1f=function(e){p3n(t,e);function t(r){var n=e.call(this)||this;return Error.captureStackTrace(n,n.constructor),n.name="ClientError",n.message=r,Object.setPrototypeOf(n,t.prototype),n}return t}(Error),nk=function(e){p3n(t,e);function t(r){var n=e.call(this,r)||this;return n.name=n.constructor.name,Error.captureStackTrace(n,n.constructor),Object.setPrototypeOf(n,t.prototype),n}return t}(Error),Aq1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=vq1(t,["pollingInterval","personalApiKey","projectApiKey","timeout","host"]);this.debugMode=!1,this.pollingInterval=r,this.personalApiKey=n,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=a,this.projectApiKey=i,this.host=u,this.poller=void 0,this.fetch=f.fetch||L1f,this.loadFeatureFlags()}return e.prototype.debug=function(t){t===void 0&&(t=!0),this.debugMode=t},e.prototype.getFeatureFlag=function(t,r,n,i,a){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f,d,c,o;return mC(this,function(l){switch(l.label){case 0:return[4,this.loadFeatureFlags()];case 1:if(l.sent(),u=void 0,f=void 0,!this.loadedSuccessfullyOnce)return[2,u];for(d=0,c=this.featureFlags;d<c.length;d++)if(o=c[d],t===o.key){f=o;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,n,i,a),this.debugMode&&console.debug("Successfully computed flag locally: ".concat(t," -> ").concat(u))}catch(g){g instanceof nk?this.debugMode&&console.debug("InconclusiveMatchError when computing flag locally: ".concat(t,": ").concat(g)):g instanceof Error&&console.error("Error computing flag locally: ".concat(t,": ").concat(g))}return[2,u]}})})},e.prototype.computeFeatureFlagPayloadLocally=function(t,r){var n,i,a,u,f,d,c,o;return gC(this,void 0,void 0,function(){var l;return mC(this,function(g){switch(g.label){case 0:return[4,this.loadFeatureFlags()];case 1:return g.sent(),l=void 0,this.loadedSuccessfullyOnce?(typeof r=="boolean"?l=(u=(a=(i=(n=this.featureFlagsByKey)===null||n===void 0?void 0:n[t])===null||i===void 0?void 0:i.filters)===null||a===void 0?void 0:a.payloads)===null||u===void 0?void 0:u[r.toString()]:typeof r=="string"&&(l=(o=(c=(d=(f=this.featureFlagsByKey)===null||f===void 0?void 0:f[t])===null||d===void 0?void 0:d.filters)===null||c===void 0?void 0:c.payloads)===null||o===void 0?void 0:o[r]),l===void 0?[2,null]:[2,l]):[2,void 0]}})})},e.prototype.getAllFlagsAndPayloads=function(t,r,n,i){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var a,u,f,d=this;return mC(this,function(c){switch(c.label){case 0:return[4,this.loadFeatureFlags()];case 1:return c.sent(),a={},u={},f=this.featureFlags.length==0,this.featureFlags.map(function(o){return gC(d,void 0,void 0,function(){var l,g,O;return mC(this,function(P){switch(P.label){case 0:return P.trys.push([0,2,,3]),l=this.computeFlagLocally(o,t,r,n,i),a[o.key]=l,[4,this.computeFeatureFlagPayloadLocally(o.key,l)];case 1:return g=P.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=P.sent(),O instanceof nk||O instanceof Error&&console.error("Error computing flag locally: ".concat(o.key,": ").concat(O)),f=!0,[3,3];case 3:return[2]}})})}),[2,{response:a,payloads:u,fallbackToDecide:f}]}})})},e.prototype.computeFlagLocally=function(t,r,n,i,a){if(n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),t.ensure_experience_continuity)throw new nk("Flag has experience continuity enabled");if(!t.active)return!1;var u=t.filters||{},f=u.aggregation_group_type_index;if(f!=null){var d=this.groupTypeMapping[String(f)];if(!d)throw console.warn("[FEATURE FLAGS] Unknown group type index ".concat(f," for feature flag ").concat(t.key)),new nk("Flag has unknown group type index");if(!(d in n))return console.warn("[FEATURE FLAGS] Can't compute group feature flag: ".concat(t.key," without group names passed in")),!1;var c=a[d];return this.matchFeatureFlagProperties(t,n[d],c)}else return this.matchFeatureFlagProperties(t,r,i)},e.prototype.matchFeatureFlagProperties=function(t,r,n){for(var i,a=t.filters||{},u=a.groups||[],f=!1,d=void 0,c=z1f([],u,!0).sort(function(M,q){var B=!!M.variant,I=!!q.variant;return B&&I?0:B?-1:I?1:0}),o=function(M){try{if(l.isConditionMatch(t,r,M,n)){var q=M.variant,B=((i=a.multivariate)===null||i===void 0?void 0:i.variants)||[];return q&&B.some(function(I){return I.key===q})?d=q:d=l.getMatchingVariant(t,r)||!0,"break"}}catch(I){if(I instanceof nk)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var P=O[g],j=o(P);if(j==="break")break}if(d!==void 0)return d;if(f)throw new nk("Can't determine if feature flag is enabled or not with given properties");return!1},e.prototype.isConditionMatch=function(t,r,n,i){var a=n.rollout_percentage;if((n.properties||[]).length>0){for(var u=0,f=n.properties;u<f.length;u++){var d=f[u],c=d.type,o=!1;if(c==="cohort"?o=V1f(d,i,this.cohorts):o=U1f(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&C1f(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=C1f(t.key,r,"variant"),i=this.variantLookupTable(t).find(function(a){return n>=a.valueMin&&n<a.valueMax});if(i)return i.key},e.prototype.variantLookupTable=function(t){var r,n=[],i=0,a=0,u=t.filters||{},f=((r=u.multivariate)===null||r===void 0?void 0:r.variants)||[];return f.forEach(function(d){a=i+d.rollout_percentage/100,n.push({valueMin:i,valueMax:a,key:d.key}),i=a}),n},e.prototype.loadFeatureFlags=function(t){return t===void 0&&(t=!1),gC(this,void 0,void 0,function(){return mC(this,function(r){switch(r.label){case 0:return!this.loadedSuccessfullyOnce||t?[4,this._loadFeatureFlags()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}})})},e.prototype._loadFeatureFlags=function(){return gC(this,void 0,void 0,function(){var t,r,n,i=this;return mC(this,function(a){switch(a.label){case 0:this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(function(){return i._loadFeatureFlags()},this.pollingInterval),a.label=1;case 1:return a.trys.push([1,4,,5]),[4,this._requestFeatureFlagDefinitions()];case 2:if(t=a.sent(),t&&t.status===401)throw new T1f("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");return t&&t.status!==200?[2]:[4,t.json()];case 3:return r=a.sent(),"flags"in r||console.error("Invalid response when getting feature flags: ".concat(JSON.stringify(r))),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce(function(u,f){return u[f.key]=f,u},{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0,[3,5];case 4:if(n=a.sent(),n instanceof T1f)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return gC(this,void 0,void 0,function(){var t,r,n,i,a;return mC(this,function(u){switch(u.label){case 0:t="".concat(this.host,"/api/feature_flag/local_evaluation?token=").concat(this.projectApiKey,"&send_cohorts"),r={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.personalApiKey),"user-agent":"posthog-node/".concat(J0u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=R1f(function(){i.abort()},this.timeout),r.signal=i.signal),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.fetch(t,r)];case 2:return[2,u.sent()];case 3:throw a=u.sent(),a;case 4:return clearTimeout(n),[7];case 5:return[2]}})})},e.prototype.stopPoller=function(){clearTimeout(this.poller)},e}();function C1f(e,t,r){r===void 0&&(r="");var n=(0,B1f.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/Eq1}function U1f(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new nk("Operator is_not_set is not supported")}else throw new nk("Property ".concat(r," not found in propertyValues"));var a=t[r];switch(i){case"exact":return Array.isArray(n)?n.indexOf(a)!==-1:n===a;case"is_not":return Array.isArray(n)?n.indexOf(a)===-1:n!==a;case"is_set":return r in t;case"icontains":return String(a).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(n).toLowerCase());case"regex":return q1f(String(n))&&String(a).match(String(n))!==null;case"not_regex":return q1f(String(n))&&String(a).match(String(n))===null;case"gt":return typeof a==typeof n&&a>n;case"gte":return typeof a==typeof n&&a>=n;case"lt":return typeof a==typeof n&&a<n;case"lte":return typeof a==typeof n&&a<=n;case"is_date_after":case"is_date_before":var u=I1f(n),f=I1f(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function V1f(e,t,r){var n=String(e.value);if(!(n in r))throw new nk("can't match cohort without a given cohort property value");var i=r[n];return W1f(i,t,r)}function W1f(e,t,r){if(!e)return!0;var n=e.type,i=e.values;if(!i||i.length===0)return!0;var a=!1;if("values"in i[0]){for(var u=0,f=i;u<f.length;u++){var d=f[u];try{var c=W1f(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new nk("Can't match cohort without a given cohort property value");return n==="AND"}else{for(var o=0,l=i;o<l.length;o++){var d=l[o];try{var c=void 0;d.type==="cohort"?c=V1f(d,t,r):c=U1f(d,t);var g=d.negation||!1;if(n==="AND"){if(!c&&!g||c&&g)return!1}else if(c&&!g||!c&&g)return!0}catch(P){if(P instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(P)),a=!0;else throw P}}if(a)throw new nk("can't match cohort without a given cohort property value");return n==="AND"}}function q1f(e){try{return new RegExp(e),!0}catch{return!1}}function I1f(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){var t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new nk("".concat(e," is in an invalid date format"))}else throw new nk("The date provided ".concat(e," must be a string, number, or date object"))}var Mq1=30*1e3,xq1=50*1e3,gma=function(e){p3n(t,e);function t(r,n){n===void 0&&(n={});var i=this,a;return n.captureMode=n?.captureMode||"json",i=e.call(this,r,n)||this,i._memoryStorage=new Sq1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new Aq1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:Mq1,personalApiKey:n.personalApiKey,projectApiKey:r,timeout:(a=n.requestTimeout)!==null&&a!==void 0?a:1e4,host:i.host,fetch:n.fetch})),i.distinctIdHasSentFlagCalls={},i.maxCacheSize=n.maxCacheSize||xq1,i}return t.prototype.getPersistedProperty=function(r){return this._memoryStorage.getProperty(r)},t.prototype.setPersistedProperty=function(r,n){return this._memoryStorage.setProperty(r,n)},t.prototype.fetch=function(r,n){return this.options.fetch?this.options.fetch(r,n):L1f(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return J0u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(J0u)},t.prototype.enable=function(){return e.prototype.optIn.call(this)},t.prototype.disable=function(){return e.prototype.optOut.call(this)},t.prototype.debug=function(r){var n;r===void 0&&(r=!0),e.prototype.debug.call(this,r),(n=this.featureFlagsPoller)===null||n===void 0||n.debug(r)},t.prototype.capture=function(r){var n=this,i=r.distinctId,a=r.event,u=r.properties,f=r.groups,d=r.sendFeatureFlags,c=r.timestamp,o=r.disableGeoip,l=function(g){e.prototype.captureStateless.call(n,i,a,g,{timestamp:c,disableGeoip:o})};d?e.prototype.getFeatureFlagsStateless.call(this,i,f,void 0,void 0,o).then(function(g){var O={};if(g)for(var P=0,j=Object.entries(g);P<j.length;P++){var M=j[P],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(F){return g?.[F]!==!1}),C=Gg({$active_feature_flags:I||void 0},O);l(Gg(Gg(Gg({},u),{$groups:f}),C))}):l(Gg(Gg({},u),{$groups:f}))},t.prototype.identify=function(r){var n=r.distinctId,i=r.properties,a=r.disableGeoip,u=i?.$set||i;e.prototype.identifyStateless.call(this,n,{$set:u},{disableGeoip:a})},t.prototype.alias=function(r){e.prototype.aliasStateless.call(this,r.alias,r.distinctId,void 0,{disableGeoip:r.disableGeoip})},t.prototype.getFeatureFlag=function(r,n,i){var a;return gC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,P,j,M,q;return mC(this,function(B){switch(B.label){case 0:return u=i||{},f=u.groups,d=u.personProperties,c=u.groupProperties,o=u.disableGeoip,l=i||{},g=l.onlyEvaluateLocally,O=l.sendFeatureFlagEvents,g==null&&(g=!1),O==null&&(O=!0),[4,(a=this.featureFlagsPoller)===null||a===void 0?void 0:a.getFeatureFlag(r,n,f,d,c)];case 1:return P=B.sent(),j=P!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:P=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(P),O&&(!(n in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[n].includes(M))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[n])?this.distinctIdHasSentFlagCalls[n].push(M):this.distinctIdHasSentFlagCalls[n]=[M],this.capture({distinctId:n,event:"$feature_flag_called",properties:(q={$feature_flag:r,$feature_flag_response:P,locally_evaluated:j},q["$feature/".concat(r)]=P,q),groups:f,disableGeoip:o})),[2,P]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return gC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return f=a||{},d=f.groups,c=f.personProperties,o=f.groupProperties,l=f.disableGeoip,g=a||{},O=g.onlyEvaluateLocally,g.sendFeatureFlagEvents,P=void 0,i?[3,2]:[4,this.getFeatureFlag(r,n,Gg(Gg({},a),{onlyEvaluateLocally:!0}))];case 1:i=M.sent(),M.label=2;case 2:return i?[4,(u=this.featureFlagsPoller)===null||u===void 0?void 0:u.computeFeatureFlagPayloadLocally(r,i)]:[3,4];case 3:P=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=P!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:P=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(P)]}catch{return[2,P]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return gC(this,void 0,void 0,function(){var a;return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlag(r,n,i)];case 1:return a=u.sent(),a===void 0?[2,void 0]:[2,!!a||!1]}})})},t.prototype.getAllFlags=function(r,n){return gC(this,void 0,void 0,function(){var i;return mC(this,function(a){switch(a.label){case 0:return[4,this.getAllFlagsAndPayloads(r,n)];case 1:return i=a.sent(),[2,i.featureFlags]}})})},t.prototype.getAllFlagsAndPayloads=function(r,n){var i;return gC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return a=n||{},u=a.groups,f=a.personProperties,d=a.groupProperties,c=a.disableGeoip,o=(n||{}).onlyEvaluateLocally,o==null&&(o=!1),[4,(i=this.featureFlagsPoller)===null||i===void 0?void 0:i.getAllFlagsAndPayloads(r,u,f,d)];case 1:return l=M.sent(),g={},O={},P=!0,l&&(g=l.response,O=l.payloads,P=l.fallbackToDecide),P&&!o?[4,e.prototype.getFeatureFlagsAndPayloadsStateless.call(this,r,u,f,d,c)]:[3,3];case 2:j=M.sent(),g=Gg(Gg({},g),j.flags||{}),O=Gg(Gg({},O),j.payloads||{}),M.label=3;case 3:return[2,{featureFlags:g,featureFlagPayloads:O}]}})})},t.prototype.groupIdentify=function(r){var n=r.groupType,i=r.groupKey,a=r.properties,u=r.distinctId,f=r.disableGeoip;e.prototype.groupIdentifyStateless.call(this,n,i,a,{disableGeoip:f},u)},t.prototype.reloadFeatureFlags=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){switch(n.label){case 0:return[4,(r=this.featureFlagsPoller)===null||r===void 0?void 0:r.loadFeatureFlags(!0)];case 1:return n.sent(),[2]}})})},t.prototype.shutdown=function(){this.shutdownAsync()},t.prototype.shutdownAsync=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(F1f);var mma=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gma(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.45.0-rc28",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var jvi=class{async sendEvent(){}async identify(){}async flush(){}};var _3n=require("fs/promises"),G1f=require("os"),$1f=require("path");var H1f=Xo(require("crypto")),Pma=new Uint8Array(256),Oma=Pma.length;function $0u(){return Oma>Pma.length-16&&(H1f.default.randomFillSync(Pma),Oma=0),Pma.slice(Oma,Oma+=16)}var VH=[];for(let e=0;e<256;++e)VH.push((e+256).toString(16).slice(1));function Q1f(e,t=0){return VH[e[t+0]]+VH[e[t+1]]+VH[e[t+2]]+VH[e[t+3]]+"-"+VH[e[t+4]]+VH[e[t+5]]+"-"+VH[e[t+6]]+VH[e[t+7]]+"-"+VH[e[t+8]]+VH[e[t+9]]+"-"+VH[e[t+10]]+VH[e[t+11]]+VH[e[t+12]]+VH[e[t+13]]+VH[e[t+14]]+VH[e[t+15]]}var J1f=Xo(require("crypto")),K0u={randomUUID:J1f.default.randomUUID};function Tq1(e,t,r){if(K0u.randomUUID&&!t&&!e)return K0u.randomUUID();e=e||{};let n=e.random||(e.rng||$0u)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Q1f(n)}var izr=Tq1;var Cq1="id",qq1=".fern",Dvi=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new gma(r),this.userId=t==null?void 0:nfu(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.45.0-rc28",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(y_.of((0,G1f.homedir)()),Ms.of(qq1),Ms.of(Cq1));await Wh(t)||(await(0,_3n.mkdir)((0,$1f.dirname)(t),{recursive:!0}),await(0,_3n.writeFile)(t,izr())),this.persistedDistinctId=(await(0,_3n.readFile)(t)).toString()}return this.persistedDistinctId}};var Y0u;async function h3n(){return Y0u==null&&(Y0u=await Iq1()),Y0u}async function Iq1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new jvi;let r=await K_a();return r!=null?new Dvi({token:r,posthogApiKey:e}):await $_a()!=null?new mma({posthogApiKey:e}):new Dvi({token:void 0,posthogApiKey:e})}catch{return new jvi}}function Svi(e,t){return function(){return e.apply(t,arguments)}}var{toString:Bq1}=Object.prototype,{getPrototypeOf:k0u}=Object,jma=(e=>t=>{let r=Bq1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),dIt=e=>(e=e.toLowerCase(),t=>jma(t)===e),Dma=e=>t=>typeof t===e,{isArray:y3n}=Array,Evi=Dma("undefined");function Nq1(e){return e!==null&&!Evi(e)&&e.constructor!==null&&!Evi(e.constructor)&&pDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var X1f=dIt("ArrayBuffer");function zq1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&X1f(e.buffer),t}var Rq1=Dma("string"),pDe=Dma("function"),Z1f=Dma("number"),Sma=e=>e!==null&&typeof e=="object",Fq1=e=>e===!0||e===!1,wma=e=>{if(jma(e)!=="object")return!1;let t=k0u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Lq1=dIt("Date"),Uq1=dIt("File"),Vq1=dIt("Blob"),Wq1=dIt("FileList"),Hq1=e=>Sma(e)&&pDe(e.pipe),Qq1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||pDe(e.append)&&((t=jma(e))==="formdata"||t==="object"&&pDe(e.toString)&&e.toString()==="[object FormData]"))},Jq1=dIt("URLSearchParams"),[Gq1,$q1,Kq1,Yq1]=["ReadableStream","Request","Response","Headers"].map(dIt),Xq1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Avi(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),y3n(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,f;for(n=0;n<u;n++)f=a[n],t.call(null,e[f],f,e)}}function k1f(e,t){t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var Nrn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ewf=e=>!Evi(e)&&e!==Nrn;function Z0u(){let{caseless:e}=ewf(this)&&this||{},t={},r=(n,i)=>{let a=e&&k1f(t,i)||i;wma(t[a])&&wma(n)?t[a]=Z0u(t[a],n):wma(n)?t[a]=Z0u({},n):y3n(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Avi(arguments[n],r);return t}var Zq1=(e,t,r,{allOwnKeys:n}={})=>(Avi(t,(i,a)=>{r&&pDe(i)?e[a]=Svi(i,r):e[a]=i},{allOwnKeys:n}),e),kq1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),e61=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},t61=(e,t,r,n)=>{let i,a,u,f={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)u=i[a],(!n||n(u,e,t))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&k0u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},r61=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},n61=e=>{if(!e)return null;if(y3n(e))return e;let t=e.length;if(!Z1f(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},i61=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&k0u(Uint8Array)),a61=(e,t)=>{let n=(e&&e[Symbol.iterator]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},o61=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},u61=dIt("HTMLFormElement"),s61=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),K1f=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),c61=dIt("RegExp"),twf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};Avi(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},l61=e=>{twf(e,(t,r)=>{if(pDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(pDe(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},f61=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return y3n(e)?n(e):n(String(e).split(t)),r},d61=()=>{},p61=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,X0u="abcdefghijklmnopqrstuvwxyz",Y1f="0123456789",rwf={DIGIT:Y1f,ALPHA:X0u,ALPHA_DIGIT:X0u+X0u.toUpperCase()+Y1f},_61=(e=16,t=rwf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function h61(e){return!!(e&&pDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var y61=e=>{let t=new Array(10),r=(n,i)=>{if(Sma(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=y3n(n)?[]:{};return Avi(n,(u,f)=>{let d=r(u,i+1);!Evi(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},v61=dIt("AsyncFunction"),b61=e=>e&&(Sma(e)||pDe(e))&&pDe(e.then)&&pDe(e.catch),nwf=((e,t)=>e?setImmediate:t?((r,n)=>(Nrn.addEventListener("message",({source:i,data:a})=>{i===Nrn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Nrn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",pDe(Nrn.postMessage)),g61=typeof queueMicrotask<"u"?queueMicrotask.bind(Nrn):typeof process<"u"&&process.nextTick||nwf,Jl={isArray:y3n,isArrayBuffer:X1f,isBuffer:Nq1,isFormData:Qq1,isArrayBufferView:zq1,isString:Rq1,isNumber:Z1f,isBoolean:Fq1,isObject:Sma,isPlainObject:wma,isReadableStream:Gq1,isRequest:$q1,isResponse:Kq1,isHeaders:Yq1,isUndefined:Evi,isDate:Lq1,isFile:Uq1,isBlob:Vq1,isRegExp:c61,isFunction:pDe,isStream:Hq1,isURLSearchParams:Jq1,isTypedArray:i61,isFileList:Wq1,forEach:Avi,merge:Z0u,extend:Zq1,trim:Xq1,stripBOM:kq1,inherits:e61,toFlatObject:t61,kindOf:jma,kindOfTest:dIt,endsWith:r61,toArray:n61,forEachEntry:a61,matchAll:o61,isHTMLForm:u61,hasOwnProperty:K1f,hasOwnProp:K1f,reduceDescriptors:twf,freezeMethods:l61,toObjectSet:f61,toCamelCase:s61,noop:d61,toFiniteNumber:p61,findKey:k1f,global:Nrn,isContextDefined:ewf,ALPHABET:rwf,generateString:_61,isSpecCompliantForm:h61,toJSONObject:y61,isAsyncFn:v61,isThenable:b61,setImmediate:nwf,asap:g61};function v3n(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Jl.inherits(v3n,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 iwf=v3n.prototype,awf={};["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=>{awf[e]={value:e}});Object.defineProperties(v3n,awf);Object.defineProperty(iwf,"isAxiosError",{value:!0});v3n.from=(e,t,r,n,i,a)=>{let u=Object.create(iwf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),v3n.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ny=v3n;var owf=Xo(aNr(),1),Ema=owf.default;function evu(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function swf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function uwf(e,t,r){return e?e.concat(t).map(function(i,a){return i=swf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function m61(e){return Jl.isArray(e)&&!e.some(evu)}var O61=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function P61(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(Ema||FormData),r=Jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(j,M){return!Jl.isUndefined(M[j])});let n=r.metaTokens,i=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Jl.isSpecCompliantForm(t);if(!Jl.isFunction(i))throw new TypeError("visitor must be a function");function c(P){if(P===null)return"";if(Jl.isDate(P))return P.toISOString();if(!d&&Jl.isBlob(P))throw new Ny("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(P)||Jl.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function o(P,j,M){let q=P;if(P&&!M&&typeof P=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),P=JSON.stringify(P);else if(Jl.isArray(P)&&m61(P)||(Jl.isFileList(P)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(P)))return j=swf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?uwf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return evu(P)?!0:(t.append(uwf(M,j,a),c(P)),!1)}let l=[],g=Object.assign(O61,{defaultVisitor:o,convertValue:c,isVisitable:evu});function O(P,j){if(!Jl.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(P),Jl.forEach(P,function(q,B){(!(Jl.isUndefined(q)||q===null)&&i.call(t,q,Jl.isString(B)?B.trim():B,j,g))===!0&&O(q,j?j.concat(B):[B])}),l.pop()}}if(!Jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var azr=P61;function cwf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function lwf(e,t){this._pairs=[],e&&azr(e,this,t)}var fwf=lwf.prototype;fwf.append=function(t,r){this._pairs.push([t,r])};fwf.toString=function(t){let r=t?function(n){return t.call(this,n,cwf)}:cwf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var dwf=lwf;function w61(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function zrn(e,t,r){if(!t)return e;let n=r&&r.encode||w61,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new dwf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var tvu=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.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(n){n!==null&&t(n)})}},rvu=tvu;var b3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pwf=Xo(require("url"),1),_wf=pwf.default.URLSearchParams;var hwf={isNode:!0,classes:{URLSearchParams:_wf,FormData:Ema,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var avu={};kc(avu,{hasBrowserEnv:()=>ivu,hasStandardBrowserEnv:()=>j61,hasStandardBrowserWebWorkerEnv:()=>D61,navigator:()=>nvu,origin:()=>S61});var ivu=typeof window<"u"&&typeof document<"u",nvu=typeof navigator=="object"&&navigator||void 0,j61=ivu&&(!nvu||["ReactNative","NativeScript","NS"].indexOf(nvu.product)<0),D61=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",S61=ivu&&window.location.href||"http://localhost";var b6={...avu,...hwf};function ovu(e,t){return azr(e,new b6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return b6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function E61(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function A61(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function M61(e){function t(r,n,i,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),d=a>=r.length;return u=!u&&Jl.isArray(i)?i.length:u,d?(Jl.hasOwnProp(i,u)?i[u]=[i[u],n]:i[u]=n,!f):((!i[u]||!Jl.isObject(i[u]))&&(i[u]=[]),t(r,n,i[u],a)&&Jl.isArray(i[u])&&(i[u]=A61(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(E61(n),i,r,0)}),r}return null}var Ama=M61;function x61(e,t,r){if(Jl.isString(e))try{return(t||JSON.parse)(e),Jl.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var uvu={transitional:b3n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Jl.isObject(t);if(a&&Jl.isHTMLForm(t)&&(t=new FormData(t)),Jl.isFormData(t))return i?JSON.stringify(Ama(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(n.indexOf("application/x-www-form-urlencoded")>-1)return ovu(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return azr(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),x61(t)):t}],transformResponse:[function(t){let r=this.transitional||uvu.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Jl.isResponse(t)||Jl.isReadableStream(t))return t;if(t&&Jl.isString(t)&&(n&&!this.responseType||i)){let u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?Ny.from(f,Ny.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:b6.classes.FormData,Blob:b6.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=>{uvu.headers[e]={}});var g3n=uvu;var T61=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"]),ywf=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1822
1822
|
`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),n=u.substring(i+1).trim(),!(!r||t[r]&&T61[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var vwf=Symbol("internals");function Mvi(e){return e&&String(e).trim().toLowerCase()}function Mma(e){return e===!1||e==null?e:Jl.isArray(e)?e.map(Mma):String(e)}function C61(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var q61=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function svu(e,t,r,n,i){if(Jl.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Jl.isString(t)){if(Jl.isString(n))return t.indexOf(n)!==-1;if(Jl.isRegExp(n))return n.test(t)}}function I61(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function B61(e,t){let r=Jl.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,a,u){return this[n].call(this,t,i,a,u)},configurable:!0})})}var m3n=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(f,d,c){let o=Mvi(d);if(!o)throw new Error("header name must be a non-empty string");let l=Jl.findKey(i,o);(!l||i[l]===void 0||c===!0||c===void 0&&i[l]!==!1)&&(i[l||d]=Mma(f))}let u=(f,d)=>Jl.forEach(f,(c,o)=>a(c,o,d));if(Jl.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(Jl.isString(t)&&(t=t.trim())&&!q61(t))u(ywf(t),r);else if(Jl.isHeaders(t))for(let[f,d]of t.entries())a(d,f,n);else t!=null&&a(r,t,n);return this}get(t,r){if(t=Mvi(t),t){let n=Jl.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return C61(i);if(Jl.isFunction(r))return r.call(this,i,n);if(Jl.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Mvi(t),t){let n=Jl.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||svu(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(u){if(u=Mvi(u),u){let f=Jl.findKey(n,u);f&&(!r||svu(n,n[f],f,r))&&(delete n[f],i=!0)}}return Jl.isArray(t)?t.forEach(a):a(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let a=r[n];(!t||svu(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return Jl.forEach(this,(i,a)=>{let u=Jl.findKey(n,a);if(u){r[u]=Mma(i),delete r[a];return}let f=t?I61(a):String(a).trim();f!==a&&delete r[a],r[f]=Mma(i),n[f]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Jl.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Jl.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
|
|
1823
1823
|
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let n=new this(t);return r.forEach(i=>n.set(i)),n}static accessor(t){let n=(this[vwf]=this[vwf]={accessors:{}}).accessors,i=this.prototype;function a(u){let f=Mvi(u);n[f]||(B61(i,u),n[f]=!0)}return Jl.isArray(t)?t.forEach(a):a(t),this}};m3n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Jl.reduceDescriptors(m3n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Jl.freezeMethods(m3n);var C3=m3n;function xvi(e,t){let r=this||g3n,n=t||r,i=C3.from(n.headers),a=n.data;return Jl.forEach(e,function(f){a=f.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function Tvi(e){return!!(e&&e.__CANCEL__)}function bwf(e,t,r){Ny.call(this,e??"canceled",Ny.ERR_CANCELED,t,r),this.name="CanceledError"}Jl.inherits(bwf,Ny,{__CANCEL__:!0});var _De=bwf;function d9t(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new Ny("Request failed with status code "+r.status,[Ny.ERR_BAD_REQUEST,Ny.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function cvu(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function lvu(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Rrn(e,t){return e&&!cvu(t)?lvu(e,t):t}var Nwf=Xo(mwf(),1),zwf=Xo(require("http"),1),Rwf=Xo(require("https"),1),Fwf=Xo(require("util"),1),Lwf=Xo(T_a(),1),hAr=Xo(require("zlib"),1);var Frn="1.7.7";function Cvi(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var U61=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function fvu(e,t,r){let n=r&&r.Blob||b6.classes.Blob,i=Cvi(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=U61.exec(e);if(!a)throw new Ny("Invalid URL",Ny.ERR_INVALID_URL);let u=a[1],f=a[2],d=a[3],c=Buffer.from(decodeURIComponent(d),f?"base64":"utf8");if(t){if(!n)throw new Ny("Blob is not supported",Ny.ERR_NOT_SUPPORT);return new n([c],{type:u})}return c}throw new Ny("Unsupported protocol "+i,Ny.ERR_NOT_SUPPORT)}var Lrn=Xo(require("stream"),1);var Owf=Xo(require("stream"),1);var dvu=Symbol("internals"),pvu=class extends Owf.default.Transform{constructor(t){t=Jl.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Jl.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[dvu]={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",n=>{n==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[dvu];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[dvu],a=i.maxRate,u=this.readableHighWaterMark,f=i.timeWindow,d=1e3/f,c=a/d,o=i.minChunkSize!==!1?Math.max(i.minChunkSize,c*.01):0,l=(O,P)=>{let j=Buffer.byteLength(O);i.bytesSeen+=j,i.bytes+=j,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(O)?process.nextTick(P):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(P)}},g=(O,P)=>{let j=Buffer.byteLength(O),M=null,q=u,B,I=0;if(a){let C=Date.now();(!i.ts||(I=C-i.ts)>=f)&&(i.ts=C,B=c-i.bytes,i.bytes=B<0?-B:0,I=0),B=c-i.bytes}if(a){if(B<=0)return setTimeout(()=>{P(null,O)},f-I);B<q&&(q=B)}q&&j>q&&j-q>o&&(M=O.subarray(q),O=O.subarray(0,q)),l(O,M?()=>{process.nextTick(P,null,M)}:P)};g(t,function O(P,j){if(P)return n(P);j?g(j,O):n(null)})}},_vu=pvu;var Uwf=require("events");var wwf=require("util"),jwf=require("stream");var{asyncIterator:Pwf}=Symbol,V61=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Pwf]?yield*e[Pwf]():yield e},xma=V61;var W61=Jl.ALPHABET.ALPHA_DIGIT+"-_",qvi=new wwf.TextEncoder,ozr=`\r
|
|
1824
1824
|
`,H61=qvi.encode(ozr),Q61=2,hvu=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Jl.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${ozr}`;i?r=qvi.encode(String(r).replace(/\r?\n|\r\n?/g,ozr)):a+=`Content-Type: ${r.type||"application/octet-stream"}${ozr}`,this.headers=qvi.encode(a+ozr),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+Q61,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Jl.isTypedArray(t)?yield t:yield*xma(t),yield H61}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},J61=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+Jl.generateString(i,W61)}=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=qvi.encode("--"+a+ozr),f=qvi.encode("--"+a+"--"+ozr+ozr),d=f.byteLength,c=Array.from(e.entries()).map(([l,g])=>{let O=new hvu(l,g);return d+=O.size,O});d+=u.byteLength*c.length,d=Jl.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),jwf.Readable.from(async function*(){for(let l of c)yield u,yield*l.encode();yield f}())},Dwf=J61;var Swf=Xo(require("stream"),1),yvu=class extends Swf.default.Transform{__transform(t,r,n){this.push(t),n()}_transform(t,r,n){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,r)}this.__transform(t,r,n)}},Ewf=yvu;var G61=(e,t)=>Jl.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(a){n(a)}},n)}:e,Awf=G61;function $61(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let c=Date.now(),o=n[a];u||(u=c),r[i]=d,n[i]=c;let l=a,g=0;for(;l!==i;)g+=r[l++],l=l%e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),c-u<t)return;let O=o&&c-o;return O?Math.round(g*1e3/O):void 0}}var Mwf=$61;function K61(e,t){let r=0,n=1e3/t,i,a,u=(c,o=Date.now())=>{r=o,i=null,a&&(clearTimeout(a),a=null),e.apply(null,c)};return[(...c)=>{let o=Date.now(),l=o-r;l>=n?u(c,o):(i=c,a||(a=setTimeout(()=>{a=null,u(i)},n-l)))},()=>i&&u(i)]}var xwf=K61;var _Ar=(e,t,r=3)=>{let n=0,i=Mwf(50,250);return xwf(a=>{let u=a.loaded,f=a.lengthComputable?a.total:void 0,d=u-n,c=i(d),o=u<=f;n=u;let l={loaded:u,total:f,progress:f?u/f:void 0,bytes:d,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)},P3n=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},w3n=e=>(...t)=>Jl.asap(()=>e(...t));var Twf={flush:hAr.default.constants.Z_SYNC_FLUSH,finishFlush:hAr.default.constants.Z_SYNC_FLUSH},Y61={flush:hAr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:hAr.default.constants.BROTLI_OPERATION_FLUSH},Cwf=Jl.isFunction(hAr.default.createBrotliDecompress),{http:X61,https:Z61}=Lwf.default,k61=/https:?/,qwf=b6.protocols.map(e=>e+":"),Iwf=(e,[t,r])=>(e.on("end",r).on("error",r),t);function eI1(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function Vwf(e,t,r){let n=t;if(!n&&n!==!1){let i=(0,Nwf.getProxyForUrl)(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));let a=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let i=n.hostname||n.host;e.hostname=i,e.host=i,e.port=n.port,e.path=r,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(a){Vwf(a,t,a.href)}}var tI1=typeof process<"u"&&Jl.kindOf(process)==="process",rI1=e=>new Promise((t,r)=>{let n,i,a=(d,c)=>{i||(i=!0,n&&n(d,c))},u=d=>{a(d),t(d)},f=d=>{a(d,!0),r(d)};e(u,f,d=>n=d).catch(f)}),nI1=({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)}},Bwf=(e,t)=>nI1(Jl.isObject(e)?e:{address:e,family:t}),Wwf=tI1&&function(t){return rI1(async function(n,i,a){let{data:u,lookup:f,family:d}=t,{responseType:c,responseEncoding:o}=t,l=t.method.toUpperCase(),g,O=!1,P;if(f){let or=Awf(f,jr=>Jl.isArray(jr)?jr:[jr]);f=(jr,Vr,It)=>{or(jr,Vr,(cr,fn,Gt)=>{if(cr)return It(cr);let ln=Jl.isArray(fn)?fn.map(En=>Bwf(En)):[Bwf(fn,Gt)];Vr.all?It(cr,ln):It(cr,ln[0].address,ln[0].family)})}}let j=new Uwf.EventEmitter,M=()=>{t.cancelToken&&t.cancelToken.unsubscribe(q),t.signal&&t.signal.removeEventListener("abort",q),j.removeAllListeners()};a((or,jr)=>{g=!0,jr&&(O=!0,M())});function q(or){j.emit("abort",!or||or.type?new _De(null,t,P):or)}j.once("abort",i),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(q),t.signal&&(t.signal.aborted?q():t.signal.addEventListener("abort",q)));let B=Rrn(t.baseURL,t.url),I=new URL(B,b6.hasBrowserEnv?b6.origin:void 0),C=I.protocol||qwf[0];if(C==="data:"){let or;if(l!=="GET")return d9t(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{or=fvu(t.url,c==="blob",{Blob:t.env&&t.env.Blob})}catch(jr){throw Ny.from(jr,Ny.ERR_BAD_REQUEST,t)}return c==="text"?(or=or.toString(o),(!o||o==="utf8")&&(or=Jl.stripBOM(or))):c==="stream"&&(or=Lrn.default.Readable.from(or)),d9t(n,i,{data:or,status:200,statusText:"OK",headers:new C3,config:t})}if(qwf.indexOf(C)===-1)return i(new Ny("Unsupported protocol "+C,Ny.ERR_BAD_REQUEST,t));let F=C3.from(t.headers).normalize();F.set("User-Agent","axios/"+Frn,!1);let{onUploadProgress:K,onDownloadProgress:ee}=t,J=t.maxRate,G,te;if(Jl.isSpecCompliantForm(u)){let or=F.getContentType(/boundary=([-_\w\d]{10,70})/i);u=Dwf(u,jr=>{F.set(jr)},{tag:`axios-${Frn}-boundary`,boundary:or&&or[1]||void 0})}else if(Jl.isFormData(u)&&Jl.isFunction(u.getHeaders)){if(F.set(u.getHeaders()),!F.hasContentLength())try{let or=await Fwf.default.promisify(u.getLength).call(u);Number.isFinite(or)&&or>=0&&F.setContentLength(or)}catch{}}else if(Jl.isBlob(u))u.size&&F.setContentType(u.type||"application/octet-stream"),F.setContentLength(u.size||0),u=Lrn.default.Readable.from(xma(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 i(new Ny("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Ny.ERR_BAD_REQUEST,t));if(F.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return i(new Ny("Request body larger than maxBodyLength limit",Ny.ERR_BAD_REQUEST,t))}let Ye=Jl.toFiniteNumber(F.getContentLength());Jl.isArray(J)?(G=J[0],te=J[1]):G=te=J,u&&(K||G)&&(Jl.isStream(u)||(u=Lrn.default.Readable.from(u,{objectMode:!1})),u=Lrn.default.pipeline([u,new _vu({maxRate:Jl.toFiniteNumber(G)})],Jl.noop),K&&u.on("progress",Iwf(u,P3n(Ye,_Ar(w3n(K),!1,3)))));let Re;if(t.auth){let or=t.auth.username||"",jr=t.auth.password||"";Re=or+":"+jr}if(!Re&&I.username){let or=I.username,jr=I.password;Re=or+":"+jr}Re&&F.delete("authorization");let wt;try{wt=zrn(I.pathname+I.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(or){let jr=new Error(or.message);return jr.config=t,jr.url=t.url,jr.exists=!0,i(jr)}F.set("Accept-Encoding","gzip, compress, deflate"+(Cwf?", br":""),!1);let Ct={path:wt,method:l,headers:F.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Re,protocol:C,family:d,beforeRedirect:eI1,beforeRedirects:{}};!Jl.isUndefined(f)&&(Ct.lookup=f),t.socketPath?Ct.socketPath=t.socketPath:(Ct.hostname=I.hostname.startsWith("[")?I.hostname.slice(1,-1):I.hostname,Ct.port=I.port,Vwf(Ct,t.proxy,C+"//"+I.hostname+(I.port?":"+I.port:"")+Ct.path));let Wt,Bt=k61.test(Ct.protocol);if(Ct.agent=Bt?t.httpsAgent:t.httpAgent,t.transport?Wt=t.transport:t.maxRedirects===0?Wt=Bt?Rwf.default:zwf.default:(t.maxRedirects&&(Ct.maxRedirects=t.maxRedirects),t.beforeRedirect&&(Ct.beforeRedirects.config=t.beforeRedirect),Wt=Bt?Z61:X61),t.maxBodyLength>-1?Ct.maxBodyLength=t.maxBodyLength:Ct.maxBodyLength=1/0,t.insecureHTTPParser&&(Ct.insecureHTTPParser=t.insecureHTTPParser),P=Wt.request(Ct,function(jr){if(P.destroyed)return;let Vr=[jr],It=+jr.headers["content-length"];if(ee||te){let En=new _vu({maxRate:Jl.toFiniteNumber(te)});ee&&En.on("progress",Iwf(En,P3n(It,_Ar(w3n(ee),!0,3)))),Vr.push(En)}let cr=jr,fn=jr.req||P;if(t.decompress!==!1&&jr.headers["content-encoding"])switch((l==="HEAD"||jr.statusCode===204)&&delete jr.headers["content-encoding"],(jr.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Vr.push(hAr.default.createUnzip(Twf)),delete jr.headers["content-encoding"];break;case"deflate":Vr.push(new Ewf),Vr.push(hAr.default.createUnzip(Twf)),delete jr.headers["content-encoding"];break;case"br":Cwf&&(Vr.push(hAr.default.createBrotliDecompress(Y61)),delete jr.headers["content-encoding"])}cr=Vr.length>1?Lrn.default.pipeline(Vr,Jl.noop):Vr[0];let Gt=Lrn.default.finished(cr,()=>{Gt(),M()}),ln={status:jr.statusCode,statusText:jr.statusMessage,headers:new C3(jr.headers),config:t,request:fn};if(c==="stream")ln.data=cr,d9t(n,i,ln);else{let En=[],Ht=0;cr.on("data",function(on){En.push(on),Ht+=on.length,t.maxContentLength>-1&&Ht>t.maxContentLength&&(O=!0,cr.destroy(),i(new Ny("maxContentLength size of "+t.maxContentLength+" exceeded",Ny.ERR_BAD_RESPONSE,t,fn)))}),cr.on("aborted",function(){if(O)return;let on=new Ny("maxContentLength size of "+t.maxContentLength+" exceeded",Ny.ERR_BAD_RESPONSE,t,fn);cr.destroy(on),i(on)}),cr.on("error",function(on){P.destroyed||i(Ny.from(on,null,t,fn))}),cr.on("end",function(){try{let on=En.length===1?En[0]:Buffer.concat(En);c!=="arraybuffer"&&(on=on.toString(o),(!o||o==="utf8")&&(on=Jl.stripBOM(on))),ln.data=on}catch(on){return i(Ny.from(on,null,t,ln.request,ln))}d9t(n,i,ln)})}j.once("abort",En=>{cr.destroyed||(cr.emit("error",En),cr.destroy())})}),j.once("abort",or=>{i(or),P.destroy(or)}),P.on("error",function(jr){i(Ny.from(jr,null,t,P))}),P.on("socket",function(jr){jr.setKeepAlive(!0,1e3*60)}),t.timeout){let or=parseInt(t.timeout,10);if(Number.isNaN(or)){i(new Ny("error trying to parse `config.timeout` to int",Ny.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(or,function(){if(g)return;let Vr=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",It=t.transitional||b3n;t.timeoutErrorMessage&&(Vr=t.timeoutErrorMessage),i(new Ny(Vr,It.clarifyTimeoutError?Ny.ETIMEDOUT:Ny.ECONNABORTED,t,P)),q()})}if(Jl.isStream(u)){let or=!1,jr=!1;u.on("end",()=>{or=!0}),u.once("error",Vr=>{jr=!0,P.destroy(Vr)}),u.on("close",()=>{!or&&!jr&&q(new _De("Request stream has been aborted",t,P))}),u.pipe(P)}else P.end(u)})};var Hwf=b6.hasStandardBrowserEnv?function(){let t=b6.navigator&&/(msie|trident)/i.test(b6.navigator.userAgent),r=document.createElement("a"),n;function i(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 n=i(window.location.href),function(u){let f=Jl.isString(u)?i(u):u;return f.protocol===n.protocol&&f.host===n.host}}():function(){return function(){return!0}}();var Qwf=b6.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let u=[e+"="+encodeURIComponent(t)];Jl.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),Jl.isString(n)&&u.push("path="+n),Jl.isString(i)&&u.push("domain="+i),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 Jwf=e=>e instanceof C3?{...e}:e;function pIt(e,t){t=t||{};let r={};function n(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 i(c,o,l){if(Jl.isUndefined(o)){if(!Jl.isUndefined(c))return n(void 0,c,l)}else return n(c,o,l)}function a(c,o){if(!Jl.isUndefined(o))return n(void 0,o)}function u(c,o){if(Jl.isUndefined(o)){if(!Jl.isUndefined(c))return n(void 0,c)}else return n(void 0,o)}function f(c,o,l){if(l in t)return n(c,o);if(l in e)return n(void 0,c)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:f,headers:(c,o)=>i(Jwf(c),Jwf(o),!0)};return Jl.forEach(Object.keys(Object.assign({},e,t)),function(o){let l=d[o]||i,g=l(e[o],t[o],o);Jl.isUndefined(g)&&l!==f||(r[o]=g)}),r}var Tma=e=>{let t=pIt({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:u,auth:f}=t;t.headers=u=C3.from(u),t.url=zrn(Rrn(t.baseURL,t.url),e.params,e.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):"")));let d;if(Jl.isFormData(r)){if(b6.hasStandardBrowserEnv||b6.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[c,...o]=d?d.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([c||"multipart/form-data",...o].join("; "))}}if(b6.hasStandardBrowserEnv&&(n&&Jl.isFunction(n)&&(n=n(t)),n||n!==!1&&Hwf(t.url))){let c=i&&a&&Qwf.read(a);c&&u.set(i,c)}return t};var iI1=typeof XMLHttpRequest<"u",Gwf=iI1&&function(e){return new Promise(function(r,n){let i=Tma(e),a=i.data,u=C3.from(i.headers).normalize(),{responseType:f,onUploadProgress:d,onDownloadProgress:c}=i,o,l,g,O,P;function j(){O&&O(),P&&P(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let M=new XMLHttpRequest;M.open(i.method.toUpperCase(),i.url,!0),M.timeout=i.timeout;function q(){if(!M)return;let I=C3.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),F={data:!f||f==="text"||f==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:I,config:e,request:M};d9t(function(ee){r(ee),j()},function(ee){n(ee),j()},F),M=null}"onloadend"in M?M.onloadend=q:M.onreadystatechange=function(){!M||M.readyState!==4||M.status===0&&!(M.responseURL&&M.responseURL.indexOf("file:")===0)||setTimeout(q)},M.onabort=function(){M&&(n(new Ny("Request aborted",Ny.ECONNABORTED,e,M)),M=null)},M.onerror=function(){n(new Ny("Network Error",Ny.ERR_NETWORK,e,M)),M=null},M.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",F=i.transitional||b3n;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),n(new Ny(C,F.clarifyTimeoutError?Ny.ETIMEDOUT:Ny.ECONNABORTED,e,M)),M=null},a===void 0&&u.setContentType(null),"setRequestHeader"in M&&Jl.forEach(u.toJSON(),function(C,F){M.setRequestHeader(F,C)}),Jl.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),f&&f!=="json"&&(M.responseType=i.responseType),c&&([g,P]=_Ar(c,!0),M.addEventListener("progress",g)),d&&M.upload&&([l,O]=_Ar(d),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",O)),(i.cancelToken||i.signal)&&(o=I=>{M&&(n(!I||I.type?new _De(null,e,M):I),M.abort(),M=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));let B=Cvi(i.url);if(B&&b6.protocols.indexOf(B)===-1){n(new Ny("Unsupported protocol "+B+":",Ny.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var aI1=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,a=function(c){if(!i){i=!0,f();let o=c instanceof Error?c:this.reason;n.abort(o instanceof Ny?o:new _De(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Ny(`timeout ${t} of ms exceeded`,Ny.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:d}=n;return d.unsubscribe=()=>Jl.asap(f),d}},$wf=aI1;var oI1=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let n=0,i;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},uI1=async function*(e,t){for await(let r of sI1(e))yield*oI1(r,t)},sI1=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},vvu=(e,t,r,n)=>{let i=uI1(e,t),a=0,u,f=d=>{u||(u=!0,n&&n(d))};return new ReadableStream({async pull(d){try{let{done:c,value:o}=await i.next();if(c){f(),d.close();return}let l=o.byteLength;if(r){let g=a+=l;r(g)}d.enqueue(new Uint8Array(o))}catch(c){throw f(c),c}},cancel(d){return f(d),i.return()}},{highWaterMark:2})};var qma=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Ywf=qma&&typeof ReadableStream=="function",cI1=qma&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Xwf=(e,...t)=>{try{return!!e(...t)}catch{return!1}},lI1=Ywf&&Xwf(()=>{let e=!1,t=new Request(b6.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Kwf=64*1024,bvu=Ywf&&Xwf(()=>Jl.isReadableStream(new Response("").body)),Cma={stream:bvu&&(e=>e.body)};qma&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Cma[t]&&(Cma[t]=Jl.isFunction(e[t])?r=>r[t]():(r,n)=>{throw new Ny(`Response type '${t}' is not supported`,Ny.ERR_NOT_SUPPORT,n)})})})(new Response);var fI1=async e=>{if(e==null)return 0;if(Jl.isBlob(e))return e.size;if(Jl.isSpecCompliantForm(e))return(await new Request(b6.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 cI1(e)).byteLength},dI1=async(e,t)=>{let r=Jl.toFiniteNumber(e.getContentLength());return r??fI1(t)},Zwf=qma&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:a,timeout:u,onDownloadProgress:f,onUploadProgress:d,responseType:c,headers:o,withCredentials:l="same-origin",fetchOptions:g}=Tma(e);c=c?(c+"").toLowerCase():"text";let O=$wf([i,a&&a.toAbortSignal()],u),P,j=O&&O.unsubscribe&&(()=>{O.unsubscribe()}),M;try{if(d&&lI1&&r!=="get"&&r!=="head"&&(M=await dI1(o,n))!==0){let F=new Request(t,{method:"POST",body:n,duplex:"half"}),K;if(Jl.isFormData(n)&&(K=F.headers.get("content-type"))&&o.setContentType(K),F.body){let[ee,J]=P3n(M,_Ar(w3n(d)));n=vvu(F.body,Kwf,ee,J)}}Jl.isString(l)||(l=l?"include":"omit");let q="credentials"in Request.prototype;P=new Request(t,{...g,signal:O,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:n,duplex:"half",credentials:q?l:void 0});let B=await fetch(P),I=bvu&&(c==="stream"||c==="response");if(bvu&&(f||I&&j)){let F={};["status","statusText","headers"].forEach(G=>{F[G]=B[G]});let K=Jl.toFiniteNumber(B.headers.get("content-length")),[ee,J]=f&&P3n(K,_Ar(w3n(f),!0))||[];B=new Response(vvu(B.body,Kwf,ee,()=>{J&&J(),j&&j()}),F)}c=c||"text";let C=await Cma[Jl.findKey(Cma,c)||"text"](B,e);return!I&&j&&j(),await new Promise((F,K)=>{d9t(F,K,{data:C,headers:C3.from(B.headers),status:B.status,statusText:B.statusText,config:e,request:P})})}catch(q){throw j&&j(),q&&q.name==="TypeError"&&/fetch/i.test(q.message)?Object.assign(new Ny("Network Error",Ny.ERR_NETWORK,e,P),{cause:q.cause||q}):Ny.from(q,q&&q.code,e,P)}});var gvu={http:Wwf,xhr:Gwf,fetch:Zwf};Jl.forEach(gvu,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var kwf=e=>`- ${e}`,pI1=e=>Jl.isFunction(e)||e===null||e===!1,Ima={getAdapter:e=>{e=Jl.isArray(e)?e:[e];let{length:t}=e,r,n,i={};for(let a=0;a<t;a++){r=e[a];let u;if(n=r,!pI1(r)&&(n=gvu[(u=String(r)).toLowerCase()],n===void 0))throw new Ny(`Unknown adapter '${u}'`);if(n)break;i[u||"#"+a]=n}if(!n){let a=Object.entries(i).map(([f,d])=>`adapter ${f} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
|
|
@@ -1941,7 +1941,7 @@ errors:
|
|
|
1941
1941
|
Run ${nl.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
1942
1942
|
Run ${nl.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),D3n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function bmu({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!RMf(e))return;let i=t??"",a=e.filter(f=>f.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((f,d)=>f.generatorName.localeCompare(d.generatorName)||f.currentVersion.localeCompare(d.currentVersion));for(let f of u)i+=`
|
|
1943
1943
|
${await xF1(f.generatorName)} (${f.apiName!=null?"API: "+f.apiName+", ":""}Group: ${f.generatorGroup}) `+nl.dim(f.currentVersion)+nl.reset(" \u2192 ")+nl.green(f.latestVersion);return i+=`
|
|
1944
|
-
`,n?D3n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xF1(e){let r=await new zMf.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function TF1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,c,o,l)=>{f.versions[c]==null&&(f.versions[c]={});let g=nP.getGeneratorNameOrThrow(o.name,l),O=await nP.getLatestGeneratorVersion({generatorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:i,includeMajor:a,context:l});O!=null&&(f.versions[c][o.name]={previousVersion:o.version,latestVersion:O})},generatorFilter:r,groupFilter:n}),f}let u={type:"multiApi",versions:{}};return await LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,d,c,o)=>{if(f==null)return;u.versions[f]==null&&(u.versions[f]={}),u.versions[f][d]==null&&(u.versions[f][d]={});let l=nP.getGeneratorNameOrThrow(c.name,o),g=await nP.getLatestGeneratorVersion({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:a,context:o});g!=null&&(u.versions[f][d][c.name]={previousVersion:c.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let f=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(f==null||f.groups==null)){for(let d of f.groups)if(!(i!=null&&d.groupName!==i))for(let c of d.generators)n!=null&&c.name!==n||await r(a.workspaceName,d.groupName,c,u)}})}))}function UMf(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[u,f]of Object.entries(a)){r.debug(`Checking if ${u} in group ${i} has an upgrade available...`);let d=aae(f.latestVersion,f.previousVersion);r.debug(`Latest version: ${f.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:u,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:f.previousVersion,latestVersion:f.latestVersion})}return n}async function HOa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await TF1({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(f.type==="multiApi")for(let[d,c]of Object.entries(f.versions))u.push(...UMf(c,d,t.logger));else u.push(...UMf(f.versions,void 0,t.logger))}return u}var bbi=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${i} ${a}`.trim(),f=u?`status code ${u}`:"an unknown error";super(`Request failed with ${f}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var k3n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var e7n=e=>e!==null&&typeof e=="object";var gbi=(...e)=>{for(let t of e)if((!e7n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Omu({},...e)},gmu=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,u]of i.entries())n&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function QOa(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Omu(e[r]??[],t[r]??[])}var mmu=(e={},t={})=>({beforeRequest:QOa(e,t,"beforeRequest"),beforeRetry:QOa(e,t,"beforeRetry"),afterResponse:QOa(e,t,"afterResponse"),beforeError:QOa(e,t,"beforeError")}),Omu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(e7n(i)){for(let[a,u]of Object.entries(i))e7n(u)&&a in t&&(u=Omu(t[a],u)),t={...t,[a]:u};e7n(i.hooks)&&(n=mmu(n,i.hooks),t.hooks=n),e7n(i.headers)&&(r=gmu(r,i.headers),t.headers=r)}return t};var VMf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),WMf=typeof globalThis.AbortController=="function",HMf=typeof globalThis.ReadableStream=="function",QMf=typeof globalThis.FormData=="function",JOa=["get","post","put","patch","head","delete"],CF1=()=>{};CF1();var JMf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},GOa=2147483647,$Oa=Symbol("stop"),GMf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},$Mf={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var YMf=e=>JOa.includes(e)?e.toUpperCase():e,qF1=["get","put","head","delete","options","trace"],IF1=[408,413,429,500,502,503,504],BF1=[413,429,503],KMf={limit:2,methods:qF1,statusCodes:IF1,afterStatusCodes:BF1,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},XMf=(e={})=>{if(typeof e=="number")return{...KMf,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...KMf,...e}};async function Pmu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new k3n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function wmu(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var ZMf=(e,t)=>{let r={};for(let n in t)!(n in $Mf)&&!(n in GMf)&&!(n in e)&&(r[n]=t[n]);return r};var mbi=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>GOa)throw new RangeError(`The \`timeout\` option cannot be greater than ${GOa}`);await Promise.resolve();let f=await n._fetch();for(let d of n._options.hooks.afterResponse){let c=await d(n.request,n._options,n._decorateResponse(f.clone()));c instanceof globalThis.Response&&(f=c)}if(n._decorateResponse(f),!f.ok&&n._options.throwHttpErrors){let d=new bbi(f,n.request,n._options);for(let c of n._options.hooks.beforeError)d=await c(d);throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!HMf)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(f.clone(),n._options.onDownloadProgress)}return f},u=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i();for(let[f,d]of Object.entries(JMf))u[f]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||d);let o=(await u).clone();if(f==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[f]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:gmu(this._input.headers,r.headers),hooks:mmu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:YMf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:XMf(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(WMf){this.abortController=new globalThis.AbortController;let n=this._options.signal??this._input.signal;n?.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(VMf&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(QMf&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof k3n)throw t;if(t instanceof bbi){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),GOa);if(this._retryCount<1)throw r;await wmu(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===$Oa)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=ZMf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Pmu(r,t,this.abortController,this._options)}_stream(t,r){let n=Number(t.headers.get("content-length"))||0,i=0;return t.status===204?(r&&r({percent:1,totalBytes:n,transferredBytes:i},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function f(){let{done:d,value:c}=await u.read();if(d){a.close();return}if(r){i+=c.byteLength;let o=n===0?0:i/n;r({percent:o,transferredBytes:i,totalBytes:n},c)}a.enqueue(c),await f()}await f()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var jmu=e=>{let t=(r,n)=>mbi.create(r,gbi(e,n));for(let r of JOa)t[r]=(n,i)=>mbi.create(n,gbi(e,i,{method:r}));return t.create=r=>jmu(gbi(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),jmu(gbi(e,r))),t.stop=$Oa,t},NF1=jmu(),kMf=NF1;var Pxf=Xo(Oxf(),1);function Mmu(e){let t=(0,Pxf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var u2f=Xo(hTf(),1),s2f=Xo(o2f(),1),uOu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},sOu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function cOu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??Mmu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,u2f.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,f&&(d.authorization=`${f.type} ${f.token}`);let c;try{c=await kMf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new uOu(e):l}if(t.allVersions)return c;let o=new sOu(e,r);if(c["dist-tags"][r]){let{time:l}=c;c=c.versions[c["dist-tags"][r]],c.time=l}else if(r){let l=!!c.versions[r];if(n&&!l)for(let[O,P]of Object.entries(c.versions))P.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=s2f.default.maxSatisfying(O,r),!r)throw o}let{time:g}=c;if(c=c.versions[r],c.time=g,!c)throw o}return c}async function qbi(e,t){let{version:r}=await cOu(e.toLowerCase(),t);return r}async function c7n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:qbi(e.packageName,{version:t?"prerelease":"latest"})}var c2f=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],yPa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=KA.Info;constructor(t){this.ttyAwareLogger=new WOa(t);let r=this.getPackageName(),n=this.getPackageVersion(),i=this.getCliName();(r==null||n==null||i==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:n,cliName:i}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.45.0-rc26"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${nl.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nTe}failWithoutThrowing(t,r){this.didSucceed=!1,FOa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await h3n()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await FMf({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1944
|
+
`,n?D3n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xF1(e){let r=await new zMf.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function TF1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,c,o,l)=>{f.versions[c]==null&&(f.versions[c]={});let g=nP.getGeneratorNameOrThrow(o.name,l),O=await nP.getLatestGeneratorVersion({generatorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:i,includeMajor:a,context:l});O!=null&&(f.versions[c][o.name]={previousVersion:o.version,latestVersion:O})},generatorFilter:r,groupFilter:n}),f}let u={type:"multiApi",versions:{}};return await LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,d,c,o)=>{if(f==null)return;u.versions[f]==null&&(u.versions[f]={}),u.versions[f][d]==null&&(u.versions[f][d]={});let l=nP.getGeneratorNameOrThrow(c.name,o),g=await nP.getLatestGeneratorVersion({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:a,context:o});g!=null&&(u.versions[f][d][c.name]={previousVersion:c.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function LMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let f=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(f==null||f.groups==null)){for(let d of f.groups)if(!(i!=null&&d.groupName!==i))for(let c of d.generators)n!=null&&c.name!==n||await r(a.workspaceName,d.groupName,c,u)}})}))}function UMf(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[u,f]of Object.entries(a)){r.debug(`Checking if ${u} in group ${i} has an upgrade available...`);let d=aae(f.latestVersion,f.previousVersion);r.debug(`Latest version: ${f.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:u,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:f.previousVersion,latestVersion:f.latestVersion})}return n}async function HOa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await TF1({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(f.type==="multiApi")for(let[d,c]of Object.entries(f.versions))u.push(...UMf(c,d,t.logger));else u.push(...UMf(f.versions,void 0,t.logger))}return u}var bbi=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${i} ${a}`.trim(),f=u?`status code ${u}`:"an unknown error";super(`Request failed with ${f}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var k3n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var e7n=e=>e!==null&&typeof e=="object";var gbi=(...e)=>{for(let t of e)if((!e7n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Omu({},...e)},gmu=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,u]of i.entries())n&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function QOa(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Omu(e[r]??[],t[r]??[])}var mmu=(e={},t={})=>({beforeRequest:QOa(e,t,"beforeRequest"),beforeRetry:QOa(e,t,"beforeRetry"),afterResponse:QOa(e,t,"afterResponse"),beforeError:QOa(e,t,"beforeError")}),Omu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(e7n(i)){for(let[a,u]of Object.entries(i))e7n(u)&&a in t&&(u=Omu(t[a],u)),t={...t,[a]:u};e7n(i.hooks)&&(n=mmu(n,i.hooks),t.hooks=n),e7n(i.headers)&&(r=gmu(r,i.headers),t.headers=r)}return t};var VMf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),WMf=typeof globalThis.AbortController=="function",HMf=typeof globalThis.ReadableStream=="function",QMf=typeof globalThis.FormData=="function",JOa=["get","post","put","patch","head","delete"],CF1=()=>{};CF1();var JMf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},GOa=2147483647,$Oa=Symbol("stop"),GMf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},$Mf={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var YMf=e=>JOa.includes(e)?e.toUpperCase():e,qF1=["get","put","head","delete","options","trace"],IF1=[408,413,429,500,502,503,504],BF1=[413,429,503],KMf={limit:2,methods:qF1,statusCodes:IF1,afterStatusCodes:BF1,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},XMf=(e={})=>{if(typeof e=="number")return{...KMf,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...KMf,...e}};async function Pmu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new k3n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function wmu(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var ZMf=(e,t)=>{let r={};for(let n in t)!(n in $Mf)&&!(n in GMf)&&!(n in e)&&(r[n]=t[n]);return r};var mbi=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>GOa)throw new RangeError(`The \`timeout\` option cannot be greater than ${GOa}`);await Promise.resolve();let f=await n._fetch();for(let d of n._options.hooks.afterResponse){let c=await d(n.request,n._options,n._decorateResponse(f.clone()));c instanceof globalThis.Response&&(f=c)}if(n._decorateResponse(f),!f.ok&&n._options.throwHttpErrors){let d=new bbi(f,n.request,n._options);for(let c of n._options.hooks.beforeError)d=await c(d);throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!HMf)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(f.clone(),n._options.onDownloadProgress)}return f},u=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i();for(let[f,d]of Object.entries(JMf))u[f]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||d);let o=(await u).clone();if(f==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[f]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:gmu(this._input.headers,r.headers),hooks:mmu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:YMf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:XMf(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(WMf){this.abortController=new globalThis.AbortController;let n=this._options.signal??this._input.signal;n?.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(VMf&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(QMf&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof k3n)throw t;if(t instanceof bbi){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),GOa);if(this._retryCount<1)throw r;await wmu(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===$Oa)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=ZMf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Pmu(r,t,this.abortController,this._options)}_stream(t,r){let n=Number(t.headers.get("content-length"))||0,i=0;return t.status===204?(r&&r({percent:1,totalBytes:n,transferredBytes:i},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function f(){let{done:d,value:c}=await u.read();if(d){a.close();return}if(r){i+=c.byteLength;let o=n===0?0:i/n;r({percent:o,transferredBytes:i,totalBytes:n},c)}a.enqueue(c),await f()}await f()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var jmu=e=>{let t=(r,n)=>mbi.create(r,gbi(e,n));for(let r of JOa)t[r]=(n,i)=>mbi.create(n,gbi(e,i,{method:r}));return t.create=r=>jmu(gbi(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),jmu(gbi(e,r))),t.stop=$Oa,t},NF1=jmu(),kMf=NF1;var Pxf=Xo(Oxf(),1);function Mmu(e){let t=(0,Pxf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var u2f=Xo(hTf(),1),s2f=Xo(o2f(),1),uOu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},sOu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function cOu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??Mmu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,u2f.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,f&&(d.authorization=`${f.type} ${f.token}`);let c;try{c=await kMf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new uOu(e):l}if(t.allVersions)return c;let o=new sOu(e,r);if(c["dist-tags"][r]){let{time:l}=c;c=c.versions[c["dist-tags"][r]],c.time=l}else if(r){let l=!!c.versions[r];if(n&&!l)for(let[O,P]of Object.entries(c.versions))P.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=s2f.default.maxSatisfying(O,r),!r)throw o}let{time:g}=c;if(c=c.versions[r],c.time=g,!c)throw o}return c}async function qbi(e,t){let{version:r}=await cOu(e.toLowerCase(),t);return r}async function c7n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:qbi(e.packageName,{version:t?"prerelease":"latest"})}var c2f=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],yPa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=KA.Info;constructor(t){this.ttyAwareLogger=new WOa(t);let r=this.getPackageName(),n=this.getPackageVersion(),i=this.getCliName();(r==null||n==null||i==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:n,cliName:i}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.45.0-rc28"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${nl.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nTe}failWithoutThrowing(t,r){this.didSucceed=!1,FOa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await h3n()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await FMf({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1945
1945
|
`)||(r+=`
|
|
1946
1946
|
`),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=xKo(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.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 fbi(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 n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw a.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,a),new nTe}finally{n.finish()}return i}async instrumentPostHogEvent(t){(await h3n()).sendEvent(t)}logger=Lpi(this.log.bind(this));constructTaskInitForWorkspace(t){let r=l2f(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?l2f(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=c2f[this.numTasks++%c2f.length],u=nl.hex(a)(i);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===E4.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(n=>x3r.indexOf(n.level)>=x3r.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===KA.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 c7n({cliEnvironment:this.environment,includePreReleases:t}),n=aae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await HOa({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}};function l2f(e){return`[${e}]:`}var Rqf=Xo(zqf(),1);async function wDe(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:a={},...u}={}){let f=i.reduce((o,l)=>({...o,[l]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,l]of Object.entries(f))d=d.replaceAll(o,l);e?.debug(`+ ${d}`);let c=(0,Rqf.default)(t,r,u);return n||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr)),c}function jPa(e,{logger:t,...r}={}){return(n,i)=>wDe(t,e,n,{...r,...i})}var SPa=require("fs/promises"),Fqf=Xo(zne(),1),EH1="buf.gen.yaml",Lqf="output",AH1=`${Lqf}/openapi.yaml`,MH1=`
|
|
1947
1947
|
version: v1
|
|
@@ -1953,8 +1953,8 @@ plugins:
|
|
|
1953
1953
|
- enum_type=string
|
|
1954
1954
|
- default_response=false
|
|
1955
1955
|
`,DPa=class{context;constructor({context:t}){this.context=t}async generate({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,local:n}){return n?this.generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r}):this.generateRemote()}async generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r}){let n=await this.setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t}),i=jq(t,r);return this.doGenerateLocal({cwd:n,target:i})}async setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t}){let r=y_.of((await Fqf.default.dir()).path);return await(0,SPa.cp)(t,r,{recursive:!0}),await(0,SPa.writeFile)(yf(r,Ms.of(EH1)),MH1),r}async doGenerateLocal({cwd:t,target:r}){let n=jPa("which",{cwd:t,logger:this.context.logger});try{await n(["buf"])}catch{this.context.failAndThrow("Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').")}try{await n(["protoc-gen-openapi"])}catch{this.context.failAndThrow("Missing required dependency; please install 'protoc-gen-openapi' to continue (e.g. 'brew install go && go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest').")}let i=jPa("buf",{cwd:t,logger:this.context.logger});return await i(["config","init"]),await i(["generate",r]),yf(t,Ms.of(AH1))}async generateRemote(){this.context.failAndThrow("Remote Protobuf generation is unimplemented.")}};async function _nn({context:e,specs:t,relativePathToDependency:r}){let n=new DPa({context:e}),i=t.filter(f=>f.type==="openapi").map(f=>({...f,relativePathToDependency:r})),a=t.filter(f=>f.type==="protobuf"),u=await Promise.all(a.map(async f=>xH1({generator:n,protobufSpec:f,relativePathToDependency:r})));return[...i,...u]}async function xH1({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var p1u=Xo(Otn(),1);var RBf=require("fs"),R7n=require("fs/promises");var FBf=require("os"),LBf=Xo(require("path"),1),UBf=require("stream/promises"),VBf=Xo(q1a(),1),WBf=Xo(zne(),1);var Dj;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(Dj||(Dj={}));var oG1=HEr();async function HBf({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:n,cliVersion:i,settings:a,loadAPIWorkspace:u}){let f,d={type:Dj.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},c=t.dependencies[e];return c==null?d={type:Dj.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${pG1(c)}`},async o=>{switch(c.type){case"version":f=await fG1({context:o,dependency:c,cliVersion:i,settings:a,loadAPIWorkspace:u});return;case"local":f=await lG1({context:o,dependency:c,cliVersion:i,settings:a,loadAPIWorkspace:u});return;default:xc(c)}}),f!=null?{didSucceed:!0,definition:f}:{didSucceed:!1,failure:d}}var QBf="dependencies";var uG1="metadata.json",sG1=".fern";function cG1(e){return yf(y_.of((0,FBf.homedir)()),Ms.of(sG1),Ms.of(QBf),Ms.of(e.organization),Ms.of(e.apiName),Ms.of(e.version))}async function lG1({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){if(i==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await i({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Ms.of(e.path)},n);return t.logger.info("Loaded..."),u}async function fG1({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){let a=cG1(e),u=yf(a,Ms.of(QBf)),f=yf(a,Ms.of(uG1)),d;if(!await Wh(u)||!await Wh(f)){t.logger.info("Downloading manifest...");let l=await oG1.definitionRegistry.get(p1u.FernFiddle.OrganizationId(e.organization),p1u.FernFiddle.ApiId(e.apiName),e.version);if(!l.ok){l.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:j=>{t.failWithoutThrowing("Failed to download API manifest",j)}});return}let g=l.body.yamlSchemaVersion!=null?parseInt(l.body.yamlSchemaVersion):void 0,O=inn(r),P=inn(l.body.cliVersion);if(g!=null){if(g>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${l.body.cliVersion}`);return}else if(g<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(O.major!==P.major||O.minor!==P.minor){t.failWithoutThrowing(`CLI version is ${l.body.cliVersion}. Expected ${O.major}.${O.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+l.body.definitionS3DownloadUrl),await(0,R7n.mkdir)(u,{recursive:!0});try{await dG1({s3PreSignedReadUrl:l.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(j){t.failWithoutThrowing("Failed to download API",j);return}d=l.body,await(0,R7n.writeFile)(f,JSON.stringify(d))}else d=JSON.parse((await(0,R7n.readFile)(f)).toString());if(t.logger.info("Parsing..."),i==null){t.failWithoutThrowing("Failed to load API");return}let c=await i({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!c.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",c.failures);return}if(c.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await c.workspace.getDefinition({context:t},n)}async function dG1({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await hN.get(e,{responseType:"stream"}),n=await WBf.default.dir(),i=LBf.default.join(n.path,"api.tgz");await(0,UBf.pipeline)(r.data,(0,RBf.createWriteStream)(i)),await(0,VBf.extract)({file:i,cwd:t})}function pG1(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:xc(e)}}var i4f=Xo(y1u(),1);function I1a(e,t){for(let[r,n]of b8(e))hG1({relativeFilepath:r,failure:n,logger:t})}function hG1({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case Dj.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case Dj.FILE_READ:r.error("Failed to open file: "+e);break;case Dj.FILE_MISSING:r.error("Missing file: "+e);break;case Dj.FILE_PARSE:t.error instanceof $pi?r.error(c6t({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case Dj.STRUCTURE_VALIDATION:for(let n of t.error.issues)for(let{title:i,subtitle:a}of yG1(n))r.error(c6t({title:i,subtitle:a,breadcrumbs:[e,...n.path]}));break;case Dj.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case Dj.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${tZi}: `+t.dependencyName);break;case Dj.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case Dj.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case Dj.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(c6t({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(n=>n!=="")]}));break;default:xc(t)}}function yG1(e){switch(e.code){case r_.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${nl.underline(e.expected)} but received ${nl.underline(e.received)}`}];case r_.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${nl.underline(t)}`}));case r_.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>nl.underline(t)).join(", ")}`}];case r_.invalid_union:case r_.invalid_arguments:case r_.invalid_return_type:case r_.invalid_date:case r_.invalid_string:case r_.too_small:case r_.too_big:case r_.invalid_intersection_types:case r_.not_multiple_of:case r_.custom:default:return[{title:e.message}]}}var XBf=require("fs/promises");async function ZBf(e,t){let r=[];for(let n of await tTe(e,t))r.push(await vG1({relativeFilepath:jq(e,n),absoluteFilepath:n}));return r}async function vG1({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,XBf.readFile)(t)).toString()}}async function kBf(e){let t={},r={};function n(i){try{t[i.relativeFilepath]={defaultUrl:void 0,contents:d0.load(i.fileContents,{schema:d0.CORE_SCHEMA}),rawContents:i.fileContents}}catch(a){r[i.relativeFilepath]={type:Dj.FILE_PARSE,error:a}}}return await Promise.all(e.map(n)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function e4f({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:n,settings:i,loadAPIWorkspace:a}){let u={},f={},d={};return await Promise.all(b8(t.packageMarkers).map(async([c,o])=>{if(o.contents.export==null)u[c]=o;else{let{export:l,...g}=o.contents;if(Q8t(g)>0)d[c]={type:Dj.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:c};else{let O=cb(c);if(R8t(t.namedDefinitionFiles).some(j=>j!==c&&j.startsWith(O)))d[c]={type:Dj.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:O};else{let j=await HBf({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:n,settings:i,loadAPIWorkspace:a});j.didSucceed?f[cb(c)]={definition:j.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[c]=j.failure}}}})),Q8t(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:f}}var t4f=Xo(require("path"),1);var v1u={};kc(v1u,{additionalProperties:()=>mG1,default:()=>PG1,definitions:()=>OG1,properties:()=>gG1,type:()=>bG1});var bG1="object",gG1={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},mG1=!1,OG1={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.TypeReferenceDeclarationWithName":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceDeclarationWithNameSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDeclarationWithName"}]},"types.ObjectPropertySchema":{$ref:"#/definitions/types.TypeReferenceDeclarationWithNameSchema"},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithContentTypeSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithContentTypeSchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},PG1={type:bG1,properties:gG1,additionalProperties:mG1,definitions:OG1};var b1u={};kc(b1u,{additionalProperties:()=>SG1,default:()=>AG1,definitions:()=>EG1,properties:()=>jG1,required:()=>DG1,type:()=>wG1});var wG1="object",jG1={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},DG1=["name"],SG1=!1,EG1={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},AG1={type:wG1,properties:jG1,required:DG1,additionalProperties:SG1,definitions:EG1};var g1u={};kc(g1u,{additionalProperties:()=>TG1,default:()=>qG1,definitions:()=>CG1,properties:()=>xG1,type:()=>MG1});var MG1="object",xG1={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},TG1=!1,CG1={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.TypeReferenceDeclarationWithName":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceDeclarationWithNameSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDeclarationWithName"}]},"types.ObjectPropertySchema":{$ref:"#/definitions/types.TypeReferenceDeclarationWithNameSchema"},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithContentTypeSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithContentTypeSchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},qG1={type:MG1,properties:xG1,additionalProperties:TG1,definitions:CG1};function r4f({files:e,absolutePathToDefinition:t}){let r,n={},i={},a={};for(let[u,f]of b8(e)){let d=f.contents,c=o=>{a[u]={type:Dj.JSONSCHEMA_VALIDATION,error:o}};if(u===m5){let o=ppi(d,b1u);if(o.success){let l=zie.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:l["default-url"],contents:l,rawContents:f.rawContents}}else c(o)}else if(t4f.default.basename(u)===$A){let o=ppi(d,g1u);if(o.success){let l=zie.serialization.PackageMarkerFileSchema.parseOrThrow(d);i[u]={defaultUrl:typeof l.export=="object"?l.export.url:void 0,contents:l,rawContents:f.rawContents}}else c(o)}else{let o=ppi(d,v1u);if(o.success){let l=zie.serialization.DefinitionFileSchema.parseOrThrow(d);n[u]={defaultUrl:void 0,contents:l,rawContents:f.rawContents,absoluteFilePath:yf(t,u)}}else c(o)}}return r==null?{didSucceed:!1,failures:{[Ms.of(m5)]:{type:Dj.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:n,rootApiFile:r,packageMarkers:i}}var jIt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;type="api";constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:n,absoluteFilePath:i,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=n,this.absoluteFilePath=i,this.changelog=a}};var DIt=class extends jIt{definition;sources;constructor({definition:t,sources:r,...n}){super(n),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};function Izr(e,t={}){return{...Object.fromEntries(b8(e.namedDefinitionFiles).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...b8(e.importedDefinitions).reduce((r,[n,i])=>({...r,...zdi(Izr(i.definition,{defaultURL:i.url}),(a,u)=>yf(n,Ms.of(u)))}),{})}}function ugi(e,t={}){return{...Object.fromEntries(b8(e.packageMarkers).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...b8(e.importedDefinitions).reduce((r,[n,i])=>({...r,...zdi(ugi(i.definition,{defaultURL:i.url}),(a,u)=>yf(n,Ms.of(u)))}),{})}}function BAr(e){return{...ugi(e),...Izr(e)}}function lae(e,t){return BAr(e.definition)[t]?.contents}var n4f=Xo(require("path"),1);async function W8(e,t){for(let[r,n]of b8(BAr(e.definition)))await t(r,n.contents,{isPackageMarker:n4f.default.basename(r)===$A,defaultUrl:n.defaultUrl})}async function Enn(e,t){for(let[r,n]of b8(ugi(e.definition)))await t(r,n.contents)}var U7n=class extends jIt{context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...n}){super(n),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let n=(0,i4f.default)(r??{}),i=this.fernWorkspaces[n];if(i==null){let a=t||this.context,u=yf(this.absoluteFilePath,Ms.of(QL)),f=await tki.loadDependenciesConfiguration({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await ZBf(u,"{yml,yaml}"),c=await kBf(d);if(!c.didSucceed)return I1a(c.failures,a.logger),a.failAndThrow();let o=r4f({files:c.files,absolutePathToDefinition:u});if(!o.didSucceed)return I1a(o.failures,a.logger),a.failAndThrow();let l=await e4f({dependenciesConfiguration:f,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!l.didSucceed)return I1a(l.failures,a.logger),a.failAndThrow();i=new DIt({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:f,workspaceName:this.workspaceName,definition:{absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:l.packageMarkers,importedDefinitions:l.importedDefinitions},cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[n]=i}return i}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var NAr={openapi:e=>({...e,type:"openapi",_visit:function(t){return NAr._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return NAr._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 V7n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return V7n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var PU={basic:e=>({...e,type:"basic",_visit:function(t){return PU._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return PU._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return PU._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return PU._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return PU._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 i1={primitive:e=>({value:e,type:"primitive",_visit:function(t){return i1._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return i1._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return i1._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return i1._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return i1._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return i1._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return i1._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return i1._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 h0={int:e=>({value:e,type:"int",_visit:function(t){return h0._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return h0._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return h0._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return h0._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return h0._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return h0._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return h0._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return h0._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return h0._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return h0._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return h0._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 W7n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return W7n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return W7n._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 Bzr={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return Bzr._visit(this,t)}}),undisciminated:e=>({value:e,type:"undisciminated",_visit:function(t){return Bzr._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 JH={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case JH.GenerallyAvailable:return t.generallyAvailable();case JH.Beta:return t.beta();case JH.Deprecated:return t.deprecated();default:return t._other()}}};var zAr={cursor:e=>({...e,type:"cursor",_visit:function(t){return zAr._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return zAr._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 RAr={language:e=>({...e,type:"language",_visit:function(t){return RAr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return RAr._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 GH={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 GH.Curl:return t.curl();case GH.Python:return t.python();case GH.Javascript:return t.javascript();case GH.Typescript:return t.typescript();case GH.Go:return t.go();case GH.Ruby:return t.ruby();case GH.Csharp:return t.csharp();case GH.Java:return t.java();case GH.Js:return t.js();case GH.Node:return t.node();case GH.Ts:return t.ts();case GH.Nodets:return t.nodets();case GH.Golang:return t.golang();case GH.Dotnet:return t.dotnet();case GH.Jvm:return t.jvm();default:return t._other()}}};var SIt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return SIt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return SIt._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 EIt={withStreaming:e=>({value:e,type:"withStreaming",_visit(t){return EIt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit(t){return EIt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e.value);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var C$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case C$.Get:return t.get();case C$.Post:return t.post();case C$.Put:return t.put();case C$.Patch:return t.patch();case C$.Delete:return t.delete();case C$.Head:return t.head();case C$.Options:return t.options();case C$.Trace:return t.trace();default:return t._other()}}};var Nzr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Nzr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Nzr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Nzr._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 g2e={file:e=>({...e,type:"file",_visit:function(t){return g2e._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return g2e._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 fae={file:e=>({...e,type:"file",_visit:function(t){return fae._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return fae._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return fae._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return fae._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return fae._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return fae._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 gb={primitive:e=>({...e,type:"primitive",_visit:function(t){return gb._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return gb._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return gb._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return gb._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return gb._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return gb._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return gb._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return gb._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return gb._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return gb._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return gb._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 jD={int:e=>({...e,type:"int",_visit:function(t){return jD._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return jD._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return jD._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return jD._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return jD._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return jD._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return jD._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return jD._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return jD._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return jD._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return jD._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 DB={boolean:e=>({value:e,type:"boolean",_visit:function(t){return DB._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return DB._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 FAr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return FAr._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return FAr._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 m2e={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return m2e._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return m2e._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return m2e._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 SB={file:e=>({...e,type:"file",_visit(t){return SB._visit(this,t)}}),json:e=>({...e,type:"json",_visit(t){return SB._visit(this,t)}}),text:e=>({...e,type:"text",_visit(t){return SB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit(t){return SB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit(t){return SB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit(t){return SB._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 Gp={primitive:e=>({...e,type:"primitive",_visit:function(t){return Gp._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Gp._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Gp._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Gp._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Gp._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Gp._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Gp._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Gp._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Gp._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Gp._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Gp._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 uk={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return uk._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return uk._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 Ay={int:e=>({...e,type:"int",_visit:function(t){return Ay._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Ay._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return Ay._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return Ay._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return Ay._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return Ay._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Ay._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return Ay._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return Ay._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return Ay._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Ay._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 qg={};kc(qg,{AllOfPropertyConflict:()=>cNn,ArraySchema:()=>Gwa,ArraySchemaWithExample:()=>Oja,Availability:()=>H1a,Base64WithExample:()=>yja,BasicSecurityScheme:()=>G1a,BearerSecurityScheme:()=>$1a,BooleanSchema:()=>Uwa,BooleanWithExample:()=>vja,CasingOverrides:()=>X1a,CommonProperty:()=>tja,CommonPropertyWithExample:()=>xja,CursorPagination:()=>Swa,CustomCodeSample:()=>jwa,CustomCodeSampleLanguage:()=>Owa,CustomCodeSampleSdk:()=>wwa,DateWithExample:()=>hja,DatetimeWithExample:()=>_ja,DiscriminatedOneOfSchema:()=>kwa,DiscriminatedOneOfSchemaWithExample:()=>Aja,DoubleSchema:()=>Fwa,DoubleWithExample:()=>dja,Encoding:()=>W1a,Endpoint:()=>Awa,EndpointExample:()=>oNn,EndpointResponseExample:()=>mwa,EndpointSdkName:()=>Hzr,EndpointWithExample:()=>q4f,EnumSchema:()=>$7n,EnumSchemaWithExample:()=>gja,EnumValue:()=>Fzr,ErrorExample:()=>ywa,FernExample:()=>bwa,FileResponse:()=>rNn,FileSchema:()=>lwa,FloatWithExample:()=>fja,FullEndpointExample:()=>Dwa,FullExample:()=>Y2,FullObjectExample:()=>awa,FullOneOfExample:()=>uwa,GlobalHeader:()=>Wwa,Header:()=>Wzr,HeaderExample:()=>aNn,HeaderSecurityScheme:()=>K1a,HeaderWithExample:()=>dNn,HttpEndpointServer:()=>nNn,HttpError:()=>vwa,HttpErrorWithExample:()=>oja,HttpMethod:()=>X7n,IdempotencyHeader:()=>Hwa,Int64WithExample:()=>sja,IntSchema:()=>zwa,IntWithExample:()=>uja,JsonRequest:()=>pwa,JsonRequestWithExample:()=>nja,JsonResponse:()=>Qzr,JsonResponseWithExample:()=>fgi,KeyValuePair:()=>owa,LiteralExample:()=>iwa,LiteralSchema:()=>sNn,LiteralSchemaValue:()=>Qwa,LongSchema:()=>Rwa,MapSchema:()=>$wa,MapSchemaWithExample:()=>Pja,MultipartRequest:()=>tNn,MultipartRequestProperty:()=>dwa,MultipartSchema:()=>fwa,NamedFullExample:()=>A9t,Namespace:()=>Z1a,NamespaceId:()=>nwa,NullableSchema:()=>Ywa,NullableSchemaWithExample:()=>jja,OauthSecurityScheme:()=>ewa,ObjectProperty:()=>Zwa,ObjectPropertyConflictInfo:()=>lNn,ObjectPropertyWithExample:()=>Eja,ObjectSchema:()=>Jwa,ObjectSchemaWithExample:()=>Dja,OctetStreamRequest:()=>eNn,OffsetPagination:()=>Ewa,OneOfSchema:()=>Xwa,OneOfSchemaWithExample:()=>Sja,OpenApiIntermediateRepresentation:()=>T4f,OpenApiSource:()=>F1a,OptionalSchema:()=>Kwa,OptionalSchemaWithExample:()=>wja,Pagination:()=>uNn,PathParameter:()=>Z7n,PathParameterExample:()=>gwa,PathParameterWithExample:()=>rja,PrimitiveExample:()=>Y7n,PrimitiveSchema:()=>Gzr,PrimitiveSchemaValue:()=>Vwa,PrimitiveSchemaValueWithExample:()=>bja,PrimitiveSchemaWithExample:()=>pNn,PropertyKey:()=>K7n,ProtobufEncoding:()=>V1a,ProtobufSource:()=>L1a,QueryParameter:()=>k7n,QueryParameterExample:()=>iNn,QueryParameterWithExample:()=>fNn,QuerySecurityScheme:()=>Y1a,ReferencedSchema:()=>E9t,Request:()=>_wa,RequestWithExample:()=>ija,Response:()=>hwa,ResponseWithExample:()=>aja,Schema:()=>X1,SchemaId:()=>sk,SchemaWithExample:()=>KC,Schemas:()=>Nwa,SdkGroup:()=>k1a,SdkGroupInfo:()=>swa,SdkGroupName:()=>Lzr,SecurityScheme:()=>twa,SecuritySchemeId:()=>J1a,Server:()=>rwa,Source:()=>U1a,StatusCode:()=>Uzr,StringSchema:()=>Lwa,StringSchemaWithExample:()=>pja,SupportedSdkLanguage:()=>Pwa,Tag:()=>Q1a,TagId:()=>EDe,Tags:()=>cwa,TextResponse:()=>Jzr,Uint64WithExample:()=>lja,UintWithExample:()=>cja,UnDiscriminatedOneOfSchema:()=>eja,UnDiscriminatedOneOfSchemaWithExample:()=>Mja,UnknownSchemaWithExample:()=>mja,Webhook:()=>Twa,WebhookExampleCall:()=>xwa,WebhookHttpMethod:()=>Mwa,WebsocketChannel:()=>Bwa,WebsocketHandshake:()=>Cwa,WebsocketHandshakeWithExample:()=>C4f,WebsocketMessageExample:()=>qwa,WebsocketSessionExample:()=>Iwa,WithAvailability:()=>hv,WithDescription:()=>M_,WithEncoding:()=>dae,WithName:()=>pO,WithNamespace:()=>Vzr,WithSdkGroupName:()=>Y1,WithSource:()=>xb,WithTitle:()=>K1,commons:()=>j1u,example:()=>D1u,finalIr:()=>S1u,parseIr:()=>E1u});var j1u={};kc(j1u,{BasicSecurityScheme:()=>G1a,BearerSecurityScheme:()=>$1a,Encoding:()=>W1a,HeaderSecurityScheme:()=>K1a,Namespace:()=>Z1a,NamespaceId:()=>nwa,OauthSecurityScheme:()=>ewa,OpenApiSource:()=>F1a,ProtobufEncoding:()=>V1a,ProtobufSource:()=>L1a,QuerySecurityScheme:()=>Y1a,SchemaId:()=>sk,SdkGroup:()=>k1a,SdkGroupName:()=>Lzr,SecurityScheme:()=>twa,SecuritySchemeId:()=>J1a,Server:()=>rwa,Source:()=>U1a,StatusCode:()=>Uzr,Tag:()=>Q1a,TagId:()=>EDe,WithAvailability:()=>hv,WithDescription:()=>M_,WithEncoding:()=>dae,WithName:()=>pO,WithNamespace:()=>Vzr,WithSdkGroupName:()=>Y1,WithSource:()=>xb,WithTitle:()=>K1});var Fn={};kc(Fn,{JsonError:()=>H7n,ParseError:()=>Q7n,any:()=>b4f,boolean:()=>g4f,booleanLiteral:()=>v4f,date:()=>o4f,discriminant:()=>A4f,enum_:()=>N1a,getObjectLikeUtils:()=>S9t,getObjectUtils:()=>G7n,getSchemaUtils:()=>g6,isProperty:()=>Rzr,lazy:()=>u4f,lazyObject:()=>_4f,list:()=>R1a,number:()=>m4f,object:()=>z1a,objectWithoutOptionalProperties:()=>p4f,optional:()=>m1u,property:()=>c4f,record:()=>j4f,set:()=>D4f,string:()=>O4f,stringLiteral:()=>y4f,transform:()=>O1u,undiscriminatedUnion:()=>E4f,union:()=>x4f,unknown:()=>P4f,withParsedProperties:()=>w1u});var vE={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 K2(e,t){return`Expected ${t}. Received ${IG1(e)}.`}function IG1(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 q$(e){return{...e,json:a4f(e.json),parse:a4f(e.parse)}}function a4f(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
1956
|
-
`)),{ok:!0,value:t}):n}}function B1a(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var H7n=class e extends Error{errors;constructor(t){super(t.map(B1a).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Q7n=class e extends Error{errors;constructor(t){super(t.map(B1a).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function g6(e){return{optional:()=>m1u(e),transform:t=>O1u(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Q7n(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new H7n(n.errors)}}}function m1u(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>vE.OPTIONAL};return{...t,...g6(t)}}function O1u(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...g6(r)}}var BG1=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function o4f(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:K2(t,"string")}]}:BG1.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:K2(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:K2(t,"Date object")}]},getType:()=>vE.DATE};return{...q$(e),...g6(e)}}function I$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...q$(r),...g6(r)}}}function N1a(e){let t=new Set(e);return I$(vE.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:K2(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:K2(n,"enum")}]}:{ok:!0,value:n})()}function u4f(e){let t=P1u(e);return{...t,...g6(t)}}function P1u(e){return{parse:(t,r)=>J7n(e).parse(t,r),json:(t,r)=>J7n(e).json(t,r),getType:()=>J7n(e).getType()}}function J7n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function sgi(e){return Object.entries(e)}function cgi(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function zzr(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function lgi(e){return Object.keys(e)}function s4f(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function S9t(e){return{withParsedProperties:t=>w1u(e,t)}}function w1u(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let u=Object.entries(t).reduce((f,[d,c])=>({...f,[d]:typeof c=="function"?c(a.value):c}),{});return{ok:!0,value:{...a.value,...u}}},json:(n,i)=>{if(!zzr(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:K2(n,"object")}]};let a=new Set(Object.keys(t)),u=cgi(n,Object.keys(n).filter(f=>!a.has(f)));return e.json(u,i)},getType:()=>e.getType()};return{...r,...g6(r),...S9t(r)}}function c4f(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Rzr(e){return e.isProperty}function z1a(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>Rzr(n)?n.rawKey:r),_getParsedProperties:()=>lgi(e),parse:(r,n)=>{let i={},a=[];for(let[u,f]of sgi(e)){let d=Rzr(f)?f.rawKey:u,c=Rzr(f)?f.valueSchema:f,o={rawKey:d,parsedKey:u,valueSchema:c};i[d]=o,d4f(c)&&a.push(d)}return l4f({value:r,requiredKeys:a,getProperty:u=>{let f=i[u];if(f!=null)return{transformedKey:f.parsedKey,transform:d=>f.valueSchema.parse(d,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,u]of sgi(e)){let f=Rzr(u)?u.valueSchema:u;d4f(f)&&i.push(a)}return l4f({value:r,requiredKeys:i,getProperty:a=>{let u=e[a];if(u!=null)return Rzr(u)?{transformedKey:u.rawKey,transform:f=>u.valueSchema.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:f=>u.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>vE.OBJECT};return{...q$(t),...g6(t),...S9t(t),...G7n(t)}}function l4f({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!zzr(e))return{ok:!1,errors:[{path:a,message:K2(e,"object")}]};let u=new Set(t),f=[],d={};for(let[c,o]of Object.entries(e)){let l=r(c);if(l!=null){u.delete(c);let g=l.transform(o);g.ok?d[l.transformedKey]=g.value:(d[c]=o,f.push(...g.errors))}else switch(n){case"fail":f.push({path:[...a,c],message:`Unexpected key "${c}"`});break;case"strip":break;case"passthrough":d[c]=o;break}}return f.push(...t.filter(c=>u.has(c)).map(c=>({path:a,message:`Missing required key "${c}"`}))),f.length===0||i?{ok:!0,value:d}:{ok:!1,errors:f}}function G7n(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>f4f({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>f4f({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>vE.OBJECT};return{...r,...g6(r),...S9t(r),...G7n(r)}}}}function f4f({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,u]=s4f(lgi(t),c=>i.has(c)),f=r(cgi(t,u)),d=n(cgi(t,a));return f.ok&&d.ok?{ok:!0,value:{...f.value,...d.value}}:{ok:!1,errors:[...f.ok?[]:f.errors,...d.ok?[]:d.errors]}}function d4f(e){return!NG1(e)}function NG1(e){switch(e.getType()){case vE.ANY:case vE.UNKNOWN:case vE.OPTIONAL:return!0;default:return!1}}function p4f(e){return z1a(e)}function _4f(e){let t={...P1u(e),_getRawProperties:()=>J7n(e)._getRawProperties(),_getParsedProperties:()=>J7n(e)._getParsedProperties()};return{...t,...g6(t),...S9t(t),...G7n(t)}}function R1a(e){let t={parse:(r,n)=>h4f(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>h4f(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>vE.LIST};return{...q$(t),...g6(t)}}function h4f(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:K2(e,"list"),path:[]}]}}function y4f(e){return I$(vE.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:K2(r,`"${e}"`)}]})()}function v4f(e){return I$(vE.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:K2(r,`${e.toString()}`)}]})()}var b4f=I$(vE.ANY,e=>({ok:!0,value:e}));var g4f=I$(vE.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"boolean")}]});var m4f=I$(vE.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"number")}]});var O4f=I$(vE.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"string")}]});var P4f=I$(vE.UNKNOWN,e=>({ok:!0,value:e}));function j4f(e,t){let r={parse:(n,i)=>w4f({value:n,isKeyNumeric:e.getType()===vE.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>w4f({value:n,isKeyNumeric:e.getType()===vE.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>vE.RECORD};return{...q$(r),...g6(r)}}function w4f({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return zzr(e)?sgi(e).reduce((a,[u,f])=>{if(f==null)return a;let d=a,c=u;if(t){let O=u.length>0?Number(u):NaN;isNaN(O)||(c=O)}let o=r(c),l=n(f,c);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let g=[];return d.ok||g.push(...d.errors),o.ok||g.push(...o.errors),l.ok||g.push(...l.errors),{ok:!1,errors:g}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:K2(e,"object")}]}}function D4f(e){let t=R1a(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:K2(n,"Set")}]},getType:()=>vE.SET};return{...q$(r),...g6(r)}}function E4f(e){let t={parse:(r,n)=>S4f((i,a)=>i.parse(r,a),e,n),json:(r,n)=>S4f((i,a)=>i.json(r,a),e,n),getType:()=>vE.UNDISCRIMINATED_UNION};return{...q$(t),...g6(t)}}function S4f(e,t,r){let n=[];for(let[i,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let f of u.errors)n.push({path:f.path,message:`[Variant ${i}] ${f.message}`})}return{ok:!1,errors:n}}function A4f(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function x4f(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=N1a(lgi(t)),a={parse:(u,f)=>M4f({value:u,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:d=>i.parse(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.parse(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),json:(u,f)=>M4f({value:u,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:d=>i.json(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.json(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),getType:()=>vE.UNION};return{...q$(a),...g6(a),...S9t(a)}}function M4f({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:f=[]}){if(!zzr(e))return{ok:!1,errors:[{path:f,message:K2(e,"object")}]};let{[t]:d,...c}=e;if(d==null)return{ok:!1,errors:[{path:f,message:`Missing discriminant ("${t}")`}]};let o=n(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=i(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...c}}:{ok:!1,errors:[{path:[...f,t],message:"Unexpected discriminant value"}]};let g=u(c,l);return g.ok?{ok:!0,value:{[r]:d,...g.value}}:g}var K1=Fn.objectWithoutOptionalProperties({title:Fn.string().optional()});var F1a=Fn.objectWithoutOptionalProperties({file:Fn.string()});var L1a=Fn.objectWithoutOptionalProperties({file:Fn.string()});var U1a=Fn.union("type",{openapi:F1a,protobuf:L1a}).transform({transform:e=>{switch(e.type){case"openapi":return NAr.openapi(e);case"protobuf":return NAr.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var xb=Fn.objectWithoutOptionalProperties({source:U1a.optional()});var V1a=Fn.objectWithoutOptionalProperties({typeName:Fn.string()});var W1a=Fn.union("type",{protobuf:V1a}).transform({transform:e=>{switch(e.type){case"protobuf":return V7n.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var dae=Fn.objectWithoutOptionalProperties({encoding:W1a.optional()});var M_=Fn.objectWithoutOptionalProperties({description:Fn.string().optional()});var H1a=Fn.enum_(["GenerallyAvailable","Beta","Deprecated"]);var hv=Fn.objectWithoutOptionalProperties({availability:H1a.optional()});var pO=Fn.objectWithoutOptionalProperties({nameOverride:Fn.string().optional(),generatedName:Fn.string()});var sk=Fn.string();var EDe=Fn.string();var Q1a=Fn.objectWithoutOptionalProperties({id:EDe}).extend(M_);var J1a=Fn.string();var G1a=Fn.objectWithoutOptionalProperties({usernameVariableName:Fn.string().optional(),usernameEnvVar:Fn.string().optional(),passwordVariableName:Fn.string().optional(),passwordEnvVar:Fn.string().optional()});var $1a=Fn.objectWithoutOptionalProperties({tokenVariableName:Fn.string().optional(),tokenEnvVar:Fn.string().optional()});var K1a=Fn.objectWithoutOptionalProperties({headerName:Fn.string(),prefix:Fn.string().optional(),headerVariableName:Fn.string().optional(),headerEnvVar:Fn.string().optional()});var Y1a=Fn.objectWithoutOptionalProperties({queryParameterName:Fn.string()});var X1a=Fn.objectWithoutOptionalProperties({snake:Fn.string().optional(),camel:Fn.string().optional(),screamingSnake:Fn.string().optional(),pascal:Fn.string().optional()});var Fzr=Fn.objectWithoutOptionalProperties({nameOverride:Fn.string().optional(),generatedName:Fn.string(),value:Fn.string(),casing:X1a.optional()}).extend(M_).extend(hv);var Z1a=Fn.objectWithoutOptionalProperties({type:Fn.stringLiteral("namespace"),name:Fn.string()});var k1a=Fn.undiscriminatedUnion([Fn.string(),Z1a]);var Lzr=Fn.list(k1a);var Y1=Fn.objectWithoutOptionalProperties({groupName:Lzr.optional()});var $7n=Fn.objectWithoutOptionalProperties({default:Fzr.optional(),values:Fn.list(Fzr)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var ewa=Fn.objectWithoutOptionalProperties({scopesEnum:$7n.optional()});var twa=Fn.union("type",{basic:G1a,bearer:$1a,header:K1a,query:Y1a,oauth:ewa}).transform({transform:e=>{switch(e.type){case"basic":return PU.basic(e);case"bearer":return PU.bearer(e);case"header":return PU.header(e);case"query":return PU.query(e);case"oauth":return PU.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Uzr=Fn.number();var rwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),url:Fn.string(),audiences:Fn.list(Fn.string()).optional()}).extend(M_);var nwa=Fn.string();var Vzr=Fn.objectWithoutOptionalProperties({namespace:Fn.string().optional()});var D1u={};kc(D1u,{FullExample:()=>Y2,FullObjectExample:()=>awa,FullOneOfExample:()=>uwa,KeyValuePair:()=>owa,LiteralExample:()=>iwa,PrimitiveExample:()=>Y7n,PropertyKey:()=>K7n});var K7n=Fn.string();var Y7n=Fn.union("type",{int:Fn.object({value:Fn.number()}),int64:Fn.object({value:Fn.number()}),uint:Fn.object({value:Fn.number()}),uint64:Fn.object({value:Fn.number()}),float:Fn.object({value:Fn.number()}),double:Fn.object({value:Fn.number()}),string:Fn.object({value:Fn.string()}),datetime:Fn.object({value:Fn.string()}),date:Fn.object({value:Fn.string()}),base64:Fn.object({value:Fn.string()}),boolean:Fn.object({value:Fn.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return h0.int(e.value);case"int64":return h0.int64(e.value);case"uint":return h0.uint(e.value);case"uint64":return h0.uint64(e.value);case"float":return h0.float(e.value);case"double":return h0.double(e.value);case"string":return h0.string(e.value);case"datetime":return h0.datetime(e.value);case"date":return h0.date(e.value);case"base64":return h0.base64(e.value);case"boolean":return h0.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var iwa=Fn.union("type",{boolean:Fn.object({value:Fn.boolean()}),string:Fn.object({value:Fn.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return W7n.boolean(e.value);case"string":return W7n.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Y2=Fn.union("type",{primitive:Fn.object({value:Y7n}),object:Fn.lazyObject(()=>awa),array:Fn.object({value:Fn.list(Fn.lazy(()=>Y2))}),map:Fn.object({value:Fn.list(Fn.lazyObject(()=>owa))}),enum:Fn.object({value:Fn.string()}),literal:Fn.object({value:iwa}),oneOf:Fn.object({value:Fn.lazy(()=>uwa)}),unknown:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"primitive":return i1.primitive(e.value);case"object":return i1.object(e);case"array":return i1.array(e.value);case"map":return i1.map(e.value);case"enum":return i1.enum(e.value);case"literal":return i1.literal(e.value);case"oneOf":return i1.oneOf(e.value);case"unknown":return i1.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var awa=Fn.objectWithoutOptionalProperties({properties:Fn.record(K7n,Fn.lazy(()=>Y2))});var owa=Fn.objectWithoutOptionalProperties({key:Y7n,value:Fn.lazy(()=>Y2)});var uwa=Fn.union("type",{discriminated:Fn.object({value:Fn.record(K7n,Fn.lazy(()=>Y2))}),undisciminated:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"discriminated":return Bzr.discriminated(e.value);case"undisciminated":return Bzr.undisciminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var S1u={};kc(S1u,{AllOfPropertyConflict:()=>cNn,ArraySchema:()=>Gwa,Availability:()=>H1a,BooleanSchema:()=>Uwa,CasingOverrides:()=>X1a,CommonProperty:()=>tja,CursorPagination:()=>Swa,CustomCodeSample:()=>jwa,CustomCodeSampleLanguage:()=>Owa,CustomCodeSampleSdk:()=>wwa,DiscriminatedOneOfSchema:()=>kwa,DoubleSchema:()=>Fwa,Endpoint:()=>Awa,EndpointExample:()=>oNn,EndpointResponseExample:()=>mwa,EndpointSdkName:()=>Hzr,EnumSchema:()=>$7n,EnumValue:()=>Fzr,ErrorExample:()=>ywa,FernExample:()=>bwa,FileResponse:()=>rNn,FileSchema:()=>lwa,FullEndpointExample:()=>Dwa,GlobalHeader:()=>Wwa,Header:()=>Wzr,HeaderExample:()=>aNn,HttpEndpointServer:()=>nNn,HttpError:()=>vwa,HttpMethod:()=>X7n,IdempotencyHeader:()=>Hwa,IntSchema:()=>zwa,JsonRequest:()=>pwa,JsonResponse:()=>Qzr,LiteralSchema:()=>sNn,LiteralSchemaValue:()=>Qwa,LongSchema:()=>Rwa,MapSchema:()=>$wa,MultipartRequest:()=>tNn,MultipartRequestProperty:()=>dwa,MultipartSchema:()=>fwa,NullableSchema:()=>Ywa,ObjectProperty:()=>Zwa,ObjectPropertyConflictInfo:()=>lNn,ObjectSchema:()=>Jwa,OctetStreamRequest:()=>eNn,OffsetPagination:()=>Ewa,OneOfSchema:()=>Xwa,OpenApiIntermediateRepresentation:()=>T4f,OptionalSchema:()=>Kwa,Pagination:()=>uNn,PathParameter:()=>Z7n,PathParameterExample:()=>gwa,PrimitiveSchema:()=>Gzr,PrimitiveSchemaValue:()=>Vwa,QueryParameter:()=>k7n,QueryParameterExample:()=>iNn,ReferencedSchema:()=>E9t,Request:()=>_wa,Response:()=>hwa,Schema:()=>X1,Schemas:()=>Nwa,SdkGroupInfo:()=>swa,StringSchema:()=>Lwa,SupportedSdkLanguage:()=>Pwa,Tags:()=>cwa,TextResponse:()=>Jzr,UnDiscriminatedOneOfSchema:()=>eja,Webhook:()=>Twa,WebhookExampleCall:()=>xwa,WebhookHttpMethod:()=>Mwa,WebsocketChannel:()=>Bwa,WebsocketHandshake:()=>Cwa,WebsocketMessageExample:()=>qwa,WebsocketSessionExample:()=>Iwa});var swa=Fn.objectWithoutOptionalProperties({summary:Fn.string().optional(),description:Fn.string().optional()});var cwa=Fn.objectWithoutOptionalProperties({tagsById:Fn.record(EDe,Q1a),orderedTagIds:Fn.list(EDe).optional()});var X7n=Fn.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var Z7n=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),variableReference:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var k7n=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var Wzr=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),env:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var Hzr=Fn.objectWithoutOptionalProperties({groupName:Lzr,methodName:Fn.string()});var eNn=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var lwa=Fn.objectWithoutOptionalProperties({isOptional:Fn.boolean(),isArray:Fn.boolean()});var fwa=Fn.union("type",{file:lwa,json:Fn.object({value:Fn.lazy(()=>X1)})}).transform({transform:e=>{switch(e.type){case"file":return g2e.file(e);case"json":return g2e.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var dwa=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:fwa,contentType:Fn.string().optional()}).extend(M_);var tNn=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),properties:Fn.list(dwa)}).extend(M_).extend(xb);var pwa=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1),contentType:Fn.string().optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(xb);var _wa=Fn.union("type",{octetStream:eNn,multipart:tNn,json:pwa}).transform({transform:e=>{switch(e.type){case"octetStream":return Nzr.octetStream(e);case"multipart":return Nzr.multipart(e);case"json":return Nzr.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var rNn=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var Qzr=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1),responseProperty:Fn.string().optional()}).extend(M_).extend(xb);var Jzr=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var hwa=Fn.union("type",{file:rNn,json:Qzr,text:Jzr,streamingSse:Qzr,streamingText:Jzr,streamingJson:Qzr}).transform({transform:e=>{switch(e.type){case"file":return fae.file(e);case"json":return fae.json(e);case"text":return fae.text(e);case"streamingSse":return fae.streamingSse(e);case"streamingText":return fae.streamingText(e);case"streamingJson":return fae.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var ywa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),description:Fn.string().optional(),example:Fn.lazy(()=>Y2)});var vwa=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1).optional(),examples:Fn.list(ywa).optional()}).extend(M_).extend(pO).extend(xb);var nNn=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),url:Fn.string().optional(),audiences:Fn.list(Fn.string()).optional()});var bwa=Fn.unknown();var gwa=Fn.objectWithoutOptionalProperties({name:Fn.string(),parameterNameOverride:Fn.string().optional(),value:Fn.lazy(()=>Y2)});var iNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),value:Fn.lazy(()=>Y2)});var aNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),value:Fn.lazy(()=>Y2)});var mwa=Fn.union("type",{withStreaming:Fn.object({value:Fn.list(Fn.lazy(()=>Y2))}),withoutStreaming:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return EIt.withStreaming(e.value);case"withoutStreaming":return EIt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Owa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),language:Fn.string(),code:Fn.string(),install:Fn.string().optional()}).extend(M_);var Pwa=Fn.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var wwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),sdk:Pwa,code:Fn.string()}).extend(M_);var jwa=Fn.union("type",{language:Owa,sdk:wwa}).transform({transform:e=>{switch(e.type){case"language":return RAr.language(e);case"sdk":return RAr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),pathParameters:Fn.list(gwa).optional(),queryParameters:Fn.list(iNn).optional(),headers:Fn.list(aNn).optional(),request:Fn.lazy(()=>Y2).optional(),response:mwa.optional(),codeSamples:Fn.list(jwa)}).extend(M_);var oNn=Fn.union("type",{unknown:Fn.object({value:bwa}),full:Dwa}).transform({transform:e=>{switch(e.type){case"unknown":return SIt.unknown(e.value);case"full":return SIt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Swa=Fn.objectWithoutOptionalProperties({cursor:Fn.string(),nextCursor:Fn.property("next_cursor",Fn.string()),results:Fn.string()});var Ewa=Fn.objectWithoutOptionalProperties({offset:Fn.string(),results:Fn.string(),step:Fn.string().optional(),hasNextPage:Fn.string().optional()});var uNn=Fn.union("type",{cursor:Swa,offset:Ewa}).transform({transform:e=>{switch(e.type){case"cursor":return zAr.cursor(e);case"offset":return zAr.offset(e);default:return e}},untransform:({_visit:e,...t})=>t});var Awa=Fn.objectWithoutOptionalProperties({authed:Fn.boolean(),internal:Fn.boolean().optional(),idempotent:Fn.boolean().optional(),method:X7n,audiences:Fn.list(Fn.string()),path:Fn.string(),summary:Fn.string().optional(),operationId:Fn.string().optional(),tags:Fn.list(EDe),pathParameters:Fn.list(Z7n),queryParameters:Fn.list(k7n),headers:Fn.list(Wzr),sdkName:Hzr.optional(),generatedRequestName:Fn.string(),requestNameOverride:Fn.string().optional(),request:_wa.optional(),response:hwa.optional(),errors:Fn.record(Uzr,vwa),server:Fn.list(nNn),examples:Fn.list(oNn),pagination:uNn.optional()}).extend(M_).extend(hv).extend(xb).extend(Vzr);var Mwa=Fn.enum_(["GET","POST"]);var xwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),payload:Fn.lazy(()=>Y2)}).extend(M_);var Twa=Fn.objectWithoutOptionalProperties({sdkName:Hzr.optional(),method:Mwa,summary:Fn.string().optional(),operationId:Fn.string(),tags:Fn.list(EDe),headers:Fn.list(Wzr),generatedPayloadName:Fn.string(),payload:Fn.lazy(()=>X1),examples:Fn.list(xwa)}).extend(M_).extend(xb).extend(Vzr);var Cwa=Fn.objectWithoutOptionalProperties({queryParameters:Fn.list(k7n),headers:Fn.list(Wzr),pathParameters:Fn.list(Z7n)});var qwa=Fn.objectWithoutOptionalProperties({messageType:Fn.string(),payload:Fn.lazy(()=>Y2)}).extend(M_);var Iwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),queryParameters:Fn.list(iNn).optional(),headers:Fn.list(aNn).optional(),messages:Fn.list(qwa)}).extend(M_);var Bwa=Fn.objectWithoutOptionalProperties({path:Fn.string(),groupName:Lzr,summary:Fn.string().optional(),handshake:Cwa,publish:Fn.lazy(()=>X1).optional(),subscribe:Fn.lazy(()=>X1).optional(),examples:Fn.list(Iwa)}).extend(M_).extend(xb);var Nwa=Fn.objectWithoutOptionalProperties({rootSchemas:Fn.record(sk,Fn.lazy(()=>X1)),namespacedSchemas:Fn.record(nwa,Fn.record(sk,Fn.lazy(()=>X1)))});var zwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional()});var Rwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional()});var Fwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional()});var Lwa=Fn.objectWithoutOptionalProperties({default:Fn.string().optional(),pattern:Fn.string().optional(),format:Fn.string().optional(),minLength:Fn.number().optional(),maxLength:Fn.number().optional()});var Uwa=Fn.objectWithoutOptionalProperties({default:Fn.boolean().optional()});var Vwa=Fn.union("type",{int:zwa,int64:Rwa,uint:Fn.object({}),uint64:Fn.object({}),float:Fn.object({}),double:Fwa,string:Lwa,datetime:Fn.object({}),date:Fn.object({}),base64:Fn.object({}),boolean:Uwa}).transform({transform:e=>{switch(e.type){case"int":return jD.int(e);case"int64":return jD.int64(e);case"uint":return jD.uint();case"uint64":return jD.uint64();case"float":return jD.float();case"double":return jD.double(e);case"string":return jD.string(e);case"datetime":return jD.datetime();case"date":return jD.date();case"base64":return jD.base64();case"boolean":return jD.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var Gzr=Fn.objectWithoutOptionalProperties({schema:Vwa}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Wwa=Fn.objectWithoutOptionalProperties({header:Fn.string(),name:Fn.string().optional(),optional:Fn.boolean().optional(),env:Fn.string().optional(),schema:Fn.lazy(()=>X1).optional()});var Hwa=Fn.objectWithoutOptionalProperties({header:Fn.string(),name:Fn.string().optional(),env:Fn.string().optional(),schema:Fn.lazy(()=>X1).optional()});var T4f=Fn.objectWithoutOptionalProperties({apiVersion:Fn.unknown().optional(),title:Fn.string().optional(),description:Fn.string().optional(),basePath:Fn.string().optional(),servers:Fn.list(rwa),groups:Fn.record(Fn.string(),swa),tags:cwa,hasEndpointsMarkedInternal:Fn.boolean(),endpoints:Fn.list(Awa),webhooks:Fn.list(Twa),channel:Fn.list(Bwa),groupedSchemas:Nwa,variables:Fn.record(Fn.string(),Gzr),nonRequestReferencedSchemas:Fn.set(sk),securitySchemes:Fn.record(J1a,twa),globalHeaders:Fn.list(Wwa).optional(),idempotencyHeaders:Fn.list(Hwa).optional()});var E9t=Fn.objectWithoutOptionalProperties({schema:sk}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var Qwa=Fn.union("type",{boolean:Fn.object({value:Fn.boolean()}),string:Fn.object({value:Fn.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return DB.boolean(e.value);case"string":return DB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var sNn=Fn.objectWithoutOptionalProperties({value:Qwa}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var X1=Fn.union("type",{primitive:Gzr,object:Fn.lazyObject(()=>Jwa),array:Fn.lazyObject(()=>Gwa),map:Fn.lazyObject(()=>$wa),optional:Fn.lazyObject(()=>Kwa),enum:$7n,reference:E9t,literal:sNn,oneOf:Fn.object({value:Fn.lazy(()=>Xwa)}),nullable:Fn.lazyObject(()=>Ywa),unknown:pO}).transform({transform:e=>{switch(e.type){case"primitive":return gb.primitive(e);case"object":return gb.object(e);case"array":return gb.array(e);case"map":return gb.map(e);case"optional":return gb.optional(e);case"enum":return gb.enum(e);case"reference":return gb.reference(e);case"literal":return gb.literal(e);case"oneOf":return gb.oneOf(e.value);case"nullable":return gb.nullable(e);case"unknown":return gb.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var cNn=Fn.objectWithoutOptionalProperties({propertyKey:Fn.string(),allOfSchemaIds:Fn.list(sk),conflictingTypeSignatures:Fn.boolean()});var Jwa=Fn.objectWithoutOptionalProperties({allOf:Fn.list(E9t),properties:Fn.list(Fn.lazyObject(()=>Zwa)),allOfPropertyConflicts:Fn.list(cNn),additionalProperties:Fn.boolean()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var lNn=Fn.objectWithoutOptionalProperties({differentSchema:Fn.boolean()});var Zwa=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>X1),readonly:Fn.boolean().optional(),conflict:Fn.record(sk,lNn),generatedName:Fn.string(),nameOverride:Fn.string().optional(),audiences:Fn.list(Fn.string())}).extend(hv);var Gwa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var $wa=Fn.objectWithoutOptionalProperties({key:Gzr,value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(K1);var Kwa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Ywa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Xwa=Fn.union("type",{discriminated:Fn.lazyObject(()=>kwa),undisciminated:Fn.lazyObject(()=>eja)}).transform({transform:e=>{switch(e.type){case"discriminated":return FAr.discriminated(e);case"undisciminated":return FAr.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var kwa=Fn.objectWithoutOptionalProperties({discriminantProperty:Fn.string(),commonProperties:Fn.list(Fn.lazyObject(()=>tja)),schemas:Fn.record(Fn.string(),Fn.lazy(()=>X1))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var tja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>X1)});var eja=Fn.objectWithoutOptionalProperties({schemas:Fn.list(Fn.lazy(()=>X1))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var E1u={};kc(E1u,{ArraySchemaWithExample:()=>Oja,Base64WithExample:()=>yja,BooleanWithExample:()=>vja,CommonPropertyWithExample:()=>xja,DateWithExample:()=>hja,DatetimeWithExample:()=>_ja,DiscriminatedOneOfSchemaWithExample:()=>Aja,DoubleWithExample:()=>dja,EndpointWithExample:()=>q4f,EnumSchemaWithExample:()=>gja,FloatWithExample:()=>fja,HeaderWithExample:()=>dNn,HttpErrorWithExample:()=>oja,Int64WithExample:()=>sja,IntWithExample:()=>uja,JsonRequestWithExample:()=>nja,JsonResponseWithExample:()=>fgi,MapSchemaWithExample:()=>Pja,NamedFullExample:()=>A9t,NullableSchemaWithExample:()=>jja,ObjectPropertyWithExample:()=>Eja,ObjectSchemaWithExample:()=>Dja,OneOfSchemaWithExample:()=>Sja,OptionalSchemaWithExample:()=>wja,PathParameterWithExample:()=>rja,PrimitiveSchemaValueWithExample:()=>bja,PrimitiveSchemaWithExample:()=>pNn,QueryParameterWithExample:()=>fNn,RequestWithExample:()=>ija,ResponseWithExample:()=>aja,SchemaWithExample:()=>KC,StringSchemaWithExample:()=>pja,Uint64WithExample:()=>lja,UintWithExample:()=>cja,UnDiscriminatedOneOfSchemaWithExample:()=>Mja,UnknownSchemaWithExample:()=>mja,WebsocketHandshakeWithExample:()=>C4f});var A9t=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),value:Fn.unknown()}).extend(M_);var fNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var dNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),env:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var C4f=Fn.objectWithoutOptionalProperties({queryParameters:Fn.list(fNn),headers:Fn.list(dNn)});var rja=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),variableReference:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var nja=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>KC),contentType:Fn.string().optional(),fullExamples:Fn.list(A9t).optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(xb);var ija=Fn.union("type",{octetStream:eNn,multipart:tNn,json:nja}).transform({transform:e=>{switch(e.type){case"octetStream":return m2e.octetStream(e);case"multipart":return m2e.multipart(e);case"json":return m2e.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var fgi=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>KC),responseProperty:Fn.string().optional(),fullExamples:Fn.list(A9t).optional()}).extend(M_).extend(xb);var aja=Fn.union("type",{file:rNn,json:fgi,text:Jzr,streamingSse:Qzr,streamingText:Jzr,streamingJson:fgi}).transform({transform:e=>{switch(e.type){case"file":return SB.file(e);case"json":return SB.json(e);case"text":return SB.text(e);case"streamingSse":return SB.streamingSse(e);case"streamingText":return SB.streamingText(e);case"streamingJson":return SB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var oja=Fn.objectWithoutOptionalProperties({statusCode:Uzr,schema:Fn.lazy(()=>KC),fullExamples:Fn.list(A9t).optional()}).extend(M_).extend(pO).extend(xb);var q4f=Fn.objectWithoutOptionalProperties({authed:Fn.boolean(),internal:Fn.boolean().optional(),idempotent:Fn.boolean().optional(),method:X7n,audiences:Fn.list(Fn.string()),path:Fn.string(),summary:Fn.string().optional(),operationId:Fn.string().optional(),tags:Fn.list(EDe),pathParameters:Fn.list(rja),queryParameters:Fn.list(fNn),headers:Fn.list(dNn),sdkName:Hzr.optional(),generatedRequestName:Fn.string(),requestNameOverride:Fn.string().optional(),request:ija.optional(),response:aja.optional(),errors:Fn.record(Uzr,oja),server:Fn.list(nNn),examples:Fn.list(oNn),pagination:uNn.optional()}).extend(M_).extend(hv).extend(xb).extend(Vzr);var uja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional(),example:Fn.number().optional()});var sja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var cja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var lja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var fja=Fn.objectWithoutOptionalProperties({example:Fn.number().optional()});var dja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional(),example:Fn.number().optional()});var pja=Fn.objectWithoutOptionalProperties({default:Fn.string().optional(),pattern:Fn.string().optional(),format:Fn.string().optional(),minLength:Fn.number().optional(),maxLength:Fn.number().optional(),example:Fn.string().optional()});var _ja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var hja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var yja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var vja=Fn.objectWithoutOptionalProperties({default:Fn.boolean().optional(),example:Fn.boolean().optional()});var bja=Fn.union("type",{int:uja,int64:sja,uint:cja,uint64:lja,float:fja,double:dja,string:pja,datetime:_ja,date:hja,base64:yja,boolean:vja}).transform({transform:e=>{switch(e.type){case"int":return Ay.int(e);case"int64":return Ay.int64(e);case"uint":return Ay.uint(e);case"uint64":return Ay.uint64(e);case"float":return Ay.float(e);case"double":return Ay.double(e);case"string":return Ay.string(e);case"datetime":return Ay.datetime(e);case"date":return Ay.date(e);case"base64":return Ay.base64(e);case"boolean":return Ay.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var pNn=Fn.objectWithoutOptionalProperties({schema:bja}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var gja=Fn.objectWithoutOptionalProperties({default:Fzr.optional(),values:Fn.list(Fzr),example:Fn.string().optional()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var mja=Fn.objectWithoutOptionalProperties({example:Fn.unknown()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var KC=Fn.union("type",{primitive:pNn,object:Fn.lazyObject(()=>Dja),array:Fn.lazyObject(()=>Oja),map:Fn.lazyObject(()=>Pja),optional:Fn.lazyObject(()=>wja),enum:gja,reference:E9t,literal:sNn,oneOf:Fn.object({value:Fn.lazy(()=>Sja)}),nullable:Fn.lazyObject(()=>jja),unknown:mja}).transform({transform:e=>{switch(e.type){case"primitive":return Gp.primitive(e);case"object":return Gp.object(e);case"array":return Gp.array(e);case"map":return Gp.map(e);case"optional":return Gp.optional(e);case"enum":return Gp.enum(e);case"reference":return Gp.reference(e);case"literal":return Gp.literal(e);case"oneOf":return Gp.oneOf(e.value);case"nullable":return Gp.nullable(e);case"unknown":return Gp.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC),example:Fn.list(Fn.unknown()).optional()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var Pja=Fn.objectWithoutOptionalProperties({key:pNn,value:Fn.lazy(()=>KC),example:Fn.unknown().optional()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(dae).extend(K1);var wja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC)}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var jja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC)}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var Dja=Fn.objectWithoutOptionalProperties({allOf:Fn.list(E9t),properties:Fn.list(Fn.lazyObject(()=>Eja)),allOfPropertyConflicts:Fn.list(cNn),fullExamples:Fn.list(A9t).optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var Eja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>KC),readonly:Fn.boolean().optional(),audiences:Fn.list(Fn.string()),conflict:Fn.record(sk,lNn),nameOverride:Fn.string().optional(),generatedName:Fn.string()}).extend(hv);var Sja=Fn.union("type",{discriminated:Fn.lazyObject(()=>Aja),undisciminated:Fn.lazyObject(()=>Mja)}).transform({transform:e=>{switch(e.type){case"discriminated":return uk.discriminated(e);case"undisciminated":return uk.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Aja=Fn.objectWithoutOptionalProperties({discriminantProperty:Fn.string(),commonProperties:Fn.list(Fn.lazyObject(()=>xja)),schemas:Fn.record(Fn.string(),Fn.lazy(()=>KC))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var xja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>KC)});var Mja=Fn.objectWithoutOptionalProperties({schemas:Fn.list(Fn.lazy(()=>KC))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);function Tja(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:xc(e.type)}}function _Nn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:xc(e)}}function PC(e){return typeof e=="string"?e:e.type}function dgi(e){if(typeof e!="string")return e.docs}function I4f(e){if(typeof e!="string")return e.default}function B4f(e){if(typeof e!="string")return e.validation}function zG1(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function N4f(e){let t=e?zG1(e):void 0;if(t==null||t.length===0)return _pi;let r=[];for(let[n,i]of t.entries())if(typeof i=="string")r.push(_A(i));else if(typeof i=="object")switch(i.type){case"namespace":{n<t.length-1?r.push(_A(i.name)):r.push(i.name,_pi);break}default:xc(i.type)}else xc(i);return r.join("/")}function hNn(e){return Ms.of(`${N4f(e)}.yml`)}function A1u({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?_pi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,N4f(r))}function z4f({sdkName:e,namespaceOverride:t}){return Ms.of(`${A1u({sdkName:e,namespaceOverride:t})}.yml`)}function R4f({location:e,namespaceOverride:t}){return t!=null?yf(Ms.of(t),e):e}function I3(e){switch(e){case JH.Deprecated:return"deprecated";case JH.Beta:return"pre-release";case JH.GenerallyAvailable:return"generally-available";default:return}}var RG1=-2147483648,FG1=2147483647,LG1=-17976931348623157e292,UG1=17976931348623157e292;function Z1({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i}){switch(e.type){case"primitive":return Cja(e);case"array":return T1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"map":return C1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"reference":return x1u({schema:e,fileContainingReference:t,context:n,namespace:i});case"unknown":return I1u();case"optional":case"nullable":return q1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"enum":return YG1({schema:e,fileContainingReference:t,context:n,declarationFile:r});case"literal":return e.value,B1u(e);case"object":return XG1({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"oneOf":return ZG1({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i});default:xc(e)}}function Cja(e){switch(e.schema.type){case"string":return HG1({description:e.description,schema:e.schema});case"int":return QG1({description:e.description,schema:e.schema});case"float":return JG1({description:e.description,schema:e.schema});case"double":return GG1({description:e.description,schema:e.schema});case"boolean":return VG1({description:e.description,schema:e.schema});case"int64":return WG1({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function VG1({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function WG1({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function HG1({description:e,schema:t}){let r="string",n=$G1(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function QG1({description:e,schema:t}){let r="integer",n=F4f(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function JG1({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function GG1({description:e,schema:t}){let r="double",n=F4f(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function $G1(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,a=KG1(t);if(!(a==null&&r==null&&n==null&&i==null))return{format:a,pattern:r,minLength:n,maxLength:i}}function KG1(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function F4f(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=M1u(r,t),n=M1u(n,t),i=M1u(i,t),!(r==null&&n==null&&a==null&&u==null&&i==null))return{min:r,max:n,exclusiveMin:a,exclusiveMax:u,multipleOf:i}}function M1u(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[RG1,FG1]:[LG1,UG1];return e<r||e>n?void 0:e}function x1u({schema:e,fileContainingReference:t,context:r,namespace:n}){let i=r.getSchema(e.schema,n);if(i==null)return"unknown";let a=kG1(i)??e.schema,u=_Nn(i),f=e$1(i),d=qja({context:r,fileContainingReference:t,declarationFile:hNn(u),type:a}),c=i.type==="nullable"?`optional<${d}>`:d;return e.description==null&&f==null?c:{type:i.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function T1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),u=`list<${PC(a)}>`;return e.description==null&&e.title==null?u:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{},type:u}}function C1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Cja(e.key),u=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),f=e.encoding!=null?Tja(e.encoding):void 0,d=`map<${PC(a)}, ${PC(u)}>`;if(e.description==null&&f==null&&e.title==null)return d;let c={type:d};return e.description!=null&&(c.docs=e.description),e.encoding!=null&&(c.encoding=f),e.availability!=null&&(c.availability=I3(e.availability)),c}function q1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),u=PC(a),f=dgi(a),d=I4f(a),c=B4f(a),o=u.startsWith("optional<")?u:`optional<${u}>`;if(e.availability==null&&e.description==null&&f==null&&d==null&&c==null&&e.title==null)return o;let l={type:o};return(e.description!=null||f!=null)&&(l.docs=e.description??f),d!=null&&(l.default=d),c!=null&&(l.validation=c),e.availability!=null&&(l.availability=I3(e.availability)),l}function I1u(){return"unknown"}function B1u(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:xc(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function YG1({schema:e,fileContainingReference:t,declarationFile:r,context:n}){let i=pgi(e),a=e.nameOverride??e.generatedName;n.builder.addType(r,{name:a,schema:i.schema});let u=qja({type:a,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return u;let f={type:u};return e.description!=null&&(f.docs=e.description),e.default!=null&&(f.default=e.default.value),e.availability!=null&&(f.availability=I3(e.availability)),f}function XG1({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=N1u({schema:e,declarationFile:r,context:n,namespace:i}),u=e.nameOverride??e.generatedName;n.builder.addType(r,{name:u,schema:a.schema});let f=qja({type:u,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function ZG1({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=z1u({schema:e,declarationFile:r,context:n,namespace:i}),u=e.nameOverride??e.generatedName;n.builder.addType(r,{name:u,schema:a.schema});let f=qja({type:u,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{...e.title!=null?{"display-name":e.title}:{},type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function qja({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function kG1(e){return gb._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function e$1(e){return gb._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function Ann(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:xc(e)}}function U4f({schema:e,context:t,declarationFile:r,namespace:n}){switch(e.type){case"primitive":return n$1(e);case"array":return t$1({schema:e,context:t,declarationFile:r,namespace:n});case"map":return r$1({schema:e,context:t,declarationFile:r,namespace:n});case"reference":return i$1({schema:e,context:t,declarationFile:r,namespace:n});case"unknown":return o$1(e.nameOverride,e.generatedName);case"optional":case"nullable":return a$1({schema:e,context:t,declarationFile:r,namespace:n});case"enum":return pgi(e);case"literal":return u$1(e,e.nameOverride,e.generatedName);case"object":return N1u({schema:e,context:t,declarationFile:r,namespace:n});case"oneOf":return z1u({schema:e.value,context:t,declarationFile:r,namespace:n});default:xc(e)}}function N1u({schema:e,context:t,declarationFile:r,namespace:n}){let i={},a=new Set;for(let c of e.properties){if(Object.keys(c.conflict).length>0){if(Object.entries(c.conflict).every(([j,M])=>!M.differentSchema))continue;Object.entries(c.conflict).forEach(([j])=>{R1u({property:c.key,schemaId:j,context:t,namespace:n}).forEach(q=>{a.add(q)})})}let o=Z1({schema:c.schema,context:t,fileContainingReference:r,namespace:n}),l=c.audiences,g=c.nameOverride,O=I3(c.availability);i[c.key]=l$1(o,l,g,O)}let u=new Set;for(let c of e.allOfPropertyConflicts)c.allOfSchemaIds.forEach(o=>a.add(o)),c.conflictingTypeSignatures&&u.add(c.propertyKey);let f=[];for(let c of e.allOf){let o=V4f({schema:c.schema,context:t,namespace:n});if(o==null||a.has(c.schema)||a.has(o))continue;let l=Z1({schema:gb.reference(c),context:t,fileContainingReference:r,namespace:n});f.push(PC(l))}for(let c of a){let o=F1u(t,c,n);for(let l of o.properties)i[l.key]==null&&(u.has(l.key)&&(i[l.key]="unknown"),i[l.key]=Z1({schema:l.schema,context:t,fileContainingReference:r,namespace:n}));for(let l of o.allOf){if(a.has(l.schema))continue;let g=Z1({schema:gb.reference(l),context:t,fileContainingReference:r,namespace:n});f.push(PC(g))}}let d={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(i).map(([c,o])=>c$1(c)?[c,typeof o=="string"?{type:o,name:`_${c}`}:{...o,name:`_${c}`}]:[c,o]))};return f.length>0&&(d.extends=f),e.additionalProperties&&(d["extra-properties"]=!0),e.availability!=null&&(d.availability=I3(e.availability)),e.source!=null&&(d.source=Ann(e.source)),{name:e.nameOverride??e.generatedName,schema:d}}function R1u({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return R1u({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:a,allOf:u}=F1u(r,t,n),f=a.some(c=>c.key===e),d=[...u.flatMap(c=>R1u({property:e,context:r,schemaId:c.schema,namespace:n}))];if(f||d.length>0)return[t,...d]}return[]}function F1u(e,t,r){let n=e.getSchema(t,r);if(n==null)return{properties:[],allOf:[]};if(n.type==="object")return{properties:n.properties,allOf:n.allOf};if(n.type==="reference")return F1u(e,n.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${n.type}`)}function t$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:T1u({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n})}}function r$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:C1u({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n})}}function n$1(e){let t=Cja(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function L4f(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function pgi(e){let t={enum:e.values.map(i=>{let a=i.nameOverride??i.generatedName,u=i.value;if(a===u&&i.description==null&&(i.casing==null||L4f(i.casing)))return a;let f={value:i.value};if(a!==u&&(f.name=a),i.description!=null&&(f.docs=i.description),i.casing!=null&&!L4f(i.casing)){let d={},c=!1;i.casing.camel!=null&&(d.camel=i.casing.camel,c=!0),i.casing.screamingSnake!=null&&(d["screaming-snake"]=i.casing.screamingSnake,c=!0),i.casing.snake!=null&&(d.snake=i.casing.snake,c=!0),i.casing.pascal!=null&&(d.pascal=i.casing.pascal,c=!0),c&&(f.casing=d)}return f})};e.description!=null&&(t.docs=e.description),e.default!=null&&(t.default=e.default.value);let r=new Set,n={...t,enum:[],source:e.source!=null?Ann(e.source):void 0};for(let i of t.enum){let a=typeof i=="string"?i:i.name??i.value;r.has(a.toLowerCase())||(n.enum.push(i),r.add(a.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function i$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:x1u({schema:e,context:t,fileContainingReference:r,namespace:n})}}function a$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:q1u({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n})}}function o$1(e,t){return{name:e??t,schema:I1u()}}function u$1(e,t,r){return{name:t??r,schema:B1u(e)}}function z1u({schema:e,context:t,declarationFile:r,namespace:n}){let i=e.encoding!=null?Tja(e.encoding):void 0;if(e.type==="discriminated"){let u={};for(let d of e.commonProperties)u[d.key]=Z1({schema:d.schema,fileContainingReference:r,context:t,namespace:n});let f={};for(let[d,c]of Object.entries(e.schemas))f[d]=Z1({schema:c,context:t,fileContainingReference:r,namespace:n});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":u,docs:e.description??void 0,availability:e.availability!=null?I3(e.availability):void 0,union:f,encoding:i,source:e.source!=null?Ann(e.source):void 0}}}let a=[];for(let u of e.schemas)a.push(Z1({schema:u,fileContainingReference:r,context:t,namespace:n}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:a,encoding:i,source:e.source!=null?Ann(e.source):void 0}}}var s$1=/^[0-9]/;function c$1(e){return s$1.test(e)}function V4f({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?V4f({context:t,schema:n.schema,namespace:r}):e}function l$1(e,t,r,n){return t.length===0&&r==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{}}}function W4f(e){let t=e.replace(/^x-|^X-/,"");return _A(t)}var H4f="BasicAuthScheme",Ija="BearerAuthScheme";function Q4f(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),e.builder.addAuthScheme({name:H4f,schema:i}),t||(e.builder.setAuth(H4f),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),e.builder.addAuthScheme({name:Ija,schema:i}),t||(e.builder.setAuth(Ija),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??W4f(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:Ija,schema:i}),t||(e.builder.setAuth(Ija),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(Ms.of("__package__.yml"),{name:"OauthScope",schema:pgi(n.scopesEnum).schema})}}function M9t({header:e,context:t,fileContainingReference:r,namespace:n}){let i=Z1({schema:e.schema,context:t,fileContainingReference:r,namespace:n}),a=PC(i),u=e.name.replace(/^x-|^X-/,""),f=e.parameterNameOverride!=null?e.parameterNameOverride:_A(u);if(e.description==null&&e.name===f&&e.env==null&&e.availability==null)return a;let d={type:a};return f!==e.name&&(d.name=f),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=I3(e.availability)),d}function Bja({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Z1({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(e.variableReference==null&&e.description==null&&e.availability==null)return PC(i);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:PC(i)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=I3(e.availability)),a}var xxu=require("fs/promises");var J4f={naming:"v1"};function hh(e,t){let r=Array.isArray(t)?t:[t];for(let n of r){let i=e[n];if(i!=null)return i}}function _gi(e,t,r,n,i=[]){try{let a=hh(e,t);if(a!=null)return r.parse(a)}catch{let u=W8t(i).join(" -> ");n.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}var Nja={of(e){return e}};var kh={SDK_METHOD_NAME:Nja.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:Nja.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:Nja.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};function wy(e){return e.$ref!=null}function O2e(e){switch(hh(e,kh.AVAILABILITY)){case"deprecated":return JH.Deprecated;case"beta":return JH.Beta;case"generally-available":return JH.GenerallyAvailable;default:break}if(!wy(e)&&e.deprecated)return JH.Deprecated}var ADe={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};function G4f({schema:e,logger:t}){return hh(e,kh.ENCODING)??void 0}function $4f(e){return hh(e,kh.FERN_ENUM)}function K4f({nameOverride:e,generatedName:t,title:r,schema:n,description:i,availability:a}){let u=hh(n,kh.SDK_GROUP_NAME),f=hh(n,kh.TYPE_DEFINITION);if(f!=null)return hgi({fernType:f,nameOverride:e,generatedName:t,title:r,description:i,availability:a,groupName:typeof u=="string"?[u]:u})}function hgi({fernType:e,nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u}){return O$({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>{switch(f.v1){case"BASE_64":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.base64({example:void 0})});case"BOOLEAN":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.boolean({default:void 0,example:void 0})});case"DATE":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.date({example:void 0})});case"DATE_TIME":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.datetime({example:void 0})});case"FLOAT":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.float({example:void 0})});case"DOUBLE":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.uint({default:void 0,example:void 0})});case"INTEGER":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.uint64({default:void 0,example:void 0})});case"LONG":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:xc(f.v1)}},unknown:()=>Gp.unknown({nameOverride:t,generatedName:r,title:n,example:void 0,description:i,availability:a,groupName:u}),map:({keyType:f,valueType:d})=>f?.type==="primitive"&&d!=null?Gp.map({nameOverride:t,generatedName:r,title:n,key:f,value:d,description:i,availability:a,groupName:u,encoding:void 0,example:void 0}):void 0,list:f=>f!=null?Gp.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u,example:void 0}):void 0,optional:f=>f!=null?Gp.optional({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u}):void 0,set:f=>f!=null?Gp.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u,example:void 0}):void 0,literal:f=>Gp.literal({nameOverride:t,generatedName:r,title:n,value:f._visit({string:d=>DB.string(d),boolean:d=>DB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:i,availability:a,groupName:u}),named:()=>{}}})}function Mnn(e){if(e!=null&&typeof e=="boolean")return e}function Y4f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,additionalProperties:i,description:a,availability:u,wrapAsNullable:f,context:d,groupName:c,example:o,encoding:l,source:g,namespace:O}){return typeof i=="boolean"||yNn(i)?zja({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:Gp.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:c,example:o,encoding:l}):zja({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:a1(i,d.options.optionalAdditionalProperties?f:!1,d,[...n,"Value"],g,O),groupName:c,example:o,encoding:l})}function zja({nameOverride:e,generatedName:t,title:r,keySchema:n,valueSchema:i,wrapAsNullable:a,description:u,availability:f,groupName:d,example:c,encoding:o}){return a?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.map({nameOverride:e,generatedName:t,title:r,description:u,availability:n.availability,key:n,value:i,groupName:d,encoding:o,example:c}),description:u,availability:f,groupName:d}):Gp.map({nameOverride:e,generatedName:t,title:r,description:u,availability:f,key:n,value:i,groupName:d,encoding:o,example:c})}function yNn(e){return e==null?!1:typeof e=="boolean"?e:!wy(e)&&Object.keys(e).length===0}function X4f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,item:i,description:a,availability:u,wrapAsNullable:f,context:d,groupName:c,example:o,source:l,namespace:g}){let O=i==null?Gp.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:c}):a1(i,!1,d,[...n,"Item"],l,g);return f$1({nameOverride:e,generatedName:t,title:r,groupName:c,itemSchema:O,wrapAsNullable:f,description:a,availability:u,example:o})}function f$1({nameOverride:e,generatedName:t,title:r,itemSchema:n,wrapAsNullable:i,description:a,availability:u,groupName:f,example:d}){return i?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.array({nameOverride:e,generatedName:t,title:r,value:n,description:a,availability:u,groupName:f,example:d}),description:a,availability:u,groupName:f}):Gp.array({nameOverride:e,generatedName:t,title:r,value:n,description:a,availability:u,groupName:f,example:d})}function L1u({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:u,required:f,wrapAsNullable:d,discriminator:c,context:o,groupName:l,encoding:g,source:O,namespace:P}){let j=c.propertyName,M=Object.fromEntries(Object.entries(c.mapping??{}).map(([B,I])=>{let C=vNn({$ref:I},!1,o,[I],g,O,P);return o.markReferencedByDiscriminatedUnion({$ref:I},j,1),[B,C]})),q=Object.entries(i).filter(([B])=>B!==j).map(([B,I])=>{let C=f!=null&&f.includes(B),F=a1(I,!C,o,[...n,B],O,P);return{key:B,schema:F}});return Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:q,description:a,availability:u,discriminant:j,subtypes:M,groupName:l,source:O})}function U1u({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:u,required:f,wrapAsNullable:d,discriminant:c,variants:o,context:l,groupName:g,encoding:O,source:P,namespace:j}){let M=Object.fromEntries(Object.entries(o).map(([B,I])=>{if(wy(I)){let C=vNn(I,!1,l,[I.$ref],O,P,j);return l.markReferencedByDiscriminatedUnion(I,c,1),[B,C]}else{let C=$zr(I,!1,l,[...n,B],O,P,j,new Set([c]));return[B,C]}})),q=Object.entries(i).filter(([B])=>B!==c).map(([B,I])=>{let C=f!=null&&f.includes(B),F=a1(I,!C,l,[...n,B],P,j);return{key:B,schema:F}});return Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:q,description:a,availability:u,discriminant:c,subtypes:M,groupName:g,source:P})}function Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,properties:i,description:a,availability:u,discriminant:f,subtypes:d,groupName:c,source:o}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.oneOf(uk.discriminated({description:a,availability:u,discriminantProperty:f,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:i,groupName:c,encoding:void 0,source:o})),groupName:c,description:a,availability:u}):Gp.oneOf(uk.discriminated({description:a,availability:u,discriminantProperty:f,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:i,groupName:c,encoding:void 0,source:o}))}function k4f(e){if(e.proto!=null)return V7n.protobuf({typeName:e.proto.type})}var d$1=/^(\d+)/;function Rja(e){let t=e.match(d$1);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let a=bNn(i);return n.length>0?`${a}_${n}`:a}}}function bNn(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],n=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),f=e%10;return f===0?n[u]:`${n[u]}_${t[f]}`}if(e<1e3){let u=Math.floor(e/100),f=e%100;return f===0?`${t[u]}_hundred`:`${t[u]}_hundred_${bNn(f)}`}let i=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[i]}_thousand`:`${t[i]}_thousand_${bNn(a)}`}var gNn=/^[a-zA-Z][a-zA-Z0-9_]*$/;function Kzr({nameOverride:e,generatedName:t,title:r,fernEnum:n,enumVarNames:i,enumValues:a,_default:u,description:f,availability:d,wrapAsNullable:c,groupName:o,context:l,source:g}){let O=h$1(i??[]),P=new Set(a),j=Array.from(P).map((q,B)=>{let I=n?.[q],C=O[B],F=gNn.test(q),K=I?.name??C,ee=F?q:ygi(q);return K!=null&&!gNn.test(K)&&(l?.logger.warn(`Enum name override ${K} is not a valid name. Falling back on ${ee}.`),K=void 0),{nameOverride:K,generatedName:ee,value:q,description:I?.description,availability:d,casing:{snake:I?.casing?.snake??void 0,pascal:I?.casing?.pascal??void 0,screamingSnake:I?.casing?.screamingSnake??void 0,camel:I?.casing?.camel??void 0}}}),M=u!=null?j.find(q=>q.value===u):void 0;return p$1({wrapAsNullable:c,nameOverride:e,generatedName:t,title:r,values:j,_default:M,description:f,availability:d,groupName:o,source:g})}function p$1({wrapAsNullable:e,nameOverride:t,generatedName:r,title:n,values:i,_default:a,description:u,availability:f,groupName:d,source:c}){return e?Gp.nullable({nameOverride:t,generatedName:r,title:n,value:Gp.enum({nameOverride:t,generatedName:r,title:n,values:i,description:u,default:a,availability:f,example:void 0,groupName:d,source:c}),description:u,availability:f,groupName:d}):Gp.enum({nameOverride:t,generatedName:r,title:n,values:i,description:u,availability:f,default:a,example:void 0,groupName:d,source:c})}var _$1={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function ygi(e){let t=Rja(e),r=_$1[e];return t!=null?rH(_A(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":rH(_A(e)))}function h$1(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(n=>n[r]===t[r]);)r++;return e.map(n=>n.substring(r))}function e3f({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,description:o,availability:l,wrapAsNullable:g,example:O,groupName:P}){return n==="int64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P})}function t3f(e){return typeof e=="string"?DB.string(e):typeof e=="boolean"?DB.boolean(e):DB.string(`${e}`)}function r3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,value:i,description:a,availability:u,groupName:f}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.literal({nameOverride:e,generatedName:t,title:r,value:t3f(i),description:a,availability:u,groupName:f}),description:a,availability:u,groupName:f}):Gp.literal({nameOverride:e,generatedName:t,title:r,value:t3f(i),description:a,availability:u,groupName:f})}function V1u({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,description:o,availability:l,wrapAsNullable:g,example:O,groupName:P}){return n==null||n==="double"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.double({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="float"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="int32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="int64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="time-delta"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P})}var y$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},v$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},b$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},g$1={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},m$1={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},O$1={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},P$1={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},w$1={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function Fja(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],n=[y$1,v$1,b$1,g$1,m$1,O$1,P$1,w$1],i;do{i=t;for(let a of n)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:f}=a.applyStrategy(t);t=u,r=[...r,...f]}}while(t.join("")!==i.join(""));return r}function WF(e){let t=e.join("_"),r=rH(_A(t));return/^\d/.test(r)?Rja(r)??r:r}function W1u(e){let t=e.join("_");return _A(t)}function YC(e){switch(e.type){case"object":return gb.object({allOf:e.allOf,properties:e.properties.map(t=>D$1(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source});case"array":return gb.array({description:e.description,availability:e.availability,value:YC(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"enum":return gb.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source});case"literal":return gb.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return gb.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:YC(e.value),groupName:e.groupName});case"optional":return gb.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:YC(e.value),groupName:e.groupName});case"primitive":return gb.primitive({description:e.description,availability:e.availability,schema:n3f(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return gb.map({description:e.description,availability:e.availability,key:gb.primitive({description:e.key.description,availability:e.key.availability,schema:n3f(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:YC(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding});case"reference":return gb.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return gb.oneOf(j$1(e.value));case"unknown":return gb.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:xc(e)}}function j$1(e){switch(e.type){case"discriminated":return FAr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:YC(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,YC(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source});case"undisciminated":return FAr.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>YC(t)),groupName:e.groupName,encoding:e.encoding,source:e.source});default:xc(e)}}function n3f(e){switch(e.type){case"string":return jD.string(e);case"base64":return jD.base64();case"boolean":return jD.boolean(e);case"date":return jD.date();case"datetime":return jD.datetime();case"double":return jD.double(e);case"float":return jD.float();case"int":return jD.int(e);case"int64":return jD.int64(e);case"uint":return jD.uint();case"uint64":return jD.uint64();default:xc(e)}}function D$1(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:YC(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function Lja(e,t){return MDe(YC(e),YC(t))}function MDe(e,t){return e.type==="primitive"&&t.type==="primitive"?i3f(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?S$1(e.values,t.values):e.type==="array"&&t.type==="array"?MDe(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?MDe(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?E$1(e.value,t.value):e.type==="object"&&t.type==="object"?A$1(e,t):e.type==="map"&&t.type==="map"?i3f(e.key.schema,t.key.schema)&&MDe(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function i3f(e,t){return e.type===t.type}function S$1(e,t){let r=new Set(...e.map(i=>i.value)),n=new Set(...t.map(i=>i.value));return Yqt(r,n)}function E$1(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,n])=>{let i=t.schemas[r];return i==null?!1:MDe(n,i)}):e.type==="undisciminated"&&t.type==="undisciminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,n)=>{let i=t.schemas[n];return i==null?!1:MDe(r,i)}):!1}function A$1(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(n=>[n.key,n.schema]));return Object.entries(t.properties).every(([n,i])=>{let a=r[n];return a==null?!1:MDe(a,i.schema)})}function a3f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,required:u,wrapAsNullable:f,allOf:d,context:c,propertiesToExclude:o,groupName:l,fullExamples:g,additionalProperties:O,availability:P,encoding:j,source:M,namespace:q}){let B=[...u??[]],I={...i},C=[],F=[];for(let G of d)if(wy(G)){let te=c.resolveSchemaReference(G);if(te.discriminator!=null&&te.discriminator.mapping!=null)continue;if(te.oneOf!=null){for(let Re of te.oneOf){let wt=wy(Re)?c.resolveSchemaReference(Re):Re,Ct=a1(wt,!1,c.DUMMY,n,M,q);Ct.type==="object"&&C.push(...Ct.properties.map(Wt=>Wt.schema.type!=="optional"&&Wt.schema.type!=="nullable"?{...Wt,schema:Gp.optional({nameOverride:void 0,generatedName:"",title:void 0,value:Wt.schema,description:void 0,availability:Wt.availability,groupName:void 0})}:Wt))}continue}let Ye=Yzr(G);if(Ye==null)continue;F.push({schemaId:Ye,convertedSchema:H1u(G,[Ye],M),properties:o3f({schema:G,context:c,breadcrumbs:n,source:M,namespace:q})}),c.markSchemaAsReferencedByNonRequest(Ye)}else{let te=a1(G,!1,c,n,M,q);te.type==="object"&&C.push(...te.properties)}let K={};for(let G of F)for(let[te,Ye]of Object.entries(G.properties)){let Re=K[te];Re!=null?(Re.schemaIds.push(G.schemaId),Re.schemas.some(Ct=>Lja(Ct,Ye))||Re.schemas.push(Ye)):K[te]={schemaIds:[G.schemaId],schemas:[Ye]}}let ee=[];for(let[G,te]of Object.entries(K))te.schemaIds.length>1&&ee.push({propertyKey:G,allOfSchemaIds:te.schemaIds,conflictingTypeSignatures:te.schemas.length>1});let J=Object.entries(I).map(([G,te])=>{let Ye=B.includes(G),Re=hh(te,kh.AUDIENCES)??[],wt=O2e(te),Ct=wy(te)?!1:te.readOnly,Wt=hh(te,kh.FERN_PROPERTY_NAME),Bt=[...n,G],or=W1u(Bt),jr=Ye?a1(te,!1,c,Bt,M,q):Gp.optional({nameOverride:e,generatedName:or,title:r,description:void 0,availability:wt,value:a1(te,!1,c,Bt,M,q),groupName:l}),Vr={};for(let It of F){let cr=It.properties[G];cr!=null&&!Lja(jr,cr)?Vr[It.schemaId]={differentSchema:!0}:cr!=null&&(Vr[It.schemaId]={differentSchema:!1})}return{key:G,schema:jr,nameOverride:Wt,audiences:Re,conflict:Vr,generatedName:W1u([...n,G]),availability:wt,readonly:Ct}});return J.push(...C.map(G=>{let te=G.conflict;for(let Ye of F){let Re=Ye.properties[G.key];Re!=null&&!Lja(G.schema,Re)?te[Ye.schemaId]={differentSchema:!0}:Re!=null&&(te[Ye.schemaId]={differentSchema:!1})}return{...G,conflict:te}})),M$1({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,properties:J.filter(G=>!o.has(G.key)),description:a,allOf:F.map(G=>G.convertedSchema),allOfPropertyConflicts:ee,groupName:l,fullExamples:g,additionalProperties:O,availability:P,source:M})}function M$1({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,properties:i,description:a,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:o,availability:l,source:g}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.object({description:a,properties:i,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:yNn(o),availability:void 0,source:g}),description:a,availability:l,groupName:d}):Gp.object({description:a,properties:i,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:yNn(o),availability:l,source:g})}function o3f({schema:e,context:t,breadcrumbs:r,source:n,namespace:i}){let a={},[u,f]=wy(e)?[t.resolveSchemaReference(e),Fja(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...o3f({schema:d,context:t,breadcrumbs:f,source:n,namespace:i})};for(let[d,c]of Object.entries(u.properties??{})){let o=a1(c,!1,t,[...f,d],n,i);a[d]=o}return a}function mNn({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,description:i,availability:a,wrapAsNullable:u,context:f,subtypes:d,groupName:c,encoding:o,source:l,subtypePrefixOverrides:g,namespace:O}){let P=x$1({schemas:d}),j=d.flatMap((B,I)=>{if(!wy(B)&&B.enum!=null&&f.options.cooerceEnumsToLiterals)return B.enum.map(F=>Gp.literal({nameOverride:void 0,generatedName:WF([t,F]),title:void 0,value:DB.string(F),groupName:void 0,description:void 0,availability:F.availability}));let C=P[I];if(g!=null){let F=g[I];F!=null&&"name"in F&&(C=F.name)}return[a1(B,!1,f,[...n,C??`${I}`],l,O)]}),M=[];for(let B=0;B<j.length;++B){let I=j[B],C=!1;for(let F=B+1;F<j.length;++F){let K=j[F];if(I!=null&&K!=null&&MDe(I,K)){C=!0;break}}I!=null&&!C&&M.push(I)}if(Object.entries(M).every(([B,I])=>I.type==="literal")){let B={},I=[];return Object.entries(M).forEach(([C,F])=>{F.type==="literal"&&F.value.type==="string"&&(I.push(F.value.value),F.description!=null&&(B[F.value.value]={description:F.description}))}),Kzr({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:i,availability:a,fernEnum:B,enumVarNames:void 0,enumValues:I,_default:void 0,groupName:c,context:f,source:l})}return M.length===1&&M[0]!=null?M[0]:u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:i,availability:a,subtypes:M,groupName:c,encoding:o,source:l})}function Q1u({nameOverride:e,generatedName:t,title:r,description:n,availability:i,wrapAsNullable:a,context:u,groupName:f,discriminator:d,encoding:c,source:o,namespace:l}){let g=Object.entries(d.mapping??{}).map(([j,M],q)=>{let B={$ref:M},I=vNn(B,!1,u,[M],c,o,l);return u.markSchemaWithDiscriminantValue(B,d.propertyName,j),I.type==="object"&&(I.properties={[d.propertyName]:Gp.literal({nameOverride:void 0,generatedName:WF([t,j]),title:void 0,value:DB.string(j),groupName:void 0,description:void 0,availability:void 0}),...I.properties.filter(C=>C.key!==d.propertyName)}),I}),O=[];for(let j=0;j<g.length;++j){let M=g[j],q=!1;for(let B=j+1;B<g.length;++B){let I=g[B];if(M!=null&&I!=null&&MDe(M,I)){q=!0;break}}M!=null&&!q&&O.push(M)}if(Object.entries(O).every(([j,M])=>M.type==="literal")){let j={},M=[];return Object.entries(O).forEach(([q,B])=>{B.type==="literal"&&B.value.type==="string"&&(M.push(B.value.value),B.description!=null&&(j[B.value.value]={description:B.description}))}),Kzr({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:n,availability:i,fernEnum:j,enumVarNames:void 0,enumValues:M,_default:void 0,groupName:f,context:u,source:o})}return O.length===1&&O[0]!=null?O[0]:u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:n,availability:i,subtypes:O,groupName:f,encoding:c,source:o})}function x$1({schemas:e}){let t={},r=0;for(let a of e){if(!wy(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),f={},d=u;for(let[c,o]of Object.entries(t)){let l=yXi(o,u);d=yXi(d,o),f[c]=l}f[r]=d,t=f}}r++}let n=[],i=0;for(let a of e){let u=t[i];if(u!=null&&u.length>0){let f=u.sort();if(f[0]!=null){n.push(f[0]),++i;continue}}wy(a)?n.push(bNn(i)??`${i}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?n.push(""):n.push(bNn(i)??`${i}`),++i}return n}function u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,description:i,availability:a,subtypes:u,groupName:f,encoding:d,source:c}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.oneOf(uk.undisciminated({description:i,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:f,encoding:d,source:c})),description:i,availability:a,groupName:f}):Gp.oneOf(uk.undisciminated({description:i,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:f,encoding:d,source:c}))}function ONn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function Uja({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;if(r&&typeof r=="number")return r;r&&t.warn(`Expected fallback to be a number, but got ${typeof r}`)}function s3f({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;if(r&&typeof r=="boolean")return r;r&&t.warn(`Expected fallback to be a boolean, but got ${typeof r}`)}function x9t({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;if(r&&typeof r=="string")return r;r&&t.warn(`Expected fallback to be a string, but got ${typeof r}`)}function c3f({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;if(r&&Array.isArray(r))return r;r&&t.warn(`Expected fallback to be a array, but got ${typeof r}`)}var xnn="#/components/schemas/";function a1(e,t,r,n,i,a,u=!1,f=new Set,d){let c=z$1({schema:e,logger:r.logger});if(wy(e)){let o=Yzr(e);return o!=null?(u?r.markSchemaAsReferencedByRequest(o):r.markSchemaAsReferencedByNonRequest(o),vNn(e,t,r,n,c,i,a)):$zr(r.resolveSchemaReference(e),t,r,Fja(e.$ref),c,i,a,f,u,d)}return $zr(e,t,r,n,c,i,a,f,u,d)}function vNn(e,t,r,n,i,a,u){let f=e.$ref.includes("properties")?$zr(r.resolveSchemaReference(e),t,r,n,i,a,u,new Set):Gp.reference(H1u(e,n,a));return t?Gp.nullable({title:void 0,nameOverride:void 0,generatedName:WF(n),value:f,description:void 0,availability:void 0,groupName:void 0}):f}function T$1(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function $zr(e,t,r,n,i,a,u,f=new Set,d=!1,c){let o=hh(e,kh.TYPE_NAME)??(r.options.useTitlesAsName?T$1(e.title):void 0),l=hh(e,kh.SDK_GROUP_NAME)??hh(e,ADe.TAGS)?.[0],g=(typeof l=="string"?[l]:l)??[];g=r.resolveGroupName(g);let O=WF(n),P=e.title,j=e.description,M=O2e(e),q=hh(e,ADe.EXAMPLES),B=[];e.example!=null&&B.push({name:void 0,value:e.example,description:void 0}),q!=null&&Object.keys(q).length>0&&B.push(...Object.entries(q).map(([C,F])=>({name:F.summary??C,value:F.value,description:F.description})));let I=K4f({schema:e,description:j,title:P,nameOverride:o,generatedName:O,availability:M});if(I!=null)return I;if(!t&&e.nullable===!0)return $zr(e,!0,r,n,i,a,u,f,d,c);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!vgi(e.enum))return wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.string({default:ONn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g,wrapAsNullable:t,description:j,availability:M});let C=$4f(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?r3f({nameOverride:o,generatedName:O,title:P,wrapAsNullable:t,value:e.enum[0],description:j,availability:M,groupName:g}):Kzr({nameOverride:o,generatedName:O,title:P,fernEnum:C,enumVarNames:hh(e,[ADe.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:j,availability:M,wrapAsNullable:t,groupName:g,context:r,source:a})}if(vgi(e.type)&&e.type[1]!=null&&e.type[0]!=null){let C=e.type[0],F=e.type[1];if(C==="null")return Gp.nullable({nameOverride:o,generatedName:O,title:P,value:$zr({...e,type:F},t,r,n,i,a,u,f,d,c),groupName:g,description:e.description,availability:M});if(F==="null")return Gp.nullable({nameOverride:o,generatedName:O,title:P,value:$zr({...e,type:C},t,r,n,i,a,u,f,d,c),groupName:g,description:e.description,availability:M})}if(vgi(e.type)&&e.type.length>1){let C=e.type.includes("null"),F=e.type.filter(K=>K!=="null").map(K=>({type:K,nullable:C}));return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t,context:r,subtypes:F,groupName:g,encoding:i,source:a,namespace:u})}if(e==="boolean"||e.type==="boolean"){let C=hh(e,kh.BOOLEAN_LITERAL);return C!=null?f3f({nameOverride:o,generatedName:O,title:P,literal:DB.boolean(C),wrapAsNullable:t,description:j,availability:M,groupName:g}):wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.boolean({default:e.default,example:s3f({schema:e,logger:r.logger,fallback:c})}),wrapAsNullable:t,description:j,availability:M,groupName:g})}if(e==="number"||e.type==="number")return V1u({nameOverride:o,generatedName:O,title:P,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="integer"||e.type==="integer")return e3f({nameOverride:o,generatedName:O,title:P,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="float")return V1u({nameOverride:o,generatedName:O,title:P,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="string"||e.type==="string"){if(e.format==="date-time")return wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.datetime({example:x9t({schema:e,logger:r.logger,fallback:c})}),wrapAsNullable:t,description:j,availability:M,groupName:g});if(e.format==="json-string")return Gp.unknown({nameOverride:o,generatedName:O,title:P,description:j,availability:M,groupName:g,example:void 0});let C=_3f(e,"const");return C!=null?f3f({nameOverride:o,generatedName:O,title:P,literal:DB.string(C),wrapAsNullable:t,description:j,availability:M,groupName:g}):wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.string({default:ONn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g,wrapAsNullable:t,description:j,availability:M})}if(e.type==="array")return X4f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,item:e.items,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,example:c3f({schema:e,logger:r.logger,fallback:c}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&l3f(e))return Y4f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,additionalProperties:e.additionalProperties,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,encoding:i,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?Q1u({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,discriminator:e.discriminator,encoding:i,source:a,namespace:u}):L1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:g,encoding:i,source:a,namespace:u});if(Array.isArray(e.type)&&(e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type)),e.oneOf!=null&&e.oneOf.length>0){let C=hh(e,kh.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?Q1u({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,discriminator:e.discriminator,encoding:i,source:a,namespace:u}):L1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:g,encoding:i,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let F=a1(e.oneOf[0],t,r,n,a,u,d);return PNn(F,j,g)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let J=e.oneOf[0],G=e.oneOf[1];if(!wy(J)&&J.type==="null")return a1(G,!0,r,n,a,u);if(!wy(G)&&G.type==="null")return a1(J,!0,r,n,a,u)}let F=I$1({schemas:e.oneOf});if(F!=null)return Kzr({nameOverride:o,generatedName:O,title:P,fernEnum:void 0,enumVarNames:void 0,enumValues:F,_default:e.default,description:j,availability:M,wrapAsNullable:t,groupName:g,context:r,source:a});let K=d3f({schemas:e.oneOf,context:r});if(K!=null&&!r.options.discriminatedUnionV2&&!C)return U1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},required:e.required,description:j,availability:M,wrapAsNullable:t,discriminant:K.discriminant,variants:K.schemas,context:r,groupName:g,encoding:i,source:a,namespace:u});let ee=e.oneOf.filter(J=>!wy(J)&&J.type==="null").length>0;return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t||ee,context:r,subtypes:e.oneOf.filter(J=>wy(J)||J.type!=="null"),encoding:i,groupName:g,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let K=a1(e.anyOf[0],t,r,n,a,u,d);return PNn(K,j,g)}if(e.anyOf.length===2){let[K,ee]=e.anyOf;if(K!=null&&ee!=null){if(!wy(K)&&K.type==="null"){let J=a1(ee,!0,r,n,a,u);return PNn(J,j,g)}else if(!wy(ee)&&ee.type==="null"){let J=a1(K,!0,r,n,a,u);return PNn(J,j,g)}}}let C=d3f({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return U1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},required:e.required,description:j,availability:M,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:g,encoding:i,source:a,namespace:u});let F=e.anyOf.filter(K=>!wy(K)&&K.type==="null").length>0;return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t||F,context:r,subtypes:e.anyOf.filter(K=>wy(K)||K.type!=="null"),encoding:i,groupName:g,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let K of e.allOf??[])(wy(K)||Object.keys(K).length>0)&&C.push(K);if((e.properties==null||e.properties.length===0)&&C.length===1&&C[0]!=null){let K=a1(C[0],t,r,n,a,u,d);return PNn(K,j,g)}let F=C.filter(K=>{let ee=Vja(K);return ee||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(K)}`),ee});if((e.properties==null||e.properties.length===0)&&F.length===1&&F[0]!=null){let K=a1(F[0],t,r,n,a,u,d);return PNn(K,j,g)}return a3f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},description:j,required:e.required,wrapAsNullable:t,allOf:F,context:r,propertiesToExclude:f,groupName:g,fullExamples:B,additionalProperties:e.additionalProperties,availability:M,encoding:i,source:a,namespace:u})}if(e.type==="object"&&C$1(e)&&q$1(e)&&l3f(e))return zja({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${O}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:ONn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g},valueSchema:Gp.unknown({nameOverride:void 0,generatedName:`${O}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:g}),groupName:g,encoding:i,example:e.example});if(e.type==null){let C=e.example??e.default;return Gp.unknown({nameOverride:o,generatedName:O,title:P,description:j,availability:M,groupName:g,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(n)} value=${JSON.stringify(e)}`)}function Yzr(e){if(e.$ref.startsWith(xnn))return e.$ref.replace(xnn,"")}function H1u(e,t,r){let n=hh(e,kh.TYPE_NAME),i=WF(t),a=e.description,u=O2e(e),f=Yzr(e);if(f==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return gb.reference({generatedName:i,nameOverride:n,title:void 0,schema:f,description:a??void 0,availability:u,groupName:void 0,source:r})}function C$1(e){return e.oneOf==null||e.oneOf.length===0}function q$1(e){return e.allOf==null||e.allOf.length===0}function l3f(e){return e.properties==null||Object.keys(e.properties).length===0}function vgi(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function PNn(e,t,r){return e.type==="reference"?Gp.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?Gp.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r}):e.type==="nullable"?Gp.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r}):e}function Vja(e){return wy(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Vja(t)):e.oneOf!=null?e.oneOf.every(t=>Vja(t)):e.anyOf!=null?e.anyOf.every(t=>Vja(t)):!1}function f3f({literal:e,wrapAsNullable:t,groupName:r,description:n,availability:i,nameOverride:a,generatedName:u,title:f}){return t?Gp.nullable({nameOverride:a,generatedName:u,title:f,value:Gp.literal({nameOverride:a,generatedName:u,title:f,value:e,description:n,availability:i,groupName:r}),groupName:r,description:n,availability:i}):Gp.literal({nameOverride:a,generatedName:u,title:f,value:e,groupName:r,description:n,availability:i})}function wU({primitive:e,wrapAsNullable:t,groupName:r,description:n,availability:i,generatedName:a,nameOverride:u,title:f}){return r=typeof r=="string"?[r]:r,t?Gp.nullable({nameOverride:u,generatedName:a,title:f,value:Gp.primitive({nameOverride:u,generatedName:a,title:f,schema:e,description:n,availability:i,groupName:r}),groupName:r,description:n,availability:i}):Gp.primitive({nameOverride:u,generatedName:a,title:f,schema:e,description:n,availability:i,groupName:r})}function I$1({schemas:e}){let t=new Set;for(let r of e){if(wy(r))return;if(r.enum!=null&&vgi(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function d3f({schemas:e,context:t}){let r={};for(let n of e){let i=p3f({schema:n,context:t});for(let[a,u]of Object.entries(i)){let f=r[a];f!=null?f[u]=n:r[a]={[u]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length)return{discriminant:n,schemas:i}}function p3f({schema:e,context:t}){let r=wy(e)?t.resolveSchemaReference(e):e;return B$1({schema:r,context:t})}function B$1({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=p3f({schema:n,context:t});for(let[a,u]of Object.entries(i??{}))r[a]=u}return r}for(let[n,i]of Object.entries(e.properties??{})){let a=wy(i)?t.resolveSchemaReference(i):i;a.type==="string"&&a.enum!=null&&vgi(a.enum)&&N$1(a.enum).length===1&&a.enum[0]!=null&&(r[n]=a.enum[0]);let u=_3f(a,"const");a.type==="string"&&u!=null&&(r[n]=u),n==="type"&&a.example!=null&&(r[n]=a.example)}return r}function N$1(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function _3f(e,t){let r=e[t];if(r!=null)return r}function z$1({schema:e,logger:t}){let r=G4f({schema:e,logger:t});if(r!=null)return k4f(r)}function Wja(e,t){let r={},n={};return e==null?r=t:n={[e]:t},{rootSchemas:r,namespacedSchemas:n}}var h3f="#/components/messages/",J1u=class{logger;document;taskContext;DUMMY;options;namespace;constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(this.document.components==null||this.document.components.schemas==null||!t.$ref.startsWith(xnn))throw new Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(xnn.length).split("/");if(n[0]==null)throw new Error(`${t.$ref} is undefined`);let i=this.document.components.schemas[n[0]];if(i==null)throw new Error(`${n[0]} is undefined`);if(wy(i)&&(i=this.resolveSchemaReference(i)),n[1]==="properties"&&n[2]!=null){let a=i.properties?.[n[2]];if(a==null)throw new Error(`${t.$ref} is undefiened. Property does not exist on object.`);wy(a)?i=this.resolveSchemaReference(a):i=a}return i}resolveMessageReference(t){if(this.document.components==null||this.document.components.messages==null||!t.$ref.startsWith(h3f))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(h3f.length),n=this.document.components.messages[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}},Hja=class extends J1u{constructor({document:t,taskContext:r,options:n,namespace:i}){super({document:t,taskContext:r,options:n,namespace:i})}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}};function Xzr(e){if(typeof e=="string")return i1.primitive(h0.string(e));if(typeof e=="number")return Number.isInteger(e)?i1.primitive(h0.int(e)):i1.primitive(h0.double(e));if(typeof e=="boolean")return i1.primitive(h0.boolean(e));if(Array.isArray(e)){let t=e.map(r=>Xzr(r));return t.length===0?void 0:i1.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=Xzr(n);i!=null&&t.push({key:h0.string(r),value:i})}return i1.map(t)}}function bgi(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function y3f(e){if(e!=null&&Array.isArray(e))return e}var Zzr=class{schemas;constructor(t){this.schemas=t}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:a,options:u,skipReadonly:f}){switch(n.type){case"enum":return typeof r=="string"&&v3f({schema:n,value:r})?i1.enum(r):n.values[0]!=null?i1.enum(n.values[0]?.value):void 0;case"literal":return i1.literal(n.value);case"nullable":{if(r==null&&!this.hasExample(n.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(i,u)))return;let d=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:u,skipReadonly:!1});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(n.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(i,u)))return;let d=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:u,skipReadonly:!1});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:u});return i1.primitive(d)}case"reference":{let d=this.schemas[n.schema];if(d!=null&&!a.has(n.schema)){a.add(n.schema);let c=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:i,options:u,skipReadonly:!1});return a.delete(n.schema),c}return}case"oneOf":switch(n.value.type){case"discriminated":{let d={},c={},o={},l=bgi(r),g=l?.[n.value.discriminantProperty],O=n.value.schemas[g],P=[],j=this.getDiscriminatedUnionVariantSchema(n.value,l);j!=null&&P.push(j),P.push(...Object.entries(n.value.schemas));for(let M of P)if(g!=null&&O!=null&&O.type==="object"){c=this.getAllProperties(O),o=this.getAllRequiredProperties(O),d[n.value.discriminantProperty]=i1.primitive(h0.string(g));break}else{let q=this.getObjectSchema(M[1]);if(q==null)continue;c=this.getAllProperties(q),o=this.getAllRequiredProperties(q),d[n.value.discriminantProperty]=i1.primitive(h0.string(M[0]))}for(let M of n.value.commonProperties){c[M.key]={schema:M.schema,readonly:!1};let q=this.getResolvedSchema(M.schema);q.type!=="optional"&&q.type!=="nullable"&&(o[M.key]=M.schema)}for(let[M,q]of Object.entries(c)){let B=M in o;if(B&&l?.[M]!=null){let I=this.buildExampleHelper({schema:q.schema,exampleId:t,example:l[M],visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});if(I!=null)d[M]=I;else return}else{let I=this.buildExampleHelper({exampleId:t,schema:q.schema,example:l?.[M],visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});if(I!=null)d[M]=I;else if(B)return}}return i1.oneOf(Bzr.discriminated(d))}case"undisciminated":{let d=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:i,options:u,skipReadonly:!1});break}}return;case"unknown":if(r!=null){let d=Xzr(r);if(d!=null)return i1.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(i,u)?void 0:u.isParameter?i1.primitive(h0.string(u.name??"string")):i1.map([{key:h0.string("key"),value:i1.primitive(h0.string("value"))}]);case"array":{let d=y3f(r),c=[];if(d!=null&&d.length>0)for(let o of d){let l=this.buildExampleHelper({exampleId:t,example:o,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});l!=null&&c.push(l)}else if(n.example!=null&&n.example.length>0)for(let o of n.example){let l=this.buildExampleHelper({exampleId:t,example:o,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});l!=null&&c.push(l)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});o!=null&&c.push(o)}return i1.array(c)}case"map":{let d=bgi(r??n.example);if(d!=null&&Object.entries(d).length>0){let l=[];for(let[g,O]of Object.entries(d)){let P=this.buildExampleFromPrimitive({schema:n.key.schema,example:g,options:u}),j=this.buildExampleHelper({exampleId:t,example:O,schema:n.value,visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});j!=null&&l.push({key:P,value:j})}return i1.map(l)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return i1.map([{key:h0.string("key"),value:i1.unknown(i1.primitive(h0.string("value")))}]);let c=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:a,depth:i+1,options:{...u,name:"value"},skipReadonly:!1});return o!=null?i1.map([{key:c,value:o}]):i1.map([])}case"object":{let d={},c=n.fullExamples?.find(O=>O.name===t)??n.fullExamples?.find(O=>O.name==null)??n.fullExamples?.[0],o=bgi(r)??(c!=null?bgi(c.value):{})??{},l=this.getAllProperties(n),g=this.getAllRequiredProperties(n);for(let[O,P]of Object.entries(l)){if(f&&P.readonly)continue;let j=O in g,M=Object.keys(o).includes(O),q=this.buildExampleHelper({schema:P.schema,exampleId:t,example:o[O],visitedSchemaIds:a,depth:i+1,options:{...u,name:O},skipReadonly:!1});if(j&&q!=null)d[O]=q;else{if(j)return;(M&&q!=null||!u.ignoreOptionals&&q!=null)&&(d[O]=q)}}return i1.object({properties:d})}default:xc(n)}}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return v3f({schema:t,value:r})?5:0;case"object":{if(!lS(r))return 0;let n=this.getAllProperties(t),i=0;for(let[a,u]of Object.entries(n))r[a]!=null?(i++,i+=this.calcExampleHeuristic(u.schema,r[a])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!lS(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,a)=>a-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!n.has(t.schema)){n.add(t.schema);let u=this.hasExample(a,r,n,i);return n.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,n,i));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(r[n.key]=n.schema)}for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?h0.string(t):r.example!=null?h0.string(r.example):h0.string(n.name??aD.STRING);case"base64":return t!=null&&typeof t=="string"?h0.base64(t):r.example!=null?h0.base64(r.example):h0.base64(aD.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?h0.boolean(t):r.example!=null?h0.boolean(r.example):h0.boolean(aD.BOOLEAN);case"date":return t!=null&&typeof t=="string"?h0.date(t):r.example!=null?h0.date(r.example):h0.date(aD.DATE);case"datetime":return t!=null&&typeof t=="string"?h0.datetime(t):r.example!=null?h0.datetime(r.example):h0.datetime(aD.DATE_TIME);case"double":return t!=null&&typeof t=="number"?h0.double(t):r.example!=null?h0.double(r.example):h0.double(aD.DOUBLE);case"float":return t!=null&&typeof t=="number"?h0.float(t):r.example!=null?h0.float(r.example):h0.float(aD.FLOAT);case"int":return t!=null&&typeof t=="number"?h0.int(t):r.example!=null?h0.int(r.example):h0.int(aD.INT);case"int64":return t!=null&&typeof t=="number"?h0.int64(t):r.example!=null?h0.int64(r.example):h0.int64(aD.INT64);case"uint":return t!=null&&typeof t=="number"?h0.uint(t):r.example!=null?h0.uint(r.example):h0.uint(aD.UINT);case"uint64":return t!=null&&typeof t=="number"?h0.uint64(t):r.example!=null?h0.uint64(r.example):h0.uint64(aD.UINT64);default:xc(r)}}};function v3f({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function T9t(e){switch(e.type){case"object":return Gp.object({allOf:e.allOf,properties:e.properties.map(t=>F$1(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source});case"array":return Gp.array({description:e.description,availability:e.availability,value:T9t(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0});case"enum":return Gp.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source});case"literal":return Gp.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return Gp.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:T9t(e.value),groupName:e.groupName});case"optional":return Gp.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:T9t(e.value),groupName:e.groupName});case"primitive":return Gp.primitive({description:e.description,availability:e.availability,schema:b3f(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return Gp.map({description:e.description,availability:e.availability,key:Gp.primitive({description:e.key.description,availability:e.key.availability,schema:b3f(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:T9t(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0});case"reference":return Gp.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return Gp.oneOf(R$1(e.value));case"unknown":return Gp.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:xc(e)}}function R$1(e){switch(e.type){case"discriminated":return uk.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:T9t(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,T9t(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source});case"undisciminated":return uk.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>T9t(t)),groupName:e.groupName,encoding:e.encoding,source:e.source});default:xc(e)}}function b3f(e){switch(e.type){case"string":return Ay.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Ay.base64({example:void 0});case"boolean":return Ay.boolean({default:e.default,example:void 0});case"date":return Ay.date({example:void 0});case"datetime":return Ay.datetime({example:void 0});case"double":return Ay.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Ay.float({example:void 0});case"int":return Ay.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Ay.int64({default:e.default,example:void 0});case"uint":return Ay.uint({default:void 0,example:void 0});case"uint64":return Ay.uint64({default:void 0,example:void 0});default:xc(e)}}function F$1(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:T9t(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function Qja(e){return e.type!=="optional"&&e.type!=="nullable"}function ggi(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var Jja=class{exampleTypeFactory;logger;schemas;constructor(t,r){this.schemas=t,this.exampleTypeFactory=new Zzr(t),this.logger=r}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=U$1(t.request),n=V$1(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let g=this.exampleTypeFactory.buildExample({skipReadonly:t.method==="POST"||t.method==="PUT",schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});g!=null&&i.push([void 0,g])}else for(let{name:g,value:O}of r.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:t.method==="POST"||t.method==="PUT",schema:r.schema,exampleId:g,example:O,options:{isParameter:!1,ignoreOptionals:!0}});P!=null&&i.push([g,P])}if(l&&i.length===0)return this.logger.warn(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(n!=null&&n.type==="present"){let l=this.isSchemaRequired(n.schema);if(n.examples.length===0){let g=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:3,isParameter:!1,ignoreOptionals:!1}});g!=null&&(t.response?.type==="json"?a.push([void 0,EIt.withoutStreaming(g)]):t.response?.type==="streamingJson"&&a.push([void 0,EIt.withStreaming([g])]))}else for(let{name:g,value:O}of n.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:g,example:O,options:{maxDepth:3,isParameter:!1,ignoreOptionals:!1}});P!=null&&(t.response?.type==="json"?a.push([g,EIt.withoutStreaming(P)]):t.response?.type==="streamingJson"&&a.push([g,EIt.withStreaming([P])]))}if(l&&a.length===0)return this.logger.warn(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let l of t.pathParameters){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&u.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:O})}let f=[];for(let l of t.queryParameters){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&f.push({name:l.name,value:O})}let d=[];for(let l of t.headers){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&d.push({name:l.name,value:O})}let c=[];t.request!=null&&t.response!=null?c=L$1(i,a):t.request!=null?c=i.map(([l,g])=>({id:l,request:g,response:void 0})):t.response!=null&&(c=a.map(([l,g])=>({id:l,request:void 0,response:g})));let o=t.examples.filter(l=>ggi(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let g=l.value["code-samples"];if(g!=null)return this.convertCodeSamples(g)}return}else return l.codeSamples}).filter(l=>$M(l));return c.length===0?[SIt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:f,headers:d,request:void 0,response:void 0,codeSamples:o})]:c.map(({id:l,request:g,response:O})=>SIt.full({name:l,description:void 0,pathParameters:u,queryParameters:f,headers:d,request:g,response:O,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?RAr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):RAr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GH.Csharp:r.sdk,code:r.code})).filter($M)}isSchemaRequired(t){return Qja(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function L$1(e,t){let r=[];if(e.length<=1){let[i,a]=e[0]??[];if(t.length===0)return r.push({id:i,request:a,response:void 0}),r;for(let[u,f]of t)r.push({id:u??i,request:a,response:f});return r}if(t.length<=1){let[i,a]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:a}),r;for(let[u,f]of e)r.push({id:u??i,request:f,response:a});return r}let n=new Set;for(let[i,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(i==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let f=!1;for(let d=0;d<t.length;d++){let[c,o]=t[d];c!=null||n.has(d)||i===c&&(r.push({id:i,request:a,response:o}),c!=null&&n.add(d),f=!0)}!f&&u!=null&&r.push({id:i,request:a,response:u})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[a,u]=t[i],f=e.find(([d])=>d==null)?.[1]??e[0]?.[1];f!=null&&r.push({id:a,request:f,response:u})}return r}function U$1(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:W$1(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function V$1(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function C9t(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return C9t(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undisciminated":return C9t(e.value.value);default:return!1}default:xc(e)}}function W$1(e){return Gp.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:T9t(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0}).filter($M),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source})}var Gja=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Zzr(t),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:n,subscribe:i,handshake:a,source:u,namespace:f}){let d=[];for(let c of r){let o=[];for(let O of a.queryParameters){let P=this.isSchemaRequired(O.schema),j=this.exampleTypeFactory.buildExample({schema:O.schema,exampleId:void 0,example:c.queryParameters?.[O.name],options:{name:O.name,isParameter:!0,ignoreOptionals:!0}});j!=null&&!C9t(j)&&(j=void 0),!(P&&j==null)&&j!=null&&o.push({name:O.name,value:j})}let l=[];for(let O of a.headers){let P=this.isSchemaRequired(O.schema),j=this.exampleTypeFactory.buildExample({schema:O.schema,exampleId:void 0,example:c.headers?.[O.name],options:{name:O.name,isParameter:!0,ignoreOptionals:!0}});j!=null&&!C9t(j)&&(j=void 0),!(P&&j==null)&&j!=null&&l.push({name:O.name,value:j})}let g=[];for(let O of c.messages){let P=t.resolveMessageReference({$ref:`#/components/messages/${O.messageId}`}),j=wy(P.payload)?t.resolveSchemaReference(P.payload):P.payload,M=this.exampleTypeFactory.buildExample({schema:a1(j,!1,t,[O.messageId],u,f),exampleId:void 0,example:O.value,options:{isParameter:!1,ignoreOptionals:!0}});M!=null&&g.push({messageType:O.type,payload:M,description:void 0})}d.push({name:c.summary,queryParameters:o,headers:l,description:c.description,messages:g})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:n}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let f of n.queryParameters){let d=this.isSchemaRequired(f.schema),c=this.exampleTypeFactory.buildExample({schema:f.schema,exampleId:void 0,example:void 0,options:{name:f.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!C9t(c)&&(c=void 0),d&&c==null)return;c!=null&&a.push({name:f.name,value:c})}let u=[];for(let f of n.headers){let d=this.isSchemaRequired(f.schema),c=this.exampleTypeFactory.buildExample({schema:f.schema,exampleId:void 0,example:void 0,options:{name:f.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!C9t(c)&&(c=void 0),d&&c==null)return;c!=null&&u.push({name:f.name,value:c})}if(t!=null){let f=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});f!=null&&i.messages.push({messageType:"publish",payload:f,description:void 0})}if(r!=null){let f=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});f!=null&&i.messages.push({messageType:"subscribe",payload:f,description:void 0})}return i}isSchemaRequired(t){return Qja(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var mgi={FERN_DISPLAY_NAME:"x-fern-display-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path"};function g3f(e){return hh(e,mgi.FERN_EXAMPLES)??[]}function O3f({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:a}){let u=[];a!=null&&u.push(a),e.tags?.[0]!=null?u.push(e.tags[0].name):i.naming!=="v2"&&u.push("websocket");let f=new Hja({document:e,taskContext:t,options:r,namespace:a}),d={},c;for(let[l,g]of Object.entries(e.components?.schemas??{})){let O=a1(g,!1,f,[l],n,a);d[l]=O}let o=new Gja(d,t.logger);for(let[l,g]of Object.entries(e.channels??{})){if(g.bindings?.ws==null){f.logger.error(`Channel ${l} does not have websocket bindings. Skipping.`);continue}let O=[];if(g.parameters!=null)for(let[B,I]of Object.entries(g.parameters??{}))O.push({name:B,description:I.description,parameterNameOverride:void 0,schema:I.schema!=null?a1(I.schema,!1,f,u,n,a):Gp.primitive({schema:Ay.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:O2e(I),source:n});let P=[];if(g.bindings.ws.headers!=null){let B=g.bindings.ws.headers.required??[];for(let[I,C]of Object.entries(g.bindings.ws.headers.properties??{})){let F=wy(C)?f.resolveSchemaReference(C):C;P.push({name:I,schema:a1(F,!B.includes(I),f,u,n,a),description:F.description,parameterNameOverride:void 0,env:void 0,availability:O2e(F),source:n})}}let j=[];if(g.bindings.ws.query!=null){let B=g.bindings.ws.query.required??[];for(let[I,C]of Object.entries(g.bindings.ws.query.properties??{})){let F=wy(C)?f.resolveSchemaReference(C):C;j.push({name:I,schema:a1(F,!B.includes(I),f,u,n,a),description:F.description,parameterNameOverride:void 0,availability:O2e(F),source:n})}}let M;g.publish!=null&&(M=m3f({generatedName:g.publish.operationId??"PublishEvent",event:g.publish,breadcrumbs:u,context:f,source:n,options:r,asyncApiOptions:i}));let q;if(g.subscribe!=null&&(q=m3f({generatedName:g.subscribe.operationId??"SubscribeEvent",event:g.subscribe,breadcrumbs:u,context:f,source:n,options:r,asyncApiOptions:i})),P.length>0||j.length>0||M!=null||q!=null){let B=g3f(g),I=[];if(B.length>0)I=o.buildWebsocketSessionExamplesForExtension({context:f,extensionExamples:B,handshake:{headers:P,queryParameters:j},publish:M,subscribe:q,source:n,namespace:a});else{let F=o.buildWebsocketSessionExample({handshake:{headers:P,queryParameters:j},publish:M,subscribe:q});F!=null&&I.push(F)}let C=e.tags?.[0]?.name!=null?[e.tags?.[0].name]:void 0;c={handshake:{headers:P.map(F=>({...F,schema:YC(F.schema),env:F.env})),queryParameters:j.map(F=>({...F,schema:YC(F.schema)})),pathParameters:O.map(F=>({...F,parameterNameOverride:void 0,schema:YC(F.schema)}))},groupName:f.resolveTags(C,"Websocket"),publish:M!=null?YC(M):M,subscribe:q!=null?YC(q):q,summary:hh(g,mgi.FERN_DISPLAY_NAME),path:l,description:void 0,examples:I,source:n};break}}return{groupedSchemas:Wja(a,d),channel:c,basePath:hh(e,mgi.BASE_PATH)}}function m3f({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:a,asyncApiOptions:u}){if(t.message.oneOf!=null){let f=[],d=[];for(let c of t.message.oneOf){let o,l={type:"notFound"};if(wy(c)){let g=r.resolveMessageReference(c);!wy(g.payload)&&u.naming==="v2"?(l=g.name?{type:"name",name:g.name}:l,o={...g.payload,title:g.name??g.payload.title,description:g.name??g.payload.description}):o=g.payload}else o=c;d.push(l),f.push(o)}return mNn({description:t.description??t.message.description,availability:O2e(t.message),subtypes:f,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}var lin=Xo(uUf(),1);var sUf=require("fs/promises");async function rAa({absoluteFilepathToOverrides:e,data:t,context:r}){let n=null;try{let i=(await(0,sUf.readFile)(e,"utf8")).toString();try{n=JSON.parse(i)}catch{n=d0.load(i,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return BKo({data:t,overrides:n})}var tbw={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},rbw={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:tbw,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}};async function lUf({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,context:r}){let n=await cUf({absolutePathToOpenAPI:e}),i;if(t!=null?i=t:typeof n=="object"&&n[kh.OPENAPI_OVERIDES_FILEPATH]!=null&&(i=yf(cb(e),Ms.of(n[kh.OPENAPI_OVERIDES_FILEPATH]))),i!=null){let a=await rAa({absoluteFilepathToOverrides:i,context:r,data:n});return await cUf({absolutePathToOpenAPI:e,parsed:a})}return n}async function cUf({absolutePathToOpenAPI:e,parsed:t}){let r={config:new lin.Config({apis:{},styleguide:{plugins:[rbw],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};return(t!=null?await(0,lin.bundle)({...r,doc:{source:new lin.Source(e,"<openapi>"),parsed:t}}):await(0,lin.bundle)({...r,ref:e})).bundle.parsed}var PJf=Xo(bQf(),1);function gQf(e){return hh(e,kh.ASYNC_CONFIG)}var mQf="$request.";function OQf(e){let t=hh(e,kh.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:_ww(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function _ww(e){return e.startsWith(mQf)?e.slice(mQf.length):e}function PQf(e){let t=e;if(t.cursor!=null)return zAr.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;return zAr.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}function wQf(e,t){let r=hh(t,kh.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=hh(e,kh.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:PQf(n)}return PQf(r)}}function jQf(e){let t=hww(e),r={};return yxu({obj:t,occurrences:r,breadcrumbs:[]}),r}function yxu({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)yxu({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)yxu({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function hww(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?gOi(r.get):void 0,put:r?.put!=null?gOi(r.put):void 0,post:r?.post!=null?gOi(r.post):void 0,patch:r?.patch!=null?gOi(r.patch):void 0,delete:r?.delete!=null?gOi(r.delete):void 0}]))}}function gOi(e){return{...e,requestBody:e.requestBody!=null?wy(e.requestBody)?e.requestBody:yww(e.requestBody):void 0}}function yww(e){let t,r;for(let n in e.content){let i=D4.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[D4.MULTIPART_FORM_DATA]:r}}:e}var DQf="#/components/parameters/",SQf="#/components/responses/",EQf="#/components/examples/",AQf="#/components/requestBodies/",z8n=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;namespace;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=jQf(t),this.options=i,this.source=a,this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown",additionalProperties:!0};n=n[i]}return n==null?{"x-fern-type":"unknown",additionalProperties:!0}:(wy(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(DQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(DQf.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(AQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(AQf.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(SQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(SQf.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(EQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(EQf.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveExampleReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}};var R8n=class extends z8n{constructor({document:t,taskContext:r,options:n,source:i,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var Sx;(function(e){e.assertEqual=i=>i;function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let a={};for(let u of i)a[u]=u;return a},e.getValidEnumValues=i=>{let a=e.objectKeys(i).filter(f=>typeof i[i[f]]!="number"),u={};for(let f of a)u[f]=i[f];return e.objectValues(u)},e.objectValues=i=>e.objectKeys(i).map(function(a){return i[a]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let u in i)Object.prototype.hasOwnProperty.call(i,u)&&a.push(u);return a},e.find=(i,a)=>{for(let u of i)if(a(u))return u},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,a=" | "){return i.map(u=>typeof u=="string"?`'${u}'`:u).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Sx||(Sx={}));var bxu;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(bxu||(bxu={}));var C0=Sx.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),V5r=e=>{switch(typeof e){case"undefined":return C0.undefined;case"string":return C0.string;case"number":return isNaN(e)?C0.nan:C0.number;case"boolean":return C0.boolean;case"function":return C0.function;case"bigint":return C0.bigint;case"symbol":return C0.symbol;case"object":return Array.isArray(e)?C0.array:e===null?C0.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C0.promise:typeof Map<"u"&&e instanceof Map?C0.map:typeof Set<"u"&&e instanceof Set?C0.set:typeof Date<"u"&&e instanceof Date?C0.date:C0.object;default:return C0.unknown}},vh=Sx.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),vww=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),NDe=class e extends Error{constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){let r=t||function(a){return a.message},n={_errors:[]},i=a=>{for(let u of a.issues)if(u.code==="invalid_union")u.unionErrors.map(i);else if(u.code==="invalid_return_type")i(u.returnTypeError);else if(u.code==="invalid_arguments")i(u.argumentsError);else if(u.path.length===0)n._errors.push(r(u));else{let f=n,d=0;for(;d<u.path.length;){let c=u.path[d];d===u.path.length-1?(f[c]=f[c]||{_errors:[]},f[c]._errors.push(r(u))):f[c]=f[c]||{_errors:[]},f=f[c],d++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Sx.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};NDe.create=e=>new NDe(e);var U8n=(e,t)=>{let r;switch(e.code){case vh.invalid_type:e.received===C0.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case vh.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Sx.jsonStringifyReplacer)}`;break;case vh.unrecognized_keys:r=`Unrecognized key(s) in object: ${Sx.joinValues(e.keys,", ")}`;break;case vh.invalid_union:r="Invalid input";break;case vh.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Sx.joinValues(e.options)}`;break;case vh.invalid_enum_value:r=`Invalid enum value. Expected ${Sx.joinValues(e.options)}, received '${e.received}'`;break;case vh.invalid_arguments:r="Invalid function arguments";break;case vh.invalid_return_type:r="Invalid function return type";break;case vh.invalid_date:r="Invalid date";break;case vh.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Sx.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case vh.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case vh.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case vh.custom:r="Invalid input";break;case vh.invalid_intersection_types:r="Intersection results could not be merged";break;case vh.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case vh.not_finite:r="Number must be finite";break;default:r=t.defaultError,Sx.assertNever(e)}return{message:r}},TQf=U8n;function bww(e){TQf=e}function lMa(){return TQf}var fMa=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,a=[...r,...i.path||[]],u={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let f="",d=n.filter(c=>!!c).slice().reverse();for(let c of d)f=c(u,{data:t,defaultError:f}).message;return{...i,path:a,message:f}},gww=[];function u0(e,t){let r=lMa(),n=fMa({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===U8n?void 0:U8n].filter(i=>!!i)});e.common.issues.push(n)}var H$=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return aP;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let a=await i.key,u=await i.value;n.push({key:a,value:u})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:a,value:u}=i;if(a.status==="aborted"||u.status==="aborted")return aP;a.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof u.value<"u"||i.alwaysSet)&&(n[a.value]=u.value)}return{status:t.value,value:n}}},aP=Object.freeze({status:"aborted"}),L8n=e=>({status:"dirty",value:e}),wk=e=>({status:"valid",value:e}),gxu=e=>e.status==="aborted",mxu=e=>e.status==="dirty",POi=e=>e.status==="valid",wOi=e=>typeof Promise<"u"&&e instanceof Promise;function dMa(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}function CQf(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r}var Sg;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Sg||(Sg={}));var mOi,OOi,B2e=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},MQf=(e,t)=>{if(POi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new NDe(e.common.issues);return this._error=r,this._error}}};function Ej(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(u,f)=>{var d,c;let{message:o}=e;return u.code==="invalid_enum_value"?{message:o??f.defaultError}:typeof f.data>"u"?{message:(d=o??n)!==null&&d!==void 0?d:f.defaultError}:u.code!=="invalid_type"?{message:f.defaultError}:{message:(c=o??r)!==null&&c!==void 0?c:f.defaultError}},description:i}}var Aj=class{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return V5r(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:V5r(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new H$,ctx:{common:t.parent.common,data:t.data,parsedType:V5r(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(wOi(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){var n;let i={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:V5r(t)},a=this._parseSync({data:t,path:i.path,parent:i});return MQf(i,a)}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:V5r(t)},i=this._parse({data:t,path:n.path,parent:n}),a=await(wOi(i)?i:Promise.resolve(i));return MQf(n,a)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let u=t(i),f=()=>a.addIssue({code:vh.custom,...n(i)});return typeof Promise<"u"&&u instanceof Promise?u.then(d=>d?!0:(f(),!1)):u?!0:(f(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new zDe({schema:this,typeName:CO.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return I2e.create(this,this._def)}nullable(){return Y9t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return iMr.create(this,this._def)}promise(){return Q5r.create(this,this._def)}or(t){return Ain.create([this,t],this._def)}and(t){return Min.create(this,t,this._def)}transform(t){return new zDe({...Ej(this._def),schema:this,typeName:CO.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Iin({...Ej(this._def),innerType:this,defaultValue:r,typeName:CO.ZodDefault})}brand(){return new jOi({typeName:CO.ZodBranded,type:this,...Ej(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Bin({...Ej(this._def),innerType:this,catchValue:r,typeName:CO.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return DOi.create(this,t)}readonly(){return Nin.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mww=/^c[^\s-]{8,}$/i,Oww=/^[0-9a-z]+$/,Pww=/^[0-9A-HJKMNP-TV-Z]{26}$/,www=/^[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}$/i,jww=/^[a-z0-9_-]{21}$/i,Dww=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Sww=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eww="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vxu,Aww=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mww=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,xww=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qQf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Tww=new RegExp(`^${qQf}$`);function IQf(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Cww(e){return new RegExp(`^${IQf(e)}$`)}function BQf(e){let t=`${qQf}T${IQf(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function qww(e,t){return!!((t==="v4"||!t)&&Aww.test(e)||(t==="v6"||!t)&&Mww.test(e))}var W5r=class e extends Aj{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C0.string){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.string,received:a.parsedType}),aP}let n=new H$,i;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let u=t.data.length>a.value,f=t.data.length<a.value;(u||f)&&(i=this._getOrReturnCtx(t,i),u?u0(i,{code:vh.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):f&&u0(i,{code:vh.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Sww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"email",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")vxu||(vxu=new RegExp(Eww,"u")),vxu.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"emoji",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")www.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"uuid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")jww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"nanoid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")mww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"cuid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Oww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"cuid2",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Pww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"ulid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),u0(i,{validation:"url",code:vh.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"regex",code:vh.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?BQf(a).test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Tww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Cww(a).test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Dww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"duration",code:vh.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?qww(t.data,a.version)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"ip",code:vh.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?xww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"base64",code:vh.invalid_string,message:a.message}),n.dirty()):Sx.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:vh.invalid_string,...Sg.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Sg.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Sg.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Sg.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Sg.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Sg.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Sg.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Sg.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Sg.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Sg.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Sg.errToObj(t)})}datetime(t){var r,n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(r=t?.offset)!==null&&r!==void 0?r:!1,local:(n=t?.local)!==null&&n!==void 0?n:!1,...Sg.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Sg.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Sg.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Sg.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Sg.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Sg.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Sg.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Sg.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Sg.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Sg.errToObj(r)})}nonempty(t){return this.min(1,Sg.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};W5r.create=e=>{var t;return new W5r({checks:[],typeName:CO.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Ej(e)})};function Iww(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,a=parseInt(e.toFixed(i).replace(".","")),u=parseInt(t.toFixed(i).replace(".",""));return a%u/Math.pow(10,i)}var Pin=class e extends Aj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==C0.number){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.number,received:a.parsedType}),aP}let n,i=new H$;for(let a of this._def.checks)a.kind==="int"?Sx.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Iww(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_finite,message:a.message}),i.dirty()):Sx.assertNever(a);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Sg.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Sg.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Sg.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Sg.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Sg.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Sg.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sg.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sg.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sg.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sg.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Sg.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Sg.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sg.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sg.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Sx.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Pin.create=e=>new Pin({checks:[],typeName:CO.ZodNumber,coerce:e?.coerce||!1,...Ej(e)});var win=class e extends Aj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==C0.bigint){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.bigint,received:a.parsedType}),aP}let n,i=new H$;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Sx.assertNever(a);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Sg.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Sg.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Sg.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Sg.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Sg.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sg.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sg.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sg.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sg.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Sg.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};win.create=e=>{var t;return new win({checks:[],typeName:CO.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Ej(e)})};var jin=class extends Aj{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C0.boolean){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.boolean,received:n.parsedType}),aP}return wk(t.data)}};jin.create=e=>new jin({typeName:CO.ZodBoolean,coerce:e?.coerce||!1,...Ej(e)});var Din=class e extends Aj{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C0.date){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.date,received:a.parsedType}),aP}if(isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_date}),aP}let n=new H$,i;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Sx.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Sg.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Sg.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Din.create=e=>new Din({checks:[],coerce:e?.coerce||!1,typeName:CO.ZodDate,...Ej(e)});var V8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.symbol){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.symbol,received:n.parsedType}),aP}return wk(t.data)}};V8n.create=e=>new V8n({typeName:CO.ZodSymbol,...Ej(e)});var Sin=class extends Aj{_parse(t){if(this._getType(t)!==C0.undefined){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.undefined,received:n.parsedType}),aP}return wk(t.data)}};Sin.create=e=>new Sin({typeName:CO.ZodUndefined,...Ej(e)});var Ein=class extends Aj{_parse(t){if(this._getType(t)!==C0.null){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.null,received:n.parsedType}),aP}return wk(t.data)}};Ein.create=e=>new Ein({typeName:CO.ZodNull,...Ej(e)});var H5r=class extends Aj{constructor(){super(...arguments),this._any=!0}_parse(t){return wk(t.data)}};H5r.create=e=>new H5r({typeName:CO.ZodAny,...Ej(e)});var nMr=class extends Aj{constructor(){super(...arguments),this._unknown=!0}_parse(t){return wk(t.data)}};nMr.create=e=>new nMr({typeName:CO.ZodUnknown,...Ej(e)});var LIt=class extends Aj{_parse(t){let r=this._getOrReturnCtx(t);return u0(r,{code:vh.invalid_type,expected:C0.never,received:r.parsedType}),aP}};LIt.create=e=>new LIt({typeName:CO.ZodNever,...Ej(e)});var W8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.undefined){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.void,received:n.parsedType}),aP}return wk(t.data)}};W8n.create=e=>new W8n({typeName:CO.ZodVoid,...Ej(e)});var iMr=class e extends Aj{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==C0.array)return u0(r,{code:vh.invalid_type,expected:C0.array,received:r.parsedType}),aP;if(i.exactLength!==null){let u=r.data.length>i.exactLength.value,f=r.data.length<i.exactLength.value;(u||f)&&(u0(r,{code:u?vh.too_big:vh.too_small,minimum:f?i.exactLength.value:void 0,maximum:u?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(u0(r,{code:vh.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(u0(r,{code:vh.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((u,f)=>i.type._parseAsync(new B2e(r,u,r.path,f)))).then(u=>H$.mergeArray(n,u));let a=[...r.data].map((u,f)=>i.type._parseSync(new B2e(r,u,r.path,f)));return H$.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Sg.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Sg.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Sg.toString(r)}})}nonempty(t){return this.min(1,t)}};iMr.create=(e,t)=>new iMr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:CO.ZodArray,...Ej(t)});function F8n(e){if(e instanceof Oae){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=I2e.create(F8n(n))}return new Oae({...e._def,shape:()=>t})}else return e instanceof iMr?new iMr({...e._def,type:F8n(e.element)}):e instanceof I2e?I2e.create(F8n(e.unwrap())):e instanceof Y9t?Y9t.create(F8n(e.unwrap())):e instanceof K9t?K9t.create(e.items.map(t=>F8n(t))):e}var Oae=class e extends Aj{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Sx.objectKeys(t);return this._cached={shape:t,keys:r}}_parse(t){if(this._getType(t)!==C0.object){let c=this._getOrReturnCtx(t);return u0(c,{code:vh.invalid_type,expected:C0.object,received:c.parsedType}),aP}let{status:n,ctx:i}=this._processInputParams(t),{shape:a,keys:u}=this._getCached(),f=[];if(!(this._def.catchall instanceof LIt&&this._def.unknownKeys==="strip"))for(let c in i.data)u.includes(c)||f.push(c);let d=[];for(let c of u){let o=a[c],l=i.data[c];d.push({key:{status:"valid",value:c},value:o._parse(new B2e(i,l,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof LIt){let c=this._def.unknownKeys;if(c==="passthrough")for(let o of f)d.push({key:{status:"valid",value:o},value:{status:"valid",value:i.data[o]}});else if(c==="strict")f.length>0&&(u0(i,{code:vh.unrecognized_keys,keys:f}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let o of f){let l=i.data[o];d.push({key:{status:"valid",value:o},value:c._parse(new B2e(i,l,i.path,o)),alwaysSet:o in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let o of d){let l=await o.key,g=await o.value;c.push({key:l,value:g,alwaysSet:o.alwaysSet})}return c}).then(c=>H$.mergeObjectSync(n,c)):H$.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(t){return Sg.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var i,a,u,f;let d=(u=(a=(i=this._def).errorMap)===null||a===void 0?void 0:a.call(i,r,n).message)!==null&&u!==void 0?u:n.defaultError;return r.code==="unrecognized_keys"?{message:(f=Sg.errToObj(t).message)!==null&&f!==void 0?f:d}:{message:d}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:CO.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};return Sx.objectKeys(t).forEach(n=>{t[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}omit(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{t[n]||(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}deepPartial(){return F8n(this)}partial(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}),new e({...this._def,shape:()=>r})}required(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof I2e;)a=a._def.innerType;r[n]=a}}),new e({...this._def,shape:()=>r})}keyof(){return NQf(Sx.objectKeys(this.shape))}};Oae.create=(e,t)=>new Oae({shape:()=>e,unknownKeys:"strip",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});Oae.strictCreate=(e,t)=>new Oae({shape:()=>e,unknownKeys:"strict",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});Oae.lazycreate=(e,t)=>new Oae({shape:e,unknownKeys:"strip",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});var Ain=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(a){for(let f of a)if(f.result.status==="valid")return f.result;for(let f of a)if(f.result.status==="dirty")return r.common.issues.push(...f.ctx.common.issues),f.result;let u=a.map(f=>new NDe(f.ctx.common.issues));return u0(r,{code:vh.invalid_union,unionErrors:u}),aP}if(r.common.async)return Promise.all(n.map(async a=>{let u={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(i);{let a,u=[];for(let d of n){let c={...r,common:{...r.common,issues:[]},parent:null},o=d._parseSync({data:r.data,path:r.path,parent:c});if(o.status==="valid")return o;o.status==="dirty"&&!a&&(a={result:o,ctx:c}),c.common.issues.length&&u.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let f=u.map(d=>new NDe(d));return u0(r,{code:vh.invalid_union,unionErrors:f}),aP}}get options(){return this._def.options}};Ain.create=(e,t)=>new Ain({options:e,typeName:CO.ZodUnion,...Ej(t)});var rMr=e=>e instanceof xin?rMr(e.schema):e instanceof zDe?rMr(e.innerType()):e instanceof Tin?[e.value]:e instanceof Cin?e.options:e instanceof qin?Sx.objectValues(e.enum):e instanceof Iin?rMr(e._def.innerType):e instanceof Sin?[void 0]:e instanceof Ein?[null]:e instanceof I2e?[void 0,...rMr(e.unwrap())]:e instanceof Y9t?[null,...rMr(e.unwrap())]:e instanceof jOi||e instanceof Nin?rMr(e.unwrap()):e instanceof Bin?rMr(e._def.innerType):[],pMa=class e extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.object)return u0(r,{code:vh.invalid_type,expected:C0.object,received:r.parsedType}),aP;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(u0(r,{code:vh.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),aP)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let a of r){let u=rMr(a.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of u){if(i.has(f))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);i.set(f,a)}}return new e({typeName:CO.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ej(n)})}};function Oxu(e,t){let r=V5r(e),n=V5r(t);if(e===t)return{valid:!0,data:e};if(r===C0.object&&n===C0.object){let i=Sx.objectKeys(t),a=Sx.objectKeys(e).filter(f=>i.indexOf(f)!==-1),u={...e,...t};for(let f of a){let d=Oxu(e[f],t[f]);if(!d.valid)return{valid:!1};u[f]=d.data}return{valid:!0,data:u}}else if(r===C0.array&&n===C0.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let a=0;a<e.length;a++){let u=e[a],f=t[a],d=Oxu(u,f);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return r===C0.date&&n===C0.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Min=class extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(a,u)=>{if(gxu(a)||gxu(u))return aP;let f=Oxu(a.value,u.value);return f.valid?((mxu(a)||mxu(u))&&r.dirty(),{status:r.value,value:f.data}):(u0(n,{code:vh.invalid_intersection_types}),aP)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,u])=>i(a,u)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Min.create=(e,t,r)=>new Min({left:e,right:t,typeName:CO.ZodIntersection,...Ej(r)});var K9t=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.array)return u0(n,{code:vh.invalid_type,expected:C0.array,received:n.parsedType}),aP;if(n.data.length<this._def.items.length)return u0(n,{code:vh.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),aP;!this._def.rest&&n.data.length>this._def.items.length&&(u0(n,{code:vh.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((u,f)=>{let d=this._def.items[f]||this._def.rest;return d?d._parse(new B2e(n,u,n.path,f)):null}).filter(u=>!!u);return n.common.async?Promise.all(a).then(u=>H$.mergeArray(r,u)):H$.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};K9t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K9t({items:e,typeName:CO.ZodTuple,rest:null,...Ej(t)})};var _Ma=class e extends Aj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.object)return u0(n,{code:vh.invalid_type,expected:C0.object,received:n.parsedType}),aP;let i=[],a=this._def.keyType,u=this._def.valueType;for(let f in n.data)i.push({key:a._parse(new B2e(n,f,n.path,f)),value:u._parse(new B2e(n,n.data[f],n.path,f)),alwaysSet:f in n.data});return n.common.async?H$.mergeObjectAsync(r,i):H$.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Aj?new e({keyType:t,valueType:r,typeName:CO.ZodRecord,...Ej(n)}):new e({keyType:W5r.create(),valueType:t,typeName:CO.ZodRecord,...Ej(r)})}},H8n=class extends Aj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.map)return u0(n,{code:vh.invalid_type,expected:C0.map,received:n.parsedType}),aP;let i=this._def.keyType,a=this._def.valueType,u=[...n.data.entries()].map(([f,d],c)=>({key:i._parse(new B2e(n,f,n.path,[c,"key"])),value:a._parse(new B2e(n,d,n.path,[c,"value"]))}));if(n.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let d of u){let c=await d.key,o=await d.value;if(c.status==="aborted"||o.status==="aborted")return aP;(c.status==="dirty"||o.status==="dirty")&&r.dirty(),f.set(c.value,o.value)}return{status:r.value,value:f}})}else{let f=new Map;for(let d of u){let c=d.key,o=d.value;if(c.status==="aborted"||o.status==="aborted")return aP;(c.status==="dirty"||o.status==="dirty")&&r.dirty(),f.set(c.value,o.value)}return{status:r.value,value:f}}}};H8n.create=(e,t,r)=>new H8n({valueType:t,keyType:e,typeName:CO.ZodMap,...Ej(r)});var Q8n=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.set)return u0(n,{code:vh.invalid_type,expected:C0.set,received:n.parsedType}),aP;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(u0(n,{code:vh.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(u0(n,{code:vh.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function u(d){let c=new Set;for(let o of d){if(o.status==="aborted")return aP;o.status==="dirty"&&r.dirty(),c.add(o.value)}return{status:r.value,value:c}}let f=[...n.data.values()].map((d,c)=>a._parse(new B2e(n,d,n.path,c)));return n.common.async?Promise.all(f).then(d=>u(d)):u(f)}min(t,r){return new e({...this._def,minSize:{value:t,message:Sg.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Sg.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Q8n.create=(e,t)=>new Q8n({valueType:e,minSize:null,maxSize:null,typeName:CO.ZodSet,...Ej(t)});var hMa=class e extends Aj{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.function)return u0(r,{code:vh.invalid_type,expected:C0.function,received:r.parsedType}),aP;function n(f,d){return fMa({data:f,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lMa(),U8n].filter(c=>!!c),issueData:{code:vh.invalid_arguments,argumentsError:d}})}function i(f,d){return fMa({data:f,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lMa(),U8n].filter(c=>!!c),issueData:{code:vh.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},u=r.data;if(this._def.returns instanceof Q5r){let f=this;return wk(async function(...d){let c=new NDe([]),o=await f._def.args.parseAsync(d,a).catch(O=>{throw c.addIssue(n(d,O)),c}),l=await Reflect.apply(u,this,o);return await f._def.returns._def.type.parseAsync(l,a).catch(O=>{throw c.addIssue(i(l,O)),c})})}else{let f=this;return wk(function(...d){let c=f._def.args.safeParse(d,a);if(!c.success)throw new NDe([n(d,c.error)]);let o=Reflect.apply(u,this,c.data),l=f._def.returns.safeParse(o,a);if(!l.success)throw new NDe([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:K9t.create(t).rest(nMr.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||K9t.create([]).rest(nMr.create()),returns:r||nMr.create(),typeName:CO.ZodFunction,...Ej(n)})}},xin=class extends Aj{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};xin.create=(e,t)=>new xin({getter:e,typeName:CO.ZodLazy,...Ej(t)});var Tin=class extends Aj{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return u0(r,{received:r.data,code:vh.invalid_literal,expected:this._def.value}),aP}return{status:"valid",value:t.data}}get value(){return this._def.value}};Tin.create=(e,t)=>new Tin({value:e,typeName:CO.ZodLiteral,...Ej(t)});function NQf(e,t){return new Cin({values:e,typeName:CO.ZodEnum,...Ej(t)})}var Cin=class e extends Aj{constructor(){super(...arguments),mOi.set(this,void 0)}_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return u0(r,{expected:Sx.joinValues(n),received:r.parsedType,code:vh.invalid_type}),aP}if(dMa(this,mOi,"f")||CQf(this,mOi,new Set(this._def.values),"f"),!dMa(this,mOi,"f").has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return u0(r,{received:r.data,code:vh.invalid_enum_value,options:n}),aP}return wk(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};mOi=new WeakMap;Cin.create=NQf;var qin=class extends Aj{constructor(){super(...arguments),OOi.set(this,void 0)}_parse(t){let r=Sx.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==C0.string&&n.parsedType!==C0.number){let i=Sx.objectValues(r);return u0(n,{expected:Sx.joinValues(i),received:n.parsedType,code:vh.invalid_type}),aP}if(dMa(this,OOi,"f")||CQf(this,OOi,new Set(Sx.getValidEnumValues(this._def.values)),"f"),!dMa(this,OOi,"f").has(t.data)){let i=Sx.objectValues(r);return u0(n,{received:n.data,code:vh.invalid_enum_value,options:i}),aP}return wk(t.data)}get enum(){return this._def.values}};OOi=new WeakMap;qin.create=(e,t)=>new qin({values:e,typeName:CO.ZodNativeEnum,...Ej(t)});var Q5r=class extends Aj{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.promise&&r.common.async===!1)return u0(r,{code:vh.invalid_type,expected:C0.promise,received:r.parsedType}),aP;let n=r.parsedType===C0.promise?r.data:Promise.resolve(r.data);return wk(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Q5r.create=(e,t)=>new Q5r({type:e,typeName:CO.ZodPromise,...Ej(t)});var zDe=class extends Aj{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===CO.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,a={addIssue:u=>{u0(n,u),u.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let u=i.transform(n.data,a);if(n.common.async)return Promise.resolve(u).then(async f=>{if(r.value==="aborted")return aP;let d=await this._def.schema._parseAsync({data:f,path:n.path,parent:n});return d.status==="aborted"?aP:d.status==="dirty"||r.value==="dirty"?L8n(d.value):d});{if(r.value==="aborted")return aP;let f=this._def.schema._parseSync({data:u,path:n.path,parent:n});return f.status==="aborted"?aP:f.status==="dirty"||r.value==="dirty"?L8n(f.value):f}}if(i.type==="refinement"){let u=f=>{let d=i.refinement(f,a);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(n.common.async===!1){let f=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return f.status==="aborted"?aP:(f.status==="dirty"&&r.dirty(),u(f.value),{status:r.value,value:f.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(f=>f.status==="aborted"?aP:(f.status==="dirty"&&r.dirty(),u(f.value).then(()=>({status:r.value,value:f.value}))))}if(i.type==="transform")if(n.common.async===!1){let u=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!POi(u))return u;let f=i.transform(u.value,a);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:f}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(u=>POi(u)?Promise.resolve(i.transform(u.value,a)).then(f=>({status:r.value,value:f})):u);Sx.assertNever(i)}};zDe.create=(e,t,r)=>new zDe({schema:e,typeName:CO.ZodEffects,effect:t,...Ej(r)});zDe.createWithPreprocess=(e,t,r)=>new zDe({schema:t,effect:{type:"preprocess",transform:e},typeName:CO.ZodEffects,...Ej(r)});var I2e=class extends Aj{_parse(t){return this._getType(t)===C0.undefined?wk(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};I2e.create=(e,t)=>new I2e({innerType:e,typeName:CO.ZodOptional,...Ej(t)});var Y9t=class extends Aj{_parse(t){return this._getType(t)===C0.null?wk(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Y9t.create=(e,t)=>new Y9t({innerType:e,typeName:CO.ZodNullable,...Ej(t)});var Iin=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===C0.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Iin.create=(e,t)=>new Iin({innerType:e,typeName:CO.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ej(t)});var Bin=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return wOi(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new NDe(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new NDe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Bin.create=(e,t)=>new Bin({innerType:e,typeName:CO.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ej(t)});var J8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.nan){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.nan,received:n.parsedType}),aP}return{status:"valid",value:t.data}}};J8n.create=e=>new J8n({typeName:CO.ZodNaN,...Ej(e)});var Bww=Symbol("zod_brand"),jOi=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},DOi=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?aP:a.status==="dirty"?(r.dirty(),L8n(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?aP:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:CO.ZodPipeline})}},Nin=class extends Aj{_parse(t){let r=this._def.innerType._parse(t),n=i=>(POi(i)&&(i.value=Object.freeze(i.value)),i);return wOi(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Nin.create=(e,t)=>new Nin({innerType:e,typeName:CO.ZodReadonly,...Ej(t)});function zQf(e,t={},r){return e?H5r.create().superRefine((n,i)=>{var a,u;if(!e(n)){let f=typeof t=="function"?t(n):typeof t=="string"?{message:t}:t,d=(u=(a=f.fatal)!==null&&a!==void 0?a:r)!==null&&u!==void 0?u:!0,c=typeof f=="string"?{message:f}:f;i.addIssue({code:"custom",...c,fatal:d})}}):H5r.create()}var Nww={object:Oae.lazycreate},CO;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(CO||(CO={}));var zww=(e,t={message:`Input not instance of ${e.name}`})=>zQf(r=>r instanceof e,t),RQf=W5r.create,FQf=Pin.create,Rww=J8n.create,Fww=win.create,LQf=jin.create,Lww=Din.create,Uww=V8n.create,Vww=Sin.create,Www=Ein.create,Hww=H5r.create,Qww=nMr.create,Jww=LIt.create,Gww=W8n.create,$ww=iMr.create,Kww=Oae.create,Yww=Oae.strictCreate,Xww=Ain.create,Zww=pMa.create,kww=Min.create,ejw=K9t.create,tjw=_Ma.create,rjw=H8n.create,njw=Q8n.create,ijw=hMa.create,ajw=xin.create,ojw=Tin.create,ujw=Cin.create,sjw=qin.create,cjw=Q5r.create,xQf=zDe.create,ljw=I2e.create,fjw=Y9t.create,djw=zDe.createWithPreprocess,pjw=DOi.create,_jw=()=>RQf().optional(),hjw=()=>FQf().optional(),yjw=()=>LQf().optional(),vjw={string:e=>W5r.create({...e,coerce:!0}),number:e=>Pin.create({...e,coerce:!0}),boolean:e=>jin.create({...e,coerce:!0}),bigint:e=>win.create({...e,coerce:!0}),date:e=>Din.create({...e,coerce:!0})},bjw=aP,RDe=Object.freeze({__proto__:null,defaultErrorMap:U8n,setErrorMap:bww,getErrorMap:lMa,makeIssue:fMa,EMPTY_PATH:gww,addIssueToContext:u0,ParseStatus:H$,INVALID:aP,DIRTY:L8n,OK:wk,isAborted:gxu,isDirty:mxu,isValid:POi,isAsync:wOi,get util(){return Sx},get objectUtil(){return bxu},ZodParsedType:C0,getParsedType:V5r,ZodType:Aj,datetimeRegex:BQf,ZodString:W5r,ZodNumber:Pin,ZodBigInt:win,ZodBoolean:jin,ZodDate:Din,ZodSymbol:V8n,ZodUndefined:Sin,ZodNull:Ein,ZodAny:H5r,ZodUnknown:nMr,ZodNever:LIt,ZodVoid:W8n,ZodArray:iMr,ZodObject:Oae,ZodUnion:Ain,ZodDiscriminatedUnion:pMa,ZodIntersection:Min,ZodTuple:K9t,ZodRecord:_Ma,ZodMap:H8n,ZodSet:Q8n,ZodFunction:hMa,ZodLazy:xin,ZodLiteral:Tin,ZodEnum:Cin,ZodNativeEnum:qin,ZodPromise:Q5r,ZodEffects:zDe,ZodTransformer:zDe,ZodOptional:I2e,ZodNullable:Y9t,ZodDefault:Iin,ZodCatch:Bin,ZodNaN:J8n,BRAND:Bww,ZodBranded:jOi,ZodPipeline:DOi,ZodReadonly:Nin,custom:zQf,Schema:Aj,ZodSchema:Aj,late:Nww,get ZodFirstPartyTypeKind(){return CO},coerce:vjw,any:Hww,array:$ww,bigint:Fww,boolean:LQf,date:Lww,discriminatedUnion:Zww,effect:xQf,enum:ujw,function:ijw,instanceof:zww,intersection:kww,lazy:ajw,literal:ojw,map:rjw,nan:Rww,nativeEnum:sjw,never:Jww,null:Www,nullable:fjw,number:FQf,object:Kww,oboolean:yjw,onumber:hjw,optional:ljw,ostring:_jw,pipeline:pjw,preprocess:djw,promise:cjw,record:tjw,set:njw,strictObject:Yww,string:RQf,symbol:Uww,transformer:xQf,tuple:ejw,undefined:Vww,union:Xww,unknown:Qww,void:Gww,NEVER:bjw,ZodIssueCode:vh,quotelessJson:vww,ZodError:NDe});var gjw=RDe.object({lang:RDe.string(),label:RDe.optional(RDe.string()),source:RDe.string()}),Pxu=RDe.array(gjw);var UQf={README_EXT:"x-readme"};function mjw(e){if(!Array.isArray(e))return!1;for(let t of e)if(!lS(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function VQf(e){let t=hh(e,UQf.README_EXT);if(!lS(t))return[];let r=t["code-samples"];if(!mjw(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function WQf(e,t,r){let n=hh(t,kh.EXAMPLES)??[],i=_gi(t,ADe.REDOCLY_CODE_SAMPLES_KEBAB,Pxu,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],u=[..._gi(t,ADe.REDOCLY_CODE_SAMPLES_CAMEL,Pxu,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...i];u.length>0&&n.push({"code-samples":u.map(d=>({name:d.label??d.lang,language:d.lang,code:d.source,install:void 0,docs:void 0}))});let f=VQf(t);return f.length>0&&n.push({"code-samples":f}),n.map(SIt.unknown)}function HQf(e){let t=hh(e,kh.AVAILABILITY);if(t==="ga"||t==="generally-available")return JH.GenerallyAvailable;if(t==="beta"||t==="pre-release")return JH.Beta;if(t==="deprecated")return JH.Deprecated;if(e.deprecated)return JH.Deprecated}function yMa(e){return{url:Ojw({url:e.url,variables:e.variables??{}}),description:e.description,name:Pjw(e),audiences:hh(e,kh.AUDIENCES)}}function Ojw({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,i);return e}function Pjw(e){let t=hh(e,[kh.SERVER_NAME_V1,kh.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function QQf(e){return hh(e,kh.PARAMETER_NAME)}function JQf(e){return hh(e,kh.SDK_VARIABLE)}function vMa({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let f of r){let d=hh(f,kh.IGNORE);if(d!=null&&d){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let c=wy(f)?n.resolveParameterReference(f):f,o=c.required??!1,l=O2e(c),g=[...i,c.name],O=WF(g);x9t({schema:c,logger:n.logger})?.includes(" ")&&n.logger.warn("Parameter example contains a space, which is ambiguous. Consider using enums for multiple examples, or use an encoding if a space is part of the parameter.");let P=c.schema!=null?a1(c.schema,!o,n,g,a,n.namespace,!1,new Set,x9t({schema:c,logger:n.logger})):o?Gp.primitive({nameOverride:void 0,generatedName:O,title:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:x9t({schema:c,logger:n.logger})}),description:void 0,availability:l,groupName:void 0}):Gp.optional({nameOverride:void 0,generatedName:O,title:void 0,value:Gp.primitive({nameOverride:void 0,generatedName:O,title:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:x9t({schema:c,logger:n.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:l,groupName:void 0});if(c.in==="header"&&c.schema!=null&&!wy(c.schema)&&c.schema.default!=null){let M=c.schema.default;typeof M=="string"&&M.length>0&&(P=Gp.literal({nameOverride:void 0,generatedName:O,title:void 0,value:DB.string(M),description:void 0,availability:l,groupName:void 0}))}let j={name:c.name,schema:P,description:c.description,parameterNameOverride:QQf(c),availability:l,source:a};c.in==="query"?u.queryParameters.push(j):c.in==="path"?u.pathParameters.push({...j,variableReference:JQf(c)}):c.in==="header"?!wjw.has(c.name)&&!n.authHeaders.has(c.name)?u.headers.push({...j,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return u}var wjw=new Set(["User-Agent","Content-Length","Content-Type","X-Forwarded-For","Cookie","Origin","Content-Disposition","X-Ping-Custom-Domain"]);function GQf(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r,schema:i??{},examples:wxu(n,t)}}}function G8n(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r.includes("*")?void 0:r,schema:i??{},examples:wxu(n,t)}}}function $Qf(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:wxu(n,t)}}}function wxu(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=hh(e,ADe.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,a])=>({name:a.summary??i,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,a])=>{let u=wy(a)?t.resolveExampleReference(a):a;return{name:u.summary??i,value:u.value,description:u.description}})),r}function jjw(e){for(let[t,r]of Object.entries(e.content))if(D4.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function Djw(e){for(let t in e.content)if(D4.parse(t)?.isOctetStream())return!0;return!1}function Sjw(e,t){let r=wy(e)?jxu(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!wy(i)&&i.type==="string"&&i.format==="binary")!=null}function $8n({requestBody:e,document:t,context:r,requestBreadcrumbs:n,source:i,namespace:a}){let u=wy(e)?r.resolveRequestBodyReference(e):e,f=jjw(u),d=f?.schema,c=f?.encoding,o=G8n(u.content,r);if(Djw(u))return m2e.octetStream({description:u.description,source:i});if(d!=null&&o==null||d!=null&&Sjw(d,t)){let g=wy(d)?jxu(d,t):{id:void 0,schema:d},O=a1(g.schema,!1,r,n,i,a),P=[];if(O.type==="object")for(let j of O.properties){if(j.schema.type==="primitive"&&j.schema.schema.type==="string"&&j.schema.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!1,isArray:!1}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="optional"&&j.schema.value.type==="primitive"&&j.schema.value.schema.type==="string"&&j.schema.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!0,isArray:!1}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="array"&&j.schema.value.type==="primitive"&&j.schema.value.schema.type==="string"&&j.schema.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!1,isArray:!0}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="optional"&&j.schema.value.type==="array"&&j.schema.value.value.type==="primitive"&&j.schema.value.value.schema.type==="string"&&j.schema.value.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!0,isArray:!0}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}P.push({key:j.key,schema:g2e.json(j.schema),description:void 0,contentType:c?.[j.key]?.contentType})}return m2e.multipart({name:wy(d)&&r.getNumberOfOccurrencesForRef(d)===1?g.id:void 0,description:g.schema.description,properties:P,source:i})}if(o==null)return;let l=a1(o.schema,!1,r,n,i,a,!0);return m2e.json({description:void 0,schema:l,contentType:o.contentType,fullExamples:o.examples,additionalProperties:!wy(o.schema)&&yNn(o.schema.additionalProperties),source:i})}function jxu(e,t){if(!e.$ref.startsWith(xnn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Yzr(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return wy(n)?jxu(n,t):{id:r,schema:n}}var Dxu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},KQf=new Set(Object.values(Dxu));var Ejw=["200","201","202","204"];function XQf({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let f=Ajw({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,c;for(let o of i!=null?[i]:Ejw){let l=t[o];l!=null&&(d=!0,c==null&&(c=YQf({operationContext:e,response:l,context:r,responseBreadcrumbs:n,streamFormat:a,source:u,namespace:r.namespace})))}if(c==null&&!d&&t.default!=null&&(c=YQf({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:a,source:u,namespace:r.namespace})),c!=null)switch(c.type){case"json":return{value:c,errors:f};case"streamingJson":case"streamingSse":return{value:c,errors:f};case"file":case"text":case"streamingText":return{value:c,errors:f};default:xc(c)}return{value:void 0,errors:f}}function YQf({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:a,namespace:u}){let f=wy(r)?n.resolveResponseReference(r):r;if(f.content!=null&&Object.entries(f.content).find(([l,g])=>{if(g.schema==null)return!1;let O=wy(g.schema)?n.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return SB.file({description:f.description,source:a});let d=GQf(f.content??{},n);if(d!=null&&t!=null)switch(t){case"json":return SB.streamingJson({description:f.description,responseProperty:hh(e.operation,kh.RESPONSE_PROPERTY),fullExamples:d.examples,schema:a1(d.schema,!1,n,i,a,u),source:a});case"sse":return SB.streamingSse({description:f.description,responseProperty:void 0,schema:YC(a1(d.schema,!1,n,i,a,u)),source:a})}let c=G8n(f.content??{},n);if(c!=null){if(t!=null)switch(t){case"json":return SB.streamingJson({description:f.description,responseProperty:void 0,fullExamples:c.examples,schema:a1(c.schema,!1,n,i,a,u),source:a});case"sse":return SB.streamingSse({description:f.description,responseProperty:void 0,schema:YC(a1(c.schema,!1,n,i,a,u)),source:a})}return SB.json({description:f.description,schema:a1(c.schema,!1,n,i,a,u),responseProperty:hh(e.operation,kh.RESPONSE_PROPERTY),fullExamples:c.examples,source:a})}for(let[o,l]of Object.entries(f.content??{})){let g=D4.parse(o);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo())return SB.file({description:f.description,source:a});if(g.isPlainText()){let O=l.schema;if(O==null)return SB.text({description:f.description,source:a});let P=wy(O)?n.resolveSchemaReference(O):O;return P.type==="string"&&P.format==="byte"?SB.file({description:f.description,source:a}):SB.text({description:f.description,source:a})}}}}function Ajw({responses:e,context:t,source:r,namespace:n}){let i={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let f=parseInt(a);if(f<400||f>600)continue;let d=wy(u)?t.resolveResponseReference(u):u,c=$Qf(d.content??{},t),o=Dxu[f];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}i[f]={statusCode:f,nameOverride:void 0,generatedName:o,description:d.description,schema:a1(c?.schema??{},!1,t,[o,"Body"],r,n),fullExamples:c?.examples,source:r}}return i}function aMr({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:a}){let{document:u,operation:f,path:d,method:c,baseBreadcrumbs:o,sdkMethodName:l}=e,g=hh(f,kh.IDEMPOTENT),O=hh(f,[kh.REQUEST_NAME_V1,kh.REQUEST_NAME_V2]),P=[...o,"Request"],j=vMa({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:P,path:d,httpMethod:c,source:a}),M=f.requestBody!=null?$8n({requestBody:f.requestBody,document:u,context:new R8n({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:P,source:a,namespace:t.namespace}):void 0;(j.queryParameters.length>0||j.headers.length>0)&&M!=null&&M.type==="json"&&M.schema.type!=="object"&&f.requestBody!=null?M=$8n({requestBody:f.requestBody,document:u,context:t,requestBreadcrumbs:[...P,"Body"],source:a,namespace:t.namespace}):f.requestBody!=null&&(M=$8n({requestBody:f.requestBody,document:u,context:t,requestBreadcrumbs:[...P],source:a,namespace:t.namespace}));let q=[...o,"Response"],B=XQf({operationContext:e,streamFormat:i,responses:f.responses,context:t,responseBreadcrumbs:q,responseStatusCode:r,source:a}),I=HQf(f),C=WQf(e,f,t),F=hh(f,kh.SERVER_NAME_V2);return{summary:f.summary,internal:hh(f,ADe.INTERNAL),idempotent:g,audiences:hh(f,kh.AUDIENCES)??[],operationId:f.operationId!=null&&n!=null?f.operationId+"_"+n:f.operationId,tags:t.resolveTagsToTagIds(f.tags),namespace:t.namespace,sdkName:l,pathParameters:j.pathParameters,queryParameters:j.queryParameters,headers:j.headers,requestNameOverride:O??void 0,generatedRequestName:WF(P),request:M,response:B.value,errors:B.errors,server:F!=null?[{name:F,url:void 0,audiences:void 0}]:(f.servers??[]).map(K=>yMa(K)),description:f.description,authed:Mjw(f,u),availability:I,method:c,path:d,examples:C,pagination:e.pagination,source:a}}function Mjw(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function kQf({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:a,operationParameters:u}=e,f=r.discriminant.name,d=r.discriminant.value,c=r["response-status-code"],o=ZQf({context:t,headerToIgnore:f,parameters:a}),l=ZQf({context:t,headerToIgnore:f,parameters:u}),g=aMr({operationContext:{...e,pathItemParameters:o,operationParameters:l,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([P])=>parseInt(P)!==c))}},context:t,streamFormat:void 0,source:n}),O=aMr({operationContext:{...e,pathItemParameters:o,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:c,streamFormat:void 0,source:n});return O.headers.push({name:f,schema:Gp.literal({nameOverride:void 0,generatedName:WF([f]),title:void 0,description:void 0,availability:void 0,value:DB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n}),{sync:g,async:O}}function ZQf({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=wy(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var Sxu="stream";function nJf({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:aMr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let n=eJf({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let c=Yzr(n.schemaReference);c!=null&&t.excludeSchema(c)}let i=tJf({operation:e.operation,response:r.responseStream}),a=aMr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Sxu}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Sxu]},context:t,streamFormat:r.format,suffix:Sxu,source:t.source});a.examples=a.examples.filter(c=>rJf(c,t)!==!1);let u=eJf({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),f=tJf({operation:e.operation,response:r.response}),d=aMr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:f}},context:t,source:t.source});return d.examples=d.examples.filter(c=>rJf(c,t)!==!0),{streaming:a,nonStreaming:d}}default:xc(r)}}function eJf({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=wy(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=G8n(i.content,e);if(a==null)return;let u=wy(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let f=u.properties?.[r.streamConditionProperty];f!=null&&wy(f)&&(f=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...f??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[D4.APPLICATION_JSON]:{schema:d}}},schemaReference:wy(a.schema)?a.schema:void 0}}function tJf({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[D4.APPLICATION_JSON]:{schema:t}}}}}function rJf(e,t){return e._visit({unknown:r=>{let n=zie.serialization.ExampleEndpointCallSchema.parse(r);if(!n.ok){t.logger.error("Failed to parse example",n.errors.toString());return}if(n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}function iJf({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:a,method:u,baseBreadcrumbs:f,sdkMethodName:d}=t,c=[...f,"Payload"],o=vMa({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:c,path:a,httpMethod:u,source:r});if(i.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let l=$8n({requestBody:i.requestBody,document:n,context:e,requestBreadcrumbs:[...f,"Payload"],source:r,namespace:e.namespace});if(l==null||l.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(i.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:i.summary,sdkName:d,namespace:e.namespace,method:u,operationId:i.operationId,tags:e.resolveTagsToTagIds(i.tags),headers:o.headers,generatedPayloadName:WF(c),payload:l.schema,description:i.description,examples:xjw(l.fullExamples),source:r}}function xjw(e){if(e==null)return[];let t=[];for(let r of e){let n=Xzr(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function Exu({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=hh(r,kh.IGNORE);if(i!=null&&i){e.logger.info(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=Tjw(r,e),u=wQf(e.document,r),f={...t,sdkMethodName:a,baseBreadcrumbs:Cjw({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path}),operation:r,operationParameters:r.parameters??[],pagination:u};if(n){let l=iJf({context:e,operationContext:f,source:e.source});return l!=null?{type:"webhook",value:l}:void 0}let d=OQf(r);if(d!=null){let l=nJf({context:e,operationContext:f,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let c=gQf(r);if(c!=null){let l=kQf({context:e,operationContext:f,asyncExtension:c,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:aMr({context:e,operationContext:f,streamFormat:void 0,source:e.source})}}function Tjw(e,t){let r=hh(e,kh.SDK_METHOD_NAME),n=hh(e,kh.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function Cjw({sdkMethodName:e,operation:t,httpMethod:r,path:n}){let i=[];if(e!=null){if(e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&i.push(typeof a=="string"?a:a.name)}i.push(e.methodName)}else t.operationId!=null?i.push(t.operationId):i.push(_A(`${r}_${n.split("/").join("_")}`));return i}function aJf(e,t,r,n){let i=[],a=uJf(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let f of a){let d=qjw({operation:f.operation}),c=Exu({context:n,pathItemContext:{...u,method:f.method},operation:f.operation,convertToWebhook:d});c!=null&&i.push(c)}return i}function oJf(e,t,r,n){let i=[],a=uJf(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let f of a){let d=Exu({context:n,pathItemContext:{...u,method:f.method},operation:f.operation,convertToWebhook:!0});d!=null&&i.push(d)}return i}function uJf(e){let t=[];return e.get!=null&&t.push({method:C$.Get,operation:e.get}),e.post!=null&&t.push({method:C$.Post,operation:e.post}),e.put!=null&&t.push({method:C$.Put,operation:e.put}),e.delete!=null&&t.push({method:C$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:C$.Patch,operation:e.patch}),t}function qjw({operation:e}){return hh(e,[kh.WEBHOOK])??!1}function sJf(e){let t=hh(e,kh.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=hh(e,kh.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function cJf(e){return hh(e,kh.FERN_BASIC_AUTH)}function Axu(e,t){if(wy(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return Ijw(e,t)}function Ijw(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=hh(e,ADe.BEARER_FORMAT),n=hh(e,kh.FERN_HEADER_AUTH);return PU.header({headerName:e.name,prefix:r!=null?"Bearer":n?.prefix,headerVariableName:n?.name??hh(e,kh.HEADER_VARIABLE_NAME),headerEnvVar:n?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=hh(e,kh.FERN_BEARER_TOKEN);return PU.bearer({tokenVariableName:r?.name??hh(e,kh.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=cJf(e),n=sJf(e);return PU.basic({usernameVariableName:r?.username?.name??n.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??n.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return PU.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return PU.oauth({scopesEnum:Bjw(e,t)})}throw new Error(`Failed to convert security scheme ${JSON.stringify(e)}`)}function Bjw(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Kzr({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t}),i=YC(n);if(i.type==="enum")return i}}function lJf(e){return hh(e,kh.BASE_PATH)}var Njw=RDe.record(RDe.string(),RDe.object({summary:RDe.string().optional(),description:RDe.string().optional()}));function fJf({document:e,context:t}){return _gi(e,kh.GROUPS,Njw,t.logger)}function dJf({context:e,document:t}){return hh(t,kh.FERN_VERSION)??void 0}function pJf(e){let t=hh(e,kh.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?hgi({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function _Jf(e){let t=hh(e,kh.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?hgi({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function hJf(e){let t=hh(e,kh.SDK_VARIABLES);return t==null?{}:Object.fromEntries(Object.entries(t).map(([r,n])=>{if(n.type==="string")return[r,{nameOverride:void 0,generatedName:WF([r]),title:n.title,schema:jD.string({default:ONn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${r} has unsupported schema ${JSON.stringify(n)}`)}))}var zjw="webhooks";function yJf(e){return hh(e,zjw)??{}}var bMa=class extends z8n{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discrminatedUnionReferences={};discrminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u})}getDummy(){return new R8n({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discrminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discrminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discrminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discrminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discrminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discrminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function vJf(e){return hh(e,kh.RESOLUTIONS)}function bJf({openapi:e}){let t=vJf(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let a of n.resolutions)e=Rjw({openapi:e,schemaReference:a,schemaName:n.name}),e=gJf({openapi:e,replaceReference:a,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(u=>[i,u]))}}return e}function Rjw({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(a=>a.replace("~1","/")),i=e;for(let a of n){let u=i[a];if(u==null)return e;i=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function gJf({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(d=>t.startsWith(d)).sort((d,c)=>c.length-d.length)[0];if(i!=null){let d=n[i];if(d!=null){let c=r.replace(i,d);return gJf({openapi:e,replaceReference:t,schemaReference:c,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replace("~1","/")),u=e;for(let d of a.slice(0,-1)){let c=u[d];if(c==null)return e;u=c}let f=a[a.length-1];return f==null||(u[f]={$ref:r}),e}function gMa({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=bJf({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([ee,J])=>Axu(J,n)==null?[]:[ee,Axu(J,n)])),u=new Set(...Object.entries(a).map(([ee,J])=>J.type==="basic"||J.type==="bearer"?"Authorization":J.type==="header"?J.headerName:null)),f=new bMa({document:e,taskContext:t,authHeaders:u,options:r,source:n,namespace:i}),d=hJf(e),c=pJf(e),o=_Jf(e),l=r.audiences??[],g=[],O=[];Object.entries(e.paths??{}).forEach(([ee,J])=>{if(J==null)return;t.logger.debug(`Converting path ${ee}`);let G=aJf(ee,J,e,f);for(let te of G){let Ye=mJf({operation:te});if(!(l.length>0&&!l.some(Re=>Ye.includes(Re))))switch(te.type){case"async":g.push(te.sync),g.push(te.async);break;case"http":g.push(te.value);break;case"streaming":g.push(te.streaming),te.nonStreaming&&g.push(te.nonStreaming);break;case"webhook":O.push(te.value);break;default:xc(te)}}}),Object.entries(yJf(e)).forEach(([ee,J])=>{if(J==null)return;t.logger.debug(`Converting path ${ee}`);let G=oJf(ee,J,e,f);for(let te of G){let Ye=mJf({operation:te});l.length>0&&!l.some(Re=>Ye.includes(Re))||O.push(te.value)}});let P=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([ee,J])=>{if(!wy(J)){let G=hh(J,kh.IGNORE);if(G!=null&&G)return[];if(KQf.has(ee))return[ee,a1({...J,"x-fern-type-name":`${ee}Body`},!1,f,[ee],n,i)]}return[ee,a1(J,!1,f,[ee],n,i)]}).filter(ee=>ee.length>0)),j=Fjw(P,f,n),M=Ljw(j,f),q={};for(let[ee,J]of Object.entries(M)){let G=YC(J);f.isSchemaExcluded(ee)||(q[ee]=G,t.logger.debug(`Converted schema ${ee}`))}let B=new Zzr(M),I=new Jja(M,f.logger),C=g.map(ee=>{let J=ee.examples,G=J;if(!r.disableExamples&&(J.length===0||J.every(ggi))){let Re=I.buildEndpointExample(ee);Re.length>0&&(G=[...Re,...J.filter(wt=>!ggi(wt))])}let te=ee.request,Ye=ee.response;return{...ee,request:te?.type==="json"?{...te,schema:YC(te.schema)}:te,response:Ye?.type==="json"?{...Ye,schema:YC(Ye.schema)}:Ye,queryParameters:ee.queryParameters.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,availability:Re.availability,source:Re.source})),pathParameters:ee.pathParameters.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,variableReference:Re.variableReference,availability:Re.availability,source:Re.source})),headers:ee.headers.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,env:Re.env,availability:Re.availability,source:Re.source})),examples:G,errors:by(ee.errors,Re=>{let wt=Re.fullExamples?.map(Ct=>{let Wt=Xzr(Ct.value);if(Wt!=null)return{name:Ct.name,description:Ct.description,example:Wt}}).filter($M);if(wt?.length===0){let Ct=B.buildExample({schema:Re.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Ct!=null&&wt.push({name:void 0,description:void 0,example:Ct})}return{generatedName:Re.generatedName,nameOverride:Re.nameOverride,schema:YC(Re.schema),description:Re.description,source:Re.source,examples:wt}})}}),F=fJf({document:e,context:f});return{apiVersion:dJf({context:f,document:e}),basePath:lJf(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(F??{}).map(([ee,J])=>[ee,{summary:J.summary??void 0,description:J.description??void 0}])),servers:(e.servers??[]).map(ee=>yMa(ee)),tags:{tagsById:Object.fromEntries((e.tags??[]).map(ee=>[ee.name,{id:ee.name,description:ee.description}])),orderedTagIds:e.tags?.map(ee=>ee.name)},endpoints:C,webhooks:O,channel:[],groupedSchemas:Wja(i,q),securitySchemes:a,hasEndpointsMarkedInternal:C.some(ee=>ee.internal),nonRequestReferencedSchemas:f.getReferencedSchemas(),variables:d,globalHeaders:c,idempotencyHeaders:o}}function Fjw(e,t,r){let n={};for(let[i,a]of Object.entries(e)){if(a.type!=="object"){n[i]=a;continue}let u={$ref:`#/components/schemas/${i}`},f=t.getReferencesFromDiscriminatedUnion(u);if(f==null){n[i]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!f.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!f.discriminants.has(o.propertyKey)),source:r};n[i]=d;let c=OJf({schema:a,schemas:e});for(let o of[...new Set(c)]){let l=n[o]??e[o];l==null||l.type!=="object"||(n[o]={...l,type:"object",properties:l.properties.filter(g=>!f.discriminants.has(g.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(g=>!f.discriminants.has(g.propertyKey))})}}return n}function Ljw(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let a={$ref:`#/components/schemas/${n}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[n]=i;continue}let f=[];for(let c of i.properties)if(u.discriminants.has(c.key)){let o=u.discriminants.get(c.key);o!=null&&f.push({...c,schema:Gp.literal({nameOverride:void 0,generatedName:WF([i.generatedName,o]),title:void 0,value:DB.string(o),groupName:void 0,description:void 0,availability:i.availability})})}else f.push(c);let d={...i,type:"object",properties:f};r[n]=d}return r}function OJf({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...OJf({schema:i,schemas:t}))}return r}function mJf({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:xc(e)}return t}async function wJf({openApi:e,taskContext:t,options:r,source:n,namespace:i}){let a=await(0,PJf.convertObj)(e,{});return gMa({openApi:a.openapi,taskContext:t,options:r,source:n,namespace:i})}var zin={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,cooerceEnumsToLiterals:!0};async function Rin({absoluteFilePathToWorkspace:e,specs:t,taskContext:r,optionOverrides:n}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channel:[],groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let a of t){let u=(await(0,xxu.readFile)(a.absoluteFilepath)).toString(),f=jq(e,a.source.file);a.source.relativePathToDependency!=null&&(f=yf(a.source.relativePathToDependency,f));let d=a.source.type==="protobuf"?NAr.protobuf({file:f}):NAr.openapi({file:f});if(u.includes("openapi")||u.includes("swagger")){let c=await lUf({absolutePathToOpenAPI:a.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:a.absoluteFilepathToOverrides});if(Wjw(c)){let o=gMa({openApi:c,taskContext:r,options:Mxu({specSettings:a.settings,overrides:n}),source:d,namespace:a.namespace});i=jJf(i,o)}else if(Hjw(c)){let o=await wJf({openApi:c,taskContext:r,options:Mxu({specSettings:a.settings}),source:d,namespace:a.namespace});i=jJf(i,o)}}else if(u.includes("asyncapi")){let c=await Vjw({absoluteFilePathToAsyncAPI:a.absoluteFilepath,context:r,absoluteFilePathToAsyncAPIOverrides:a.absoluteFilepathToOverrides}),o=O3f({document:c,taskContext:r,options:Mxu({specSettings:a.settings}),source:d,asyncApiOptions:Ujw({specSettings:a.settings}),namespace:a.namespace});o.channel!=null&&i.channel.push(o.channel),o.groupedSchemas!=null&&(i.groupedSchemas=DJf(i.groupedSchemas,o.groupedSchemas)),o.basePath!=null&&(i.basePath=o.basePath)}else r.failAndThrow(`${a.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}function Mxu({specSettings:e,overrides:t}){return{disableExamples:t?.disableExamples??zin.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.shouldUseUndiscriminatedUnionsWithLiterals??zin.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.shouldUseTitleAsName??zin.useTitlesAsName,audiences:t?.audiences??e?.audiences??zin.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??zin.optionalAdditionalProperties,cooerceEnumsToLiterals:t?.cooerceEnumsToLiterals??e?.cooerceEnumsToLiterals??zin.cooerceEnumsToLiterals}}function Ujw({specSettings:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??J4f.naming}}function jJf(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channel:[...e.channel,...t.channel],groupedSchemas:DJf(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function DJf(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,n]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...n}:e.namespacedSchemas[r]=n;return e}async function Vjw({absoluteFilePathToAsyncAPI:e,absoluteFilePathToAsyncAPIOverrides:t,context:r}){let n=(await(0,xxu.readFile)(e)).toString(),i=await d0.load(n);return t!=null?await rAa({absoluteFilepathToOverrides:t,context:r,data:i}):i}function Wjw(e){return e.openapi!=null}function Hjw(e){return e.swagger!=null}function OMa({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Txu({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let a=PC(i.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!i.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let u={type:a};return i.allowMultiple&&(u["allow-multiple"]=!0),e.description!=null&&(u.docs=e.description),e.parameterNameOverride!=null&&(u.name=e.parameterNameOverride),e.availability!=null&&(u.availability=I3(e.availability)),u}function Txu({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,groupName:void 0}),context:t,declarationFile:Ms.of($A),fileContainingReference:r,namespace:n}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undisciminated"){let a=[];for(let[u,f]of Object.entries(i.value.schemas))f.type==="literal"&&f.value.type==="string"&&(gNn.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:ygi(f.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(i.value.schemas.length===2){let[u,f]=i.value.schemas;if(u!=null&&f!=null&&mMa({array:u,primitive:f}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:f,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(u!=null&&f!=null&&mMa({array:u,primitive:f}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}}for(let[u,f]of Object.entries(i.value.schemas))return Txu({schema:f,context:t,fileContainingReference:r,namespace:n})}else if(i.type==="object")return}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let i=t.getSchema(e.value.schema,n);if(i==null)return;if(i.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,declarationFile:Ms.of($A),namespace:n}),allowMultiple:!0}}if(e.value.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undisciminated"){let i=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(gNn.test(u.value.value)?i.push(u.value.value):i.push({value:u.value.value,name:ygi(u.value.value)}));if(i.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:i}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&mMa({array:a,primitive:u}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(a!=null&&u!=null&&mMa({array:u,primitive:a}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return Txu({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return;return{value:Z1({schema:e,context:t,fileContainingReference:r,namespace:n}),allowMultiple:!1}}return e.type==="array"?{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}:{value:Z1({schema:e,context:t,fileContainingReference:r,namespace:n}),allowMultiple:!1}}function mMa({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function SJf({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=Qjw(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=Jjw({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=J5r(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function Qjw(e){let t={};return e.forEach(r=>{let n=J5r(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function Jjw({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=J5r(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function J5r(e){switch(e.type){case"primitive":return EJf(e.value);case"object":return AJf(e.properties);case"array":return Gjw(e.value);case"map":return $jw(e.value);case"oneOf":return Kjw(e.value);case"enum":return e.value;case"literal":return Yjw(e.value);case"unknown":return J5r(e.value);default:xc(e)}}function EJf(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:xc(e)}}function AJf(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,J5r(r)]))}function Gjw(e){return e.map(t=>J5r(t))}function $jw(e){return Object.fromEntries(e.map(t=>[EJf(t.key),J5r(t.value)]))}function Kjw(e){return e.type==="discriminated"?AJf(e.value):J5r(e.value)}function Yjw(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:xc(e)}}function oMr(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function PMa(e,t){return t??(e?.groupName!=null?oMr(e.groupName):void 0)}function MJf({channel:e,context:t,declarationFile:r}){let n={path:e.path,auth:!1};e.summary!=null&&(n["display-name"]=e.summary);let i=oMr(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=Bja({pathParameter:d,context:t,fileContainingReference:r,namespace:i});Object.keys(a).length>0&&(n["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let c=OMa({queryParameter:d,context:t,fileContainingReference:r,namespace:i});c!=null&&(u[d.name]=c)}Object.keys(u).length>0&&(n["query-parameters"]=u);let f={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let c=M9t({header:d,context:t,fileContainingReference:r,namespace:i});f[d.name]=c}Object.keys(f).length>0&&(n.headers=f),t.builder.addChannel(r,{channel:n}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:Z1({schema:e.subscribe,context:t,fileContainingReference:r,namespace:i})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:Z1({schema:e.publish,context:t,fileContainingReference:r,namespace:i})}});for(let d of e.examples){let c=SJf({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:c})}}var xJf="Production",TJf="Default";function CJf(e){return Object.entries(e).reduce((t,[r,n])=>(BIn(n)?Object.entries(n.urls).forEach(([i,a])=>{t[i]=a}):t[r]=typeof n=="string"?n:n.url,t),{})}function qJf(e){if(e.environmentOverrides!=null){for(let[f,d]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:f,schema:d});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let f of e.ir.servers){let d=f.audiences?{url:f.url,audiences:f.audiences}:f.url;if(f.name==null){r.push(d);continue}t[f.name]=d}let n={},i=[];for(let f of e.ir.endpoints)for(let d of f.server){if(d.url==null)continue;let c=d.audiences?{url:d.url,audiences:d.audiences}:d.url;if(d.name==null){i.push(c);continue}n[d.name]=c}let a=Object.keys(t).length,u=Object.keys(n).length;if(a===0&&u===0){let f=e.ir.servers[0]?.url,d=e.ir.servers[0]?.audiences;f!=null&&(e.builder.addEnvironment({name:TJf,schema:d?{url:f,audiences:d}:f}),e.builder.setDefaultEnvironment(TJf))}else if(a>0&&u===0){let f=0;r.length>0&&e.logger.error(`Skipping servers ${r.map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);for(let[d,c]of Object.entries(t))f===0&&e.builder.setDefaultEnvironment(d),e.builder.addEnvironment({name:d,schema:c}),f+=1}else if(u>0){(r.length>0||i.length>0)&&e.logger.error(`Skipping servers ${[...r,...i].map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);let f=Object.entries(t)[0];if(f!=null){let[d,c]=f;e.setDefaultServerName(d)}e.builder.addEnvironment({name:xJf,schema:{urls:{...CJf(t),...CJf(n)}}}),e.builder.setDefaultEnvironment(xJf)}}function wMa(e){return PC(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var Cxu=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},Xjw=.75,Zjw=new Set("authorization");function IJf(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let i="optional<string>";if(n.name==null&&n.env==null&&typeof n.schema=="string")i=n.schema;else if(n!=null){let a=n.schema?_Nn(n.schema):void 0,u=a!=null?oMr(a):void 0,f=Ms.of("api.yml");i={name:n.name,env:n.env,type:n.schema!=null?PC(Z1({schema:n.schema,context:e,fileContainingReference:u?yf(Ms.of(_A(u)),f):f,namespace:u}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:i})}if(e.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let a of i.headers){if(Zjw.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let f=t[a.name],d=M9t({header:{...a,schema:f?.schema??a.schema,name:f?.name??a.name},fileContainingReference:Ms.of(m5),context:e,namespace:void 0});u=new Cxu(d),r[a.name]=u}u.increment()}let n=e.ir.endpoints.length*Xjw;for(let[i,a]of Object.entries(r)){let u=t[i],f=a.count===e.ir.endpoints.length,d=a.count>=n;u==null&&(f?e.builder.addGlobalHeader({name:i,schema:a.schema}):d&&e.builder.addGlobalHeader({name:i,schema:wMa(a.schema)}))}}}function BJf(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?_Nn(t.schema):void 0,n=r!=null?oMr(r):void 0,i=M9t({header:{...t,schema:t.schema??gb.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:jD.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Ms.of(m5),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:wMa(i)})}}function jk(e){switch(e.type){case"primitive":return zJf(e.value);case"object":return RJf(e.properties);case"array":return FJf(e.value);case"map":return kjw(e.value);case"oneOf":return eDw(e.value);case"enum":return e.value;case"literal":return tDw(e.value);case"unknown":return jk(e.value);default:xc(e)}}function NJf(e){switch(e.type){case"withStreaming":return{stream:FJf(e.value)};case"withoutStreaming":return{body:jk(e.value)};default:xc(e)}}function zJf(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:xc(e)}}function RJf(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,jk(r)]))}function FJf(e){return e.map(t=>jk(t))}function kjw(e){return Object.fromEntries(e.map(t=>[zJf(t.key),jk(t.value)]))}function eDw(e){return e.type==="discriminated"?RJf(e.value):jk(e.value)}function tDw(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:xc(e)}}function LJf({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=rDw(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=nDw(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=iDw({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=jk(e.request)),e.response!=null&&(r.response=NJf(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(n=>n.type==="language"?{name:n.name??void 0,docs:n.description??void 0,language:n.language,code:n.code,install:n.install??void 0}:{name:n.name??void 0,docs:n.description??void 0,sdk:n.sdk,code:n.code}).filter($M)),r)}function rDw(e){let t={};return e.forEach(r=>{let n=jk(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function nDw(e){let t={};return e.forEach(r=>{let n=jk(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function iDw({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=jk(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function UJf(e){return C$._visit(e,{get:()=>zie.HttpMethodSchema.Get,post:()=>zie.HttpMethodSchema.Post,put:()=>zie.HttpMethodSchema.Put,patch:()=>zie.HttpMethodSchema.Patch,delete:()=>zie.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unkown http method is unsupported")}})}function VJf({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:n}=r.ir,i=[],a=new Set,u=e.path,f=PMa(e.sdkName,e.namespace),d={};for(let j of e.pathParameters)j.parameterNameOverride&&(u=u.replace(j.name,j.parameterNameOverride)),d[j.parameterNameOverride??j.name]=Bja({pathParameter:j,context:r,fileContainingReference:t,namespace:f}),a.add(j.name);let c={};for(let j of e.queryParameters){let M=OMa({queryParameter:j,context:r,fileContainingReference:t,namespace:f});M!=null&&(c[j.name]=M,a.add(j.name))}let o;e.pagination!=null&&(e.pagination.type==="cursor"?o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results}:o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage});let l={path:u,method:UJf(e.method),auth:e.authed,docs:e.description??void 0,pagination:o};Object.keys(d).length>0&&(l["path-parameters"]=d),e.summary!=null&&(l["display-name"]=e.summary);let g={},O=r.builder.getGlobalHeaderNames(),P=e.headers.filter(j=>!O.has(j.name));for(let j of P){let M=M9t({header:j,context:r,fileContainingReference:t,namespace:f});g[j.name]=M,a.add(typeof M=="string"?j.name:M.name??j.name)}if(e.request!=null){let j=oDw({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,queryParameters:Object.keys(c).length>0?c:void 0,nonRequestReferencedSchemas:Array.from(n),headers:Object.keys(g).length>0?g:void 0,usedNames:a,namespace:f});l.request=j.value,i=[...i,...j.schemaIdsToExclude??[]]}else{let j=Object.keys(c).length>0,M=Object.keys(g).length>0,q={};(j||M)&&(q.name=e.requestNameOverride??e.generatedRequestName),j&&(q["query-parameters"]=c),M&&(q.headers=g),Object.keys(q).length>0&&(l.request=q)}if(e.response!=null&&e.response._visit({json:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l.response={docs:j.description??void 0,type:PC(M)},j.responseProperty!=null&&(l.response.property=j.responseProperty)},streamingJson:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l["response-stream"]={docs:j.description??void 0,type:PC(M),format:"json"}},streamingSse:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l["response-stream"]={docs:j.description??void 0,type:PC(M),format:"sse"}},file:j=>{l.response={docs:j.description??void 0,type:"file"}},streamingText:j=>{l["response-stream"]={docs:j.description??void 0,type:"text"}},text:j=>{l.response={docs:j.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let j=r.getDefaultServerName(),M=e.server[0];M==null?j!=null&&(l.url=j):l.url=M.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=I3(e.availability)),Object.entries(e.errors).forEach(([j,M])=>{let q=M.generatedName,B=Ms.of($A);r.builder.enableUniqueErrorsPerEndpoint&&(q=`${e.generatedRequestName}${M.generatedName}`,M.schema!=null&&(M.schema.type!=="reference"&&M.schema.type!=="oneOf"?M.schema.generatedName=`${e.generatedRequestName}${M.schema.generatedName}`:M.schema.type==="oneOf"&&(M.schema.value.generatedName=`${e.generatedRequestName}${M.schema.value.generatedName}`)));let I={"status-code":parseInt(j)},C=R4f({location:WJf,namespaceOverride:f});if(M.schema!=null){let ee=Z1({schema:M.schema,context:r,fileContainingReference:C,declarationFile:C,namespace:f});I.type=PC(ee),I.docs=M.description}r.builder.addError(C,{name:q,schema:r.isErrorUnknownSchema(parseInt(j))?{...I,type:"unknown"}:I}),l.errors==null&&(l.errors=[]);let F=r.builder.addImport({file:t,fileToImport:C});l.errors.push(F!=null?`${F}.${q}`:q),I.type!=null&&M.examples?.forEach(ee=>{let J={value:jk(ee.example),name:ee.name,docs:ee.description};r.builder.addErrorExample(C,{name:q,example:J})})}),e.examples.length>0&&(l.examples=aDw({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[qxu,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:i}}function aDw({endpointExamples:e,context:t}){return e.map(r=>{try{return LJf({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function oDw({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:a,queryParameters:u,nonRequestReferencedSchemas:f,headers:d,usedNames:c,namespace:o}){if(n.type==="json"){let l=n.schema.type==="reference"?n.schema.schema:void 0,g=n.schema.type==="reference"?r.getSchema(n.schema.schema,o):n.schema;if(g?.type!=="object"||l!=null&&f.includes(l)){let q=Z1({schema:n.schema,fileContainingReference:t,context:r,namespace:o}),B={schemaIdsToExclude:[],value:{body:q}},I=Object.keys(u??{}).length>0,C=Object.keys(d??{}).length>0;return I&&(B.value["query-parameters"]=u),C&&(B.value.headers=d),(I||C)&&(B.value.name=i??a),n.contentType!=null&&(B.value["content-type"]=n.contentType),n.description!=null&&(B.value.docs=n.description),B}let O=Object.fromEntries(g.properties.filter(q=>q.readonly==null?!0:!((e.method==="POST"||e.method==="PUT")&&q.readonly)).map(q=>{let B=Z1({schema:q.schema,fileContainingReference:t,context:r,namespace:o}),I=q.nameOverride??q.key,C=I3(q.availability);if(!c.has(I)&&q.audiences.length<=0)return c.add(I),q.nameOverride!=null?[q.key,{type:PC(B),docs:dgi(B),name:q.nameOverride,availability:C}]:[q.key,C?{...typeof B=="string"?{type:B}:B,availability:C}:B];let F={type:PC(B),docs:dgi(B)};return c.has(I)&&(F.name=q.generatedName),q.audiences.length>0&&(F.audiences=q.audiences),C!=null&&(F.availability=C),c.add(I),[q.key,F]})),P=g.allOf.map(q=>{let B=Z1({schema:gb.reference(q),fileContainingReference:t,context:r,namespace:o});return PC(B)}),j={properties:O};P.length>0&&(j.extends=P),n.additionalProperties&&(j["extra-properties"]=!0);let M={name:i??g.nameOverride??g.generatedName,"query-parameters":u,headers:d,body:j};return n.contentType!=null&&(M["content-type"]=n.contentType),n.description!=null&&(M.docs=n.description),{schemaIdsToExclude:l!=null?[l]:[],value:M}}else{if(n.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":D4.APPLICATION_OCTET_STREAM,...n.description?{docs:n.description}:{}}};if(n.type==="multipart"){let l=Object.fromEntries(n.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let P={type:O};return g.description!=null&&(P.docs=g.description),g.contentType!=null&&(P["content-type"]=g.contentType),[g.key,P]}return[g.key,O]}else{let O=Z1({schema:g.schema.value,fileContainingReference:t,context:r,namespace:o});return g.contentType!=null&&(typeof O=="string"?O={type:O,"content-type":g.contentType}:O["content-type"]=g.contentType),[g.key,O]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??a,"query-parameters":u,headers:d,body:{properties:l},"content-type":D4.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else xc(n)}}function uDw({location:e,namespaceOverride:t}){return t!=null?{...e,file:yf(Ms.of(t),e.file)}:e}function sDw(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:Ms.of(`${_A(r)}.yml`),endpointId:e.summary!=null?_A(e.summary):_A(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Ms.of($A),endpointId:_A(e.summary)}:{file:Ms.of($A),endpointId:_A(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Ms.of($A),endpointId:n};let i=SOi(r),a=SOi(n);if(Yqt(i,a))return{file:Ms.of("__package__.yml"),endpointId:r};let u=fDw({operationId:n,tag:r,path:e.path,method:e.method});if(u!=null)return u;let f=[];for(let d=0;d<i.length;++d){let c=i[d];if(c!=null&&c===a[d])f.push(c);else{let o=_A(r);return{file:Ms.of(`${o}.yml`),endpointId:n,tag:r}}}if(f.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Ms.of(_A(f.join("_"))+".yml"),endpointId:_A(a.slice(f.length).join("_")),tag:r}}function EOi(e){let t=e.tags[0];if(e.sdkName!=null){let r=A1u({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Ms.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return uDw({namespaceOverride:e.namespace,location:sDw(e)})}function SOi(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=W8t(t),t}var cDw=new RegExp("[^a-zA-Z0-9{}]+"),lDw=new RegExp("[{}]","g");function fDw({operationId:e,tag:t,path:r,method:n}){let a=`${r.split(cDw).join("_").replaceAll(lDw,"_")}_${n.toLowerCase()}`;if(e.endsWith(a))return{file:Ms.of(_A(t)+".yml"),endpointId:_A(e.slice(0,-1*a.length)),tag:t}}function HJf(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let a of r){let{endpointId:u,file:f,tag:d}=EOi(a),c=f.split(".")[0];c!=null&&t.add(c);let o;if(a.sdkName!=null){let O=e.ir.groups;for(let P of a.sdkName.groupName){let j=typeof P=="string"?P:P.name,M=O[j];if(M==null)break;if(M.summary!=null||M.description!=null){o=O[j];break}}}let l=d==null?void 0:n.tagsById[d],g=VJf({context:e,endpoint:a,declarationFile:f});i=[...i,...g.schemaIdsToExclude],e.builder.addEndpoint(f,{name:u,schema:g.value,source:a.source!=null?Ann(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(f,{"display-name":o?.summary??l?.id,docs:o?.description??l?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}function QJf(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?oMr(r.groupName):void 0,i=Z1({schema:gb.primitive(r),context:e,fileContainingReference:Ms.of($A),namespace:n});e.builder.addVariable({name:t,schema:{type:PC(i),docs:r.description??void 0}})}}function JJf(e){for(let t of e.ir.webhooks){let r=_Dw({webhook:t,context:e});if(r==null)continue;let n=PMa(t.sdkName,t.namespace),i={};for(let u of t.headers)i[u.name]=M9t({header:u,context:e,fileContainingReference:r.file,namespace:n});let a={method:t.method,"display-name":t.summary??void 0,headers:i,payload:Z1({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:jk(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function dDw({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:yf(Ms.of(t),e.file)}:e}function pDw({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:Ms.of($A),endpointId:n};let i=SOi(r),a=SOi(n);if(Yqt(i,a))return{file:Ms.of("__package__.yml"),endpointId:r};let u=[];for(let f=0;f<i.length;++f){let d=i[f];if(d!=null&&d===a[f])u.push(d);else{let c=_A(r);return{file:Ms.of(`${c}.yml`),endpointId:n,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Ms.of(_A(u.join("_"))+".yml"),endpointId:_A(a.slice(u.length).join("_")),tag:r}}function _Dw({webhook:e,context:t}){return e.sdkName!=null?{file:z4f({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:dDw({namespaceOverride:e.namespace,location:pDw({webhook:e,context:t})})}var hDw=Ms.of($A);function GJf(e){switch(e.type){case"object":return X9t(e.groupName);case"enum":return X9t(e.groupName);case"oneOf":return X9t(e.value.groupName);case"array":return X9t(e.groupName);case"map":return X9t(e.groupName);case"reference":return X9t(e.groupName);case"literal":return X9t(e.groupName);case"optional":return X9t(e.groupName);case"nullable":return X9t(e.groupName);case"primitive":return X9t(e.groupName);case"unknown":return hDw;default:xc(e)}}function X9t(e){return hNn(e)}var qxu="external",WJf=Ms.of($A);function $Jf({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,a]of Object.entries(e)){if(t.includes(i))continue;let u=GJf(a),f=U4f({schema:a,context:n,declarationFile:u,namespace:r});if(zIn(f.schema)){let d=PC(f.schema);if(d===(f.name??i)||d===`optional<${f.name??i}>`)continue}n.builder.addType(u,{name:f.name??i,schema:f.schema})}}function KJf(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),qJf(e),IJf(e),BJf(e),Q4f(e),QJf(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(qxu);let{schemaIdsToExclude:t,sdkGroups:r}=HJf(e);JJf(e);for(let n of e.ir.channel){let i=hNn(n.groupName);MJf({channel:n,context:e,declarationFile:i})}$Jf({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:t,namespace:void 0,context:e});for(let[n,i]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))$Jf({schemas:i,schemaIdsToExclude:t,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(i=>r.has(i))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}var AOi=class{context;constructor(t){this.context=t}};var G5r=Xo(require("path"),1);var jMa=Xo(require("path"),1),DMa=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[u,f]of Object.entries(n.files)){let d=i!=null?Ms.of(`${i}${jMa.default.sep}${u}`):Ms.of(u);t[d]=f}let a=Object.keys(n.directories).sort();for(let u of a){let f=i!=null?`${i}${jMa.default.sep}${u}`:u,d=n.directories[u];r(d,f)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(jMa.default.sep))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Ms.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}};var Fin=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new DMa,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),n!=null&&(u.service["base-path"]=n),i!=null&&(u.service["display-name"]=i),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return NEr(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{}),r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:n}){if(t===r)return;let i=n??_A((cb(r)+"/"+(0,G5r.basename)(r,(0,G5r.extname)(r))).replaceAll("__package__","root"));if(t===Ms.of(m5))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=jq(cb(y_.of(`/${t}`)),y_.of(`/${r}`)),i;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[i]=jq(cb(y_.of(`/${t}`)),y_.of(`/${r}`)),i}addType(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let a=i.types[r];a!=null&&(typeof a=="string"?i.types[r]={type:a,examples:[n]}:(a.examples==null&&(a.examples=[]),a.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let a=i.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(f=>Yqt(f,n))??!1)||a.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(a.service.source=i),a.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=G5r.default.join(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([i,a])=>[i,{...a,path:G5r.default.join(r,a.path)}]))});for(let i of Object.values(t))i.service!=null&&(i.service={...i.service,endpoints:Object.fromEntries(Object.entries(i.service.endpoints).map(([a,u])=>[a,{...u,path:G5r.default.join(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===$A?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};var SMa=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;constructor({taskContext:t,ir:r,enableUniqueErrorsPerEndpoint:n,detectGlobalHeaders:i,environmentOverrides:a,globalHeaderOverrides:u,authOverrides:f}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.enableUniqueErrorsPerEndpoint=n,this.builder=new Fin(n),r.title!=null&&this.builder.setDisplayName({displayName:r.title}),this.detectGlobalHeaders=i,this.environmentOverrides=a,this.authOverrides=f,this.globalHeaderOverrides=u;let d={};if(!this.enableUniqueErrorsPerEndpoint)for(let c of r.endpoints)for(let[o,l]of Object.entries(c.errors)){let g=parseInt(o),O=d[g];O==null&&l.schema!=null?d[g]=l.schema:O!=null&&l.schema!=null&&MDe(O,l.schema)||this.unknownSchema.add(g)}}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}};function Ixu(e){let t=new SMa(e);return KJf(t)}function EMa(e,t){return by(e,t)}var N2e=class extends jIt{specs;sources;constructor({specs:t,...r}){super(r),this.specs=t,this.sources=this.convertSpecsToIdentifiableSources(t)}async getOpenAPIIr({context:t,relativePathToDependency:r},n){let i=await _nn({context:t,specs:this.specs,relativePathToDependency:r});return await Rin({absoluteFilePathToWorkspace:this.absoluteFilePath,specs:i,taskContext:t,optionOverrides:yDw(n)})}async getDefinition({context:t,relativePathToDependency:r},n){let i=await this.getOpenAPIIr({context:t,relativePathToDependency:r},n),a=Ixu({authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0,taskContext:t,ir:i,enableUniqueErrorsPerEndpoint:n?.enableUniqueErrorsPerEndpoint??!1,detectGlobalHeaders:n?.detectGlobalHeaders??!0});return{absoluteFilePath:y_.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:d0.dump(a.rootApiFile)},namedDefinitionFiles:{...EMa(a.definitionFiles,u=>({absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(u),contents:u})),[Ms.of($A)]:{absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}async toFernWorkspace({context:t},r){let n=await this.getDefinition({context:t},r);return new DIt({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter($M)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,n=[];return t.reduce((i,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),i.push({type:a.type,id:izr(),absoluteFilePath:u})),i},n)}};function MOi(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.enableDiscriminatedUnionV2=!0),t}function yDw(e){if(e==null)return;let t={};return e.enableDiscriminatedUnionV2&&(t.discriminatedUnionV2=!0),e.optionalAdditionalProperties&&(t.optionalAdditionalProperties=!0),e.cooerceEnumsToLiterals&&(t.cooerceEnumsToLiterals=!0),t}function YJf(e,t){if(vDw(e))return t.alias(e);if(bDw(e))return t.enum(e);if(gDw(e))return t.object(e);if(mDw(e))return t.union(e);xc(e)}function vDw(e){return e?.alias!=null}function bDw(e){return e?.values!=null}function gDw(e){return e?.fields!=null}function mDw(e){return e?.union!=null}var KMa={};kc(KMa,{ConjureAliasDeclaration:()=>IMa,ConjureArgument:()=>JMa,ConjureArgumentWithParamType:()=>QMa,ConjureDefinitions:()=>VMa,ConjureEndpoint:()=>GMa,ConjureEnumDeclaration:()=>LMa,ConjureEnumVariant:()=>FMa,ConjureEnumWithDocs:()=>RMa,ConjureObjectDeclaration:()=>zMa,ConjureParamType:()=>HMa,ConjurePrimitive:()=>qMa,ConjureService:()=>$Ma,ConjureServiceName:()=>CMa,ConjureType:()=>Y5r,ConjureTypeDeclaration:()=>UMa,ConjureTypeReference:()=>X5r,ConjureTypeWithDocs:()=>BMa,ConjureTypes:()=>WMa,ConjureUnionDeclaration:()=>NMa,DefinitionFile:()=>wGf,WithDocs:()=>k9t,commons:()=>Fxu,conjure:()=>Lxu,services:()=>Uxu,types:()=>Vxu});var Fxu={};kc(Fxu,{WithDocs:()=>k9t});var Vy={};kc(Vy,{JsonError:()=>K8n,ParseError:()=>Y8n,any:()=>lGf,boolean:()=>fGf,booleanLiteral:()=>cGf,date:()=>ZJf,discriminant:()=>mGf,enum_:()=>MMa,getObjectLikeUtils:()=>Z9t,getObjectUtils:()=>Z8n,getSchemaUtils:()=>O6,isProperty:()=>K5r,lazy:()=>kJf,lazyObject:()=>oGf,list:()=>TMa,number:()=>dGf,object:()=>xMa,objectWithoutOptionalProperties:()=>aGf,optional:()=>Bxu,property:()=>tGf,record:()=>yGf,set:()=>vGf,string:()=>pGf,stringLiteral:()=>sGf,transform:()=>Nxu,undiscriminatedUnion:()=>gGf,union:()=>PGf,unknown:()=>_Gf,withParsedProperties:()=>Rxu});var gE={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 Z2(e,t){return`Expected ${t}. Received ${ODw(e)}.`}function ODw(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 Q$(e){return{...e,json:XJf(e.json),parse:XJf(e.parse)}}function XJf(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
1957
|
-
`)),{ok:!0,value:t}):n}}function AMa(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var K8n=class e extends Error{errors;constructor(t){super(t.map(AMa).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Y8n=class e extends Error{errors;constructor(t){super(t.map(AMa).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function O6(e){return{optional:()=>Bxu(e),transform:t=>Nxu(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Y8n(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new K8n(n.errors)}}}function Bxu(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>gE.OPTIONAL};return{...t,...O6(t)}}function Nxu(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...O6(r)}}var PDw=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function ZJf(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:Z2(t,"string")}]}:PDw.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:Z2(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:Z2(t,"Date object")}]},getType:()=>gE.DATE};return{...Q$(e),...O6(e)}}function J$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...Q$(r),...O6(r)}}}function MMa(e){let t=new Set(e);return J$(gE.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:Z2(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:Z2(n,"enum")}]}:{ok:!0,value:n})()}function kJf(e){let t=zxu(e);return{...t,...O6(t)}}function zxu(e){return{parse:(t,r)=>X8n(e).parse(t,r),json:(t,r)=>X8n(e).json(t,r),getType:()=>X8n(e).getType()}}function X8n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function xOi(e){return Object.entries(e)}function TOi(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function $5r(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function COi(e){return Object.keys(e)}function eGf(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function Z9t(e){return{withParsedProperties:t=>Rxu(e,t)}}function Rxu(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let u=Object.entries(t).reduce((f,[d,c])=>({...f,[d]:typeof c=="function"?c(a.value):c}),{});return{ok:!0,value:{...a.value,...u}}},json:(n,i)=>{if(!$5r(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:Z2(n,"object")}]};let a=new Set(Object.keys(t)),u=TOi(n,Object.keys(n).filter(f=>!a.has(f)));return e.json(u,i)},getType:()=>e.getType()};return{...r,...O6(r),...Z9t(r)}}function tGf(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function K5r(e){return e.isProperty}function xMa(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>K5r(n)?n.rawKey:r),_getParsedProperties:()=>COi(e),parse:(r,n)=>{let i={},a=[];for(let[u,f]of xOi(e)){let d=K5r(f)?f.rawKey:u,c=K5r(f)?f.valueSchema:f,o={rawKey:d,parsedKey:u,valueSchema:c};i[d]=o,iGf(c)&&a.push(d)}return rGf({value:r,requiredKeys:a,getProperty:u=>{let f=i[u];if(f!=null)return{transformedKey:f.parsedKey,transform:d=>f.valueSchema.parse(d,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,u]of xOi(e)){let f=K5r(u)?u.valueSchema:u;iGf(f)&&i.push(a)}return rGf({value:r,requiredKeys:i,getProperty:a=>{let u=e[a];if(u!=null)return K5r(u)?{transformedKey:u.rawKey,transform:f=>u.valueSchema.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:f=>u.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>gE.OBJECT};return{...Q$(t),...O6(t),...Z9t(t),...Z8n(t)}}function rGf({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!$5r(e))return{ok:!1,errors:[{path:a,message:Z2(e,"object")}]};let u=new Set(t),f=[],d={};for(let[c,o]of Object.entries(e)){let l=r(c);if(l!=null){u.delete(c);let g=l.transform(o);g.ok?d[l.transformedKey]=g.value:(d[c]=o,f.push(...g.errors))}else switch(n){case"fail":f.push({path:[...a,c],message:`Unexpected key "${c}"`});break;case"strip":break;case"passthrough":d[c]=o;break}}return f.push(...t.filter(c=>u.has(c)).map(c=>({path:a,message:`Missing required key "${c}"`}))),f.length===0||i?{ok:!0,value:d}:{ok:!1,errors:f}}function Z8n(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>nGf({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>nGf({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>gE.OBJECT};return{...r,...O6(r),...Z9t(r),...Z8n(r)}}}}function nGf({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,u]=eGf(COi(t),c=>i.has(c)),f=r(TOi(t,u)),d=n(TOi(t,a));return f.ok&&d.ok?{ok:!0,value:{...f.value,...d.value}}:{ok:!1,errors:[...f.ok?[]:f.errors,...d.ok?[]:d.errors]}}function iGf(e){return!wDw(e)}function wDw(e){switch(e.getType()){case gE.ANY:case gE.UNKNOWN:case gE.OPTIONAL:return!0;default:return!1}}function aGf(e){return xMa(e)}function oGf(e){let t={...zxu(e),_getRawProperties:()=>X8n(e)._getRawProperties(),_getParsedProperties:()=>X8n(e)._getParsedProperties()};return{...t,...O6(t),...Z9t(t),...Z8n(t)}}function TMa(e){let t={parse:(r,n)=>uGf(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>uGf(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>gE.LIST};return{...Q$(t),...O6(t)}}function uGf(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:Z2(e,"list"),path:[]}]}}function sGf(e){return J$(gE.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:Z2(r,`"${e}"`)}]})()}function cGf(e){return J$(gE.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:Z2(r,`${e.toString()}`)}]})()}var lGf=J$(gE.ANY,e=>({ok:!0,value:e}));var fGf=J$(gE.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"boolean")}]});var dGf=J$(gE.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"number")}]});var pGf=J$(gE.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"string")}]});var _Gf=J$(gE.UNKNOWN,e=>({ok:!0,value:e}));function yGf(e,t){let r={parse:(n,i)=>hGf({value:n,isKeyNumeric:e.getType()===gE.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>hGf({value:n,isKeyNumeric:e.getType()===gE.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>gE.RECORD};return{...Q$(r),...O6(r)}}function hGf({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return $5r(e)?xOi(e).reduce((a,[u,f])=>{if(f==null)return a;let d=a,c=u;if(t){let O=u.length>0?Number(u):NaN;isNaN(O)||(c=O)}let o=r(c),l=n(f,c);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let g=[];return d.ok||g.push(...d.errors),o.ok||g.push(...o.errors),l.ok||g.push(...l.errors),{ok:!1,errors:g}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:Z2(e,"object")}]}}function vGf(e){let t=TMa(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:Z2(n,"Set")}]},getType:()=>gE.SET};return{...Q$(r),...O6(r)}}function gGf(e){let t={parse:(r,n)=>bGf((i,a)=>i.parse(r,a),e,n),json:(r,n)=>bGf((i,a)=>i.json(r,a),e,n),getType:()=>gE.UNDISCRIMINATED_UNION};return{...Q$(t),...O6(t)}}function bGf(e,t,r){let n=[];for(let[i,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let f of u.errors)n.push({path:f.path,message:`[Variant ${i}] ${f.message}`})}return{ok:!1,errors:n}}function mGf(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function PGf(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=MMa(COi(t)),a={parse:(u,f)=>OGf({value:u,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:d=>i.parse(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.parse(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),json:(u,f)=>OGf({value:u,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:d=>i.json(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.json(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),getType:()=>gE.UNION};return{...Q$(a),...O6(a),...Z9t(a)}}function OGf({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:f=[]}){if(!$5r(e))return{ok:!1,errors:[{path:f,message:Z2(e,"object")}]};let{[t]:d,...c}=e;if(d==null)return{ok:!1,errors:[{path:f,message:`Missing discriminant ("${t}")`}]};let o=n(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=i(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...c}}:{ok:!1,errors:[{path:[...f,t],message:"Unexpected discriminant value"}]};let g=u(c,l);return g.ok?{ok:!0,value:{[r]:d,...g.value}}:g}var k9t=Vy.objectWithoutOptionalProperties({docs:Vy.string().optional()});var Lxu={};kc(Lxu,{ConjureServiceName:()=>CMa,DefinitionFile:()=>wGf});var CMa=Vy.string();var qMa=Vy.enum_(["rid","string","safelong","integer","double","boolean"]);var Y5r=Vy.undiscriminatedUnion([qMa,Vy.string()]);var IMa=Vy.objectWithoutOptionalProperties({alias:Y5r,docs:Vy.string().optional()});var BMa=Vy.objectWithoutOptionalProperties({type:Y5r,docs:Vy.string().optional()});var X5r=Vy.undiscriminatedUnion([Y5r,BMa]);var NMa=Vy.objectWithoutOptionalProperties({union:Vy.record(Vy.string(),X5r)});var zMa=Vy.objectWithoutOptionalProperties({fields:Vy.record(Vy.string(),X5r)});var RMa=Vy.objectWithoutOptionalProperties({value:Vy.string()}).extend(k9t);var FMa=Vy.undiscriminatedUnion([Vy.string(),RMa]);var LMa=Vy.objectWithoutOptionalProperties({values:Vy.list(FMa)});var UMa=Vy.undiscriminatedUnion([IMa,NMa,zMa,LMa]);var VMa=Vy.objectWithoutOptionalProperties({objects:Vy.record(Vy.string(),UMa).optional()});var WMa=Vy.objectWithoutOptionalProperties({conjureImports:Vy.property("conjure-imports",Vy.record(Vy.string(),Vy.string()).optional()),definitions:VMa.optional()});var HMa=Vy.enum_(["path","query","body"]);var QMa=Vy.objectWithoutOptionalProperties({paramType:Vy.property("param-type",HMa),type:Vy.string()}).extend(k9t);var JMa=Vy.undiscriminatedUnion([Vy.string(),QMa]);var GMa=Vy.objectWithoutOptionalProperties({http:Vy.string(),args:Vy.record(Vy.string(),JMa).optional(),returns:X5r.optional()}).extend(k9t);var $Ma=Vy.objectWithoutOptionalProperties({name:Vy.string().optional(),package:Vy.string().optional(),basePath:Vy.property("base-path",Vy.string().optional()),endpoints:Vy.record(Vy.string(),GMa).optional()}).extend(k9t);var wGf=Vy.objectWithoutOptionalProperties({types:WMa.optional(),services:Vy.record(CMa,$Ma).optional()});var Uxu={};kc(Uxu,{ConjureArgument:()=>JMa,ConjureArgumentWithParamType:()=>QMa,ConjureEndpoint:()=>GMa,ConjureParamType:()=>HMa,ConjureService:()=>$Ma});var Vxu={};kc(Vxu,{ConjureAliasDeclaration:()=>IMa,ConjureDefinitions:()=>VMa,ConjureEnumDeclaration:()=>LMa,ConjureEnumVariant:()=>FMa,ConjureEnumWithDocs:()=>RMa,ConjureObjectDeclaration:()=>zMa,ConjurePrimitive:()=>qMa,ConjureType:()=>Y5r,ConjureTypeDeclaration:()=>UMa,ConjureTypeReference:()=>X5r,ConjureTypeWithDocs:()=>BMa,ConjureTypes:()=>WMa,ConjureUnionDeclaration:()=>NMa});var jGf=require("fs/promises");async function DGf(e,t){let r=[];for(let n of await tTe(e,t))r.push(await jDw({relativeFilepath:jq(e,n),absoluteFilepath:n}));return r}async function jDw({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,jGf.readFile)(t)).toString().replaceAll(": rid",": string").replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:KMa.DefinitionFile.parseOrThrow(d0.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}var qOi=class extends AOi{fernDefinitionBuilder=new Fin(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:n,globalHeaderOverrides:i}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(n!=null){for(let[a,u]of Object.entries(n.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});n["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(n["default-environment"]),n["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(n["default-url"])}return await SGf(t,(a,u,f)=>{for(let[o,l]of Object.entries(f.services??{})){let g=gXi({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Ms.of(`${g}/__package__.yml`);return}let c=TZo(u)?.split(".")[0];c!=null&&(this.conjureFilepathToFernFilepath[u]=Ms.of(`${c}/__package__.yml`))}),await SGf(t,(a,u,f)=>{if(f.services==null||Object.keys(f.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[c,o]of Object.entries(f.types?.conjureImports??{})){let l=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ms.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Ms.of(l),alias:c})}this.importAllTypes({conjureFile:f,fernFilePath:d});return}for(let[d,c]of Object.entries(f.services)){let o=gXi({value:d,suffix:"Service"}),l=Ms.of(`${o}/__package__.yml`),g={};c.basePath!=null&&(g["base-path"]=c.basePath),c.docs!=null&&(g.docs=c.docs),this.fernDefinitionBuilder.setServiceInfo(l,g),this.importAllTypes({conjureFile:f,fernFilePath:l});for(let[O,P]of Object.entries(f.types?.conjureImports??{})){let j=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ms.of(P)});this.fernDefinitionBuilder.addImport({file:l,fileToImport:Ms.of(j),alias:O})}for(let[O,P]of Object.entries(c.endpoints??{})){let j=NKo(P.http);if(j.type==="failure"){this.context?.logger.error(`Failed to parse ${P.http}. Skipping.`);continue}let M={auth:!0,path:j.path,method:j.method,response:P.returns==="binary"?"file":P.returns},q={};if(P.args!=null)for(let B of j.pathParameters){let I=P.args[B];if(I==null)throw new Error(`Failed to find path parameter ${B} in ${P.http}`);q[B]=typeof I=="string"?I:{type:I.type}}Object.entries(q).length>0&&(M["path-parameters"]=q);for(let[B,I]of Object.entries(P.args??{}))if(q[B]==null)if(typeof I=="string")M.request={body:I==="binary"?"bytes":I};else switch(I.paramType){case"body":M.request={body:I.type==="binary"?"bytes":I.type};break;case"query":M.request==null?M.request={"query-parameters":{[B]:I.type}}:typeof M.request!="string"&&M.request?.["query-parameters"]==null?M.request["query-parameters"]={[B]:I.type}:typeof M.request!="string"&&M.request?.["query-parameters"]!=null&&(M.request["query-parameters"][B]=I.type)}M.request!=null&&typeof M.request!="string"&&M.request?.["query-parameters"]!=null&&(M.request.name=`${O}Request`),this.fernDefinitionBuilder.addEndpoint(l,{name:O,schema:M,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[n,i]of Object.entries(t.types?.definitions?.objects??{}))YJf(i,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,f])=>[u,{type:typeof f=="string"?f:f.type,docs:typeof f=="string"?void 0:f.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:n}){let i=yf(cb(t),Ms.of(r)),a=w3r(n,i),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function SGf(e,t){for(let r of await DGf(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}var YMa=class extends jIt{absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=yf(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let n=await this.getDefinition({context:t},r);return new DIt({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let i=await new qOi(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:y_.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:i.rootApiFile["default-url"],contents:i.rootApiFile,rawContents:d0.dump(i.rootApiFile)},namedDefinitionFiles:{...EMa(i.definitionFiles,a=>({absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(a),contents:a})),[Ms.of($A)]:{absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(i.packageMarkerFile),contents:i.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function Wxu(e,t){for(let[r,n]of b8(e.failures))DDw({relativeFilepath:r,failure:n,logger:t})}function DDw({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case Dj.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case Dj.FILE_READ:r.error("Failed to open file: "+e);break;case Dj.FILE_MISSING:r.error("Missing file: "+e);break;case Dj.FILE_PARSE:t.error instanceof $pi?r.error(c6t({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case Dj.STRUCTURE_VALIDATION:for(let n of t.error.issues)for(let{title:i,subtitle:a}of SDw(n))r.error(c6t({title:i,subtitle:a,breadcrumbs:[e,...n.path]}));break;case Dj.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case Dj.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${tZi}: `+t.dependencyName);break;case Dj.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case Dj.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case Dj.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(c6t({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(n=>n!=="")]}));break;default:xc(t)}}function SDw(e){switch(e.code){case r_.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${nl.underline(e.expected)} but received ${nl.underline(e.received)}`}];case r_.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${nl.underline(t)}`}));case r_.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>nl.underline(t)).join(", ")}`}];case r_.invalid_union:case r_.invalid_arguments:case r_.invalid_return_type:case r_.invalid_date:case r_.invalid_string:case r_.too_small:case r_.too_big:case r_.invalid_intersection_types:case r_.not_multiple_of:case r_.custom:default:return[{title:e.message}]}}var EGf=require("fs/promises");async function AGf(e,t){let r=[];for(let n of await tTe(e,t))r.push(await EDw({relativeFilepath:jq(e,n),absoluteFilepath:n}));return r}async function EDw({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,EGf.readFile)(t)).toString()}}async function MGf({absolutePathToWorkspace:e}){let t=yf(e,Ms.of(ael));if(!await Wh(t))return;let n=await AGf(t,"{md,mdx}");return{files:await Promise.all(n.map(i=>({absoluteFilepath:i.absoluteFilepath,contents:i.fileContents})))}}async function Hxu({absolutePathToWorkspace:e,namespace:t,definitions:r}){let n=[];for(let i of r){let a=i.overrides!=null?yf(e,Ms.of(i.overrides)):void 0;if(i.schema.type==="protobuf"){let f=yf(e,Ms.of(i.schema.root));if(!await Wh(f))return{didSucceed:!1,failures:{[Ms.of(i.schema.root)]:{type:Dj.FILE_MISSING}}};let d=yf(e,Ms.of(i.schema.target));if(!await Wh(d))return{didSucceed:!1,failures:{[Ms.of(i.schema.target)]:{type:Dj.FILE_MISSING}}};n.push({type:"protobuf",absoluteFilepathToProtobufRoot:f,absoluteFilepathToProtobufTarget:d,absoluteFilepathToOverrides:a,generateLocally:i.schema.localGeneration,settings:{audiences:i.audiences??[],shouldUseTitleAsName:i.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:i.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,optionalAdditionalProperties:i.settings?.shouldUseOptionalAdditionalProperties??!0,cooerceEnumsToLiterals:i.settings?.coerceEnumsToLiterals??!0}});continue}let u=yf(e,Ms.of(i.schema.path));if(!await Wh(u))return{didSucceed:!1,failures:{[Ms.of(i.schema.path)]:{type:Dj.FILE_MISSING}}};if(i.overrides!=null&&a!=null&&!await Wh(a))return{didSucceed:!1,failures:{[Ms.of(i.overrides)]:{type:Dj.FILE_MISSING}}};n.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:i.audiences??[],shouldUseTitleAsName:i.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:i.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,asyncApiNaming:i.settings?.asyncApiMessageNaming,optionalAdditionalProperties:i.settings?.shouldUseOptionalAdditionalProperties??!0,cooerceEnumsToLiterals:i.settings?.coerceEnumsToLiterals??!0},source:{type:"openapi",file:u},namespace:t})}return n}async function IOi({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:n}){let i=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:e,context:t}),a;try{a=await MGf({absolutePathToWorkspace:e})}catch{}if(i?.api!=null&&i?.api.type==="conjure")return{didSucceed:!0,workspace:new YMa({workspaceName:n,absoluteFilePath:e,generatorsConfiguration:i,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:Ms.of(i.api.pathToConjureDefinition)})};if(i?.api!=null&&(i.api.type==="singleNamespace"&&i.api.definitions.length>0||i.api.type==="multiNamespace")){let u=[];if(i.api.type==="singleNamespace"){let f=await Hxu({absolutePathToWorkspace:e,namespace:void 0,definitions:i.api.definitions});if(!Array.isArray(f))return f;u.push(...f)}else{for(let[f,d]of Object.entries(i.api.definitions)){let c=await Hxu({absolutePathToWorkspace:e,namespace:f,definitions:d});if(!Array.isArray(c))return c;u.push(...c)}if(i.api.rootDefinitions!=null){let f=await Hxu({absolutePathToWorkspace:e,namespace:void 0,definitions:i.api.rootDefinitions});if(!Array.isArray(f))return f;u.push(...f)}}return{didSucceed:!0,workspace:new N2e({specs:u,workspaceName:n,absoluteFilePath:e,generatorsConfiguration:i,changelog:a,cliVersion:r})}}return await Wh(yf(e,Ms.of(QL)))?{didSucceed:!0,workspace:new U7n({absoluteFilePath:e,generatorsConfiguration:i,workspaceName:n,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:IOi})}:{didSucceed:!1,failures:{[Ms.of(qkr)]:{type:Dj.MISCONFIGURED_DIRECTORY}}}}var xGf=require("fs/promises");var TGf=Xo(require("path"),1);async function Qxu({fernDirectory:e,context:t}){let r=yf(e,Ms.of(LSr));if(!await Wh(r))return;let n=await ADw({absolutePathToDocsDefinition:e,context:t});if(n!=null)return{type:"docs",absoluteFilePath:e,config:n,workspaceName:void 0,absoluteFilepathToDocsConfig:yf(e,Ms.of(LSr))}}async function ADw({absolutePathToDocsDefinition:e,context:t}){if(!await Wh(e))return;let r=yf(e,Ms.of(LSr));return await MDw({absolutePathOfConfiguration:r,context:t})}async function MDw({absolutePathOfConfiguration:e,context:t}){let r=await(0,xGf.readFile)(e),n=d0.load(r.toString());return await xDw({value:n,context:t,filepathBeingParsed:e})}async function xDw({value:e,context:t,filepathBeingParsed:r}){let n=await gTe.RawSchemas.Serializer.DocsConfiguration.parse(e);if(n.ok)return n.value;let i=n.errors.map(u=>{let f=u.path.length>0?`${u.message} at "${u.path.join(" -> ")}"`:u.message;return DZ({content:f,prefix:" - "})}),a=[`Failed to parse file: ${TGf.default.relative(process.cwd(),r)}`,...i].join(`
|
|
1956
|
+
`)),{ok:!0,value:t}):n}}function B1a(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var H7n=class e extends Error{errors;constructor(t){super(t.map(B1a).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Q7n=class e extends Error{errors;constructor(t){super(t.map(B1a).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function g6(e){return{optional:()=>m1u(e),transform:t=>O1u(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Q7n(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new H7n(n.errors)}}}function m1u(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>vE.OPTIONAL};return{...t,...g6(t)}}function O1u(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...g6(r)}}var BG1=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function o4f(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:K2(t,"string")}]}:BG1.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:K2(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:K2(t,"Date object")}]},getType:()=>vE.DATE};return{...q$(e),...g6(e)}}function I$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...q$(r),...g6(r)}}}function N1a(e){let t=new Set(e);return I$(vE.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:K2(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:K2(n,"enum")}]}:{ok:!0,value:n})()}function u4f(e){let t=P1u(e);return{...t,...g6(t)}}function P1u(e){return{parse:(t,r)=>J7n(e).parse(t,r),json:(t,r)=>J7n(e).json(t,r),getType:()=>J7n(e).getType()}}function J7n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function sgi(e){return Object.entries(e)}function cgi(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function zzr(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function lgi(e){return Object.keys(e)}function s4f(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function S9t(e){return{withParsedProperties:t=>w1u(e,t)}}function w1u(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let u=Object.entries(t).reduce((f,[d,c])=>({...f,[d]:typeof c=="function"?c(a.value):c}),{});return{ok:!0,value:{...a.value,...u}}},json:(n,i)=>{if(!zzr(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:K2(n,"object")}]};let a=new Set(Object.keys(t)),u=cgi(n,Object.keys(n).filter(f=>!a.has(f)));return e.json(u,i)},getType:()=>e.getType()};return{...r,...g6(r),...S9t(r)}}function c4f(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Rzr(e){return e.isProperty}function z1a(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>Rzr(n)?n.rawKey:r),_getParsedProperties:()=>lgi(e),parse:(r,n)=>{let i={},a=[];for(let[u,f]of sgi(e)){let d=Rzr(f)?f.rawKey:u,c=Rzr(f)?f.valueSchema:f,o={rawKey:d,parsedKey:u,valueSchema:c};i[d]=o,d4f(c)&&a.push(d)}return l4f({value:r,requiredKeys:a,getProperty:u=>{let f=i[u];if(f!=null)return{transformedKey:f.parsedKey,transform:d=>f.valueSchema.parse(d,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,u]of sgi(e)){let f=Rzr(u)?u.valueSchema:u;d4f(f)&&i.push(a)}return l4f({value:r,requiredKeys:i,getProperty:a=>{let u=e[a];if(u!=null)return Rzr(u)?{transformedKey:u.rawKey,transform:f=>u.valueSchema.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:f=>u.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>vE.OBJECT};return{...q$(t),...g6(t),...S9t(t),...G7n(t)}}function l4f({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!zzr(e))return{ok:!1,errors:[{path:a,message:K2(e,"object")}]};let u=new Set(t),f=[],d={};for(let[c,o]of Object.entries(e)){let l=r(c);if(l!=null){u.delete(c);let g=l.transform(o);g.ok?d[l.transformedKey]=g.value:(d[c]=o,f.push(...g.errors))}else switch(n){case"fail":f.push({path:[...a,c],message:`Unexpected key "${c}"`});break;case"strip":break;case"passthrough":d[c]=o;break}}return f.push(...t.filter(c=>u.has(c)).map(c=>({path:a,message:`Missing required key "${c}"`}))),f.length===0||i?{ok:!0,value:d}:{ok:!1,errors:f}}function G7n(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>f4f({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>f4f({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>vE.OBJECT};return{...r,...g6(r),...S9t(r),...G7n(r)}}}}function f4f({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,u]=s4f(lgi(t),c=>i.has(c)),f=r(cgi(t,u)),d=n(cgi(t,a));return f.ok&&d.ok?{ok:!0,value:{...f.value,...d.value}}:{ok:!1,errors:[...f.ok?[]:f.errors,...d.ok?[]:d.errors]}}function d4f(e){return!NG1(e)}function NG1(e){switch(e.getType()){case vE.ANY:case vE.UNKNOWN:case vE.OPTIONAL:return!0;default:return!1}}function p4f(e){return z1a(e)}function _4f(e){let t={...P1u(e),_getRawProperties:()=>J7n(e)._getRawProperties(),_getParsedProperties:()=>J7n(e)._getParsedProperties()};return{...t,...g6(t),...S9t(t),...G7n(t)}}function R1a(e){let t={parse:(r,n)=>h4f(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>h4f(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>vE.LIST};return{...q$(t),...g6(t)}}function h4f(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:K2(e,"list"),path:[]}]}}function y4f(e){return I$(vE.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:K2(r,`"${e}"`)}]})()}function v4f(e){return I$(vE.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:K2(r,`${e.toString()}`)}]})()}var b4f=I$(vE.ANY,e=>({ok:!0,value:e}));var g4f=I$(vE.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"boolean")}]});var m4f=I$(vE.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"number")}]});var O4f=I$(vE.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:K2(e,"string")}]});var P4f=I$(vE.UNKNOWN,e=>({ok:!0,value:e}));function j4f(e,t){let r={parse:(n,i)=>w4f({value:n,isKeyNumeric:e.getType()===vE.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>w4f({value:n,isKeyNumeric:e.getType()===vE.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>vE.RECORD};return{...q$(r),...g6(r)}}function w4f({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return zzr(e)?sgi(e).reduce((a,[u,f])=>{if(f==null)return a;let d=a,c=u;if(t){let O=u.length>0?Number(u):NaN;isNaN(O)||(c=O)}let o=r(c),l=n(f,c);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let g=[];return d.ok||g.push(...d.errors),o.ok||g.push(...o.errors),l.ok||g.push(...l.errors),{ok:!1,errors:g}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:K2(e,"object")}]}}function D4f(e){let t=R1a(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:K2(n,"Set")}]},getType:()=>vE.SET};return{...q$(r),...g6(r)}}function E4f(e){let t={parse:(r,n)=>S4f((i,a)=>i.parse(r,a),e,n),json:(r,n)=>S4f((i,a)=>i.json(r,a),e,n),getType:()=>vE.UNDISCRIMINATED_UNION};return{...q$(t),...g6(t)}}function S4f(e,t,r){let n=[];for(let[i,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let f of u.errors)n.push({path:f.path,message:`[Variant ${i}] ${f.message}`})}return{ok:!1,errors:n}}function A4f(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function x4f(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=N1a(lgi(t)),a={parse:(u,f)=>M4f({value:u,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:d=>i.parse(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.parse(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),json:(u,f)=>M4f({value:u,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:d=>i.json(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.json(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),getType:()=>vE.UNION};return{...q$(a),...g6(a),...S9t(a)}}function M4f({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:f=[]}){if(!zzr(e))return{ok:!1,errors:[{path:f,message:K2(e,"object")}]};let{[t]:d,...c}=e;if(d==null)return{ok:!1,errors:[{path:f,message:`Missing discriminant ("${t}")`}]};let o=n(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=i(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...c}}:{ok:!1,errors:[{path:[...f,t],message:"Unexpected discriminant value"}]};let g=u(c,l);return g.ok?{ok:!0,value:{[r]:d,...g.value}}:g}var K1=Fn.objectWithoutOptionalProperties({title:Fn.string().optional()});var F1a=Fn.objectWithoutOptionalProperties({file:Fn.string()});var L1a=Fn.objectWithoutOptionalProperties({file:Fn.string()});var U1a=Fn.union("type",{openapi:F1a,protobuf:L1a}).transform({transform:e=>{switch(e.type){case"openapi":return NAr.openapi(e);case"protobuf":return NAr.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var xb=Fn.objectWithoutOptionalProperties({source:U1a.optional()});var V1a=Fn.objectWithoutOptionalProperties({typeName:Fn.string()});var W1a=Fn.union("type",{protobuf:V1a}).transform({transform:e=>{switch(e.type){case"protobuf":return V7n.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var dae=Fn.objectWithoutOptionalProperties({encoding:W1a.optional()});var M_=Fn.objectWithoutOptionalProperties({description:Fn.string().optional()});var H1a=Fn.enum_(["GenerallyAvailable","Beta","Deprecated"]);var hv=Fn.objectWithoutOptionalProperties({availability:H1a.optional()});var pO=Fn.objectWithoutOptionalProperties({nameOverride:Fn.string().optional(),generatedName:Fn.string()});var sk=Fn.string();var EDe=Fn.string();var Q1a=Fn.objectWithoutOptionalProperties({id:EDe}).extend(M_);var J1a=Fn.string();var G1a=Fn.objectWithoutOptionalProperties({usernameVariableName:Fn.string().optional(),usernameEnvVar:Fn.string().optional(),passwordVariableName:Fn.string().optional(),passwordEnvVar:Fn.string().optional()});var $1a=Fn.objectWithoutOptionalProperties({tokenVariableName:Fn.string().optional(),tokenEnvVar:Fn.string().optional()});var K1a=Fn.objectWithoutOptionalProperties({headerName:Fn.string(),prefix:Fn.string().optional(),headerVariableName:Fn.string().optional(),headerEnvVar:Fn.string().optional()});var Y1a=Fn.objectWithoutOptionalProperties({queryParameterName:Fn.string()});var X1a=Fn.objectWithoutOptionalProperties({snake:Fn.string().optional(),camel:Fn.string().optional(),screamingSnake:Fn.string().optional(),pascal:Fn.string().optional()});var Fzr=Fn.objectWithoutOptionalProperties({nameOverride:Fn.string().optional(),generatedName:Fn.string(),value:Fn.string(),casing:X1a.optional()}).extend(M_).extend(hv);var Z1a=Fn.objectWithoutOptionalProperties({type:Fn.stringLiteral("namespace"),name:Fn.string()});var k1a=Fn.undiscriminatedUnion([Fn.string(),Z1a]);var Lzr=Fn.list(k1a);var Y1=Fn.objectWithoutOptionalProperties({groupName:Lzr.optional()});var $7n=Fn.objectWithoutOptionalProperties({default:Fzr.optional(),values:Fn.list(Fzr)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var ewa=Fn.objectWithoutOptionalProperties({scopesEnum:$7n.optional()});var twa=Fn.union("type",{basic:G1a,bearer:$1a,header:K1a,query:Y1a,oauth:ewa}).transform({transform:e=>{switch(e.type){case"basic":return PU.basic(e);case"bearer":return PU.bearer(e);case"header":return PU.header(e);case"query":return PU.query(e);case"oauth":return PU.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Uzr=Fn.number();var rwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),url:Fn.string(),audiences:Fn.list(Fn.string()).optional()}).extend(M_);var nwa=Fn.string();var Vzr=Fn.objectWithoutOptionalProperties({namespace:Fn.string().optional()});var D1u={};kc(D1u,{FullExample:()=>Y2,FullObjectExample:()=>awa,FullOneOfExample:()=>uwa,KeyValuePair:()=>owa,LiteralExample:()=>iwa,PrimitiveExample:()=>Y7n,PropertyKey:()=>K7n});var K7n=Fn.string();var Y7n=Fn.union("type",{int:Fn.object({value:Fn.number()}),int64:Fn.object({value:Fn.number()}),uint:Fn.object({value:Fn.number()}),uint64:Fn.object({value:Fn.number()}),float:Fn.object({value:Fn.number()}),double:Fn.object({value:Fn.number()}),string:Fn.object({value:Fn.string()}),datetime:Fn.object({value:Fn.string()}),date:Fn.object({value:Fn.string()}),base64:Fn.object({value:Fn.string()}),boolean:Fn.object({value:Fn.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return h0.int(e.value);case"int64":return h0.int64(e.value);case"uint":return h0.uint(e.value);case"uint64":return h0.uint64(e.value);case"float":return h0.float(e.value);case"double":return h0.double(e.value);case"string":return h0.string(e.value);case"datetime":return h0.datetime(e.value);case"date":return h0.date(e.value);case"base64":return h0.base64(e.value);case"boolean":return h0.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var iwa=Fn.union("type",{boolean:Fn.object({value:Fn.boolean()}),string:Fn.object({value:Fn.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return W7n.boolean(e.value);case"string":return W7n.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Y2=Fn.union("type",{primitive:Fn.object({value:Y7n}),object:Fn.lazyObject(()=>awa),array:Fn.object({value:Fn.list(Fn.lazy(()=>Y2))}),map:Fn.object({value:Fn.list(Fn.lazyObject(()=>owa))}),enum:Fn.object({value:Fn.string()}),literal:Fn.object({value:iwa}),oneOf:Fn.object({value:Fn.lazy(()=>uwa)}),unknown:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"primitive":return i1.primitive(e.value);case"object":return i1.object(e);case"array":return i1.array(e.value);case"map":return i1.map(e.value);case"enum":return i1.enum(e.value);case"literal":return i1.literal(e.value);case"oneOf":return i1.oneOf(e.value);case"unknown":return i1.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var awa=Fn.objectWithoutOptionalProperties({properties:Fn.record(K7n,Fn.lazy(()=>Y2))});var owa=Fn.objectWithoutOptionalProperties({key:Y7n,value:Fn.lazy(()=>Y2)});var uwa=Fn.union("type",{discriminated:Fn.object({value:Fn.record(K7n,Fn.lazy(()=>Y2))}),undisciminated:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"discriminated":return Bzr.discriminated(e.value);case"undisciminated":return Bzr.undisciminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var S1u={};kc(S1u,{AllOfPropertyConflict:()=>cNn,ArraySchema:()=>Gwa,Availability:()=>H1a,BooleanSchema:()=>Uwa,CasingOverrides:()=>X1a,CommonProperty:()=>tja,CursorPagination:()=>Swa,CustomCodeSample:()=>jwa,CustomCodeSampleLanguage:()=>Owa,CustomCodeSampleSdk:()=>wwa,DiscriminatedOneOfSchema:()=>kwa,DoubleSchema:()=>Fwa,Endpoint:()=>Awa,EndpointExample:()=>oNn,EndpointResponseExample:()=>mwa,EndpointSdkName:()=>Hzr,EnumSchema:()=>$7n,EnumValue:()=>Fzr,ErrorExample:()=>ywa,FernExample:()=>bwa,FileResponse:()=>rNn,FileSchema:()=>lwa,FullEndpointExample:()=>Dwa,GlobalHeader:()=>Wwa,Header:()=>Wzr,HeaderExample:()=>aNn,HttpEndpointServer:()=>nNn,HttpError:()=>vwa,HttpMethod:()=>X7n,IdempotencyHeader:()=>Hwa,IntSchema:()=>zwa,JsonRequest:()=>pwa,JsonResponse:()=>Qzr,LiteralSchema:()=>sNn,LiteralSchemaValue:()=>Qwa,LongSchema:()=>Rwa,MapSchema:()=>$wa,MultipartRequest:()=>tNn,MultipartRequestProperty:()=>dwa,MultipartSchema:()=>fwa,NullableSchema:()=>Ywa,ObjectProperty:()=>Zwa,ObjectPropertyConflictInfo:()=>lNn,ObjectSchema:()=>Jwa,OctetStreamRequest:()=>eNn,OffsetPagination:()=>Ewa,OneOfSchema:()=>Xwa,OpenApiIntermediateRepresentation:()=>T4f,OptionalSchema:()=>Kwa,Pagination:()=>uNn,PathParameter:()=>Z7n,PathParameterExample:()=>gwa,PrimitiveSchema:()=>Gzr,PrimitiveSchemaValue:()=>Vwa,QueryParameter:()=>k7n,QueryParameterExample:()=>iNn,ReferencedSchema:()=>E9t,Request:()=>_wa,Response:()=>hwa,Schema:()=>X1,Schemas:()=>Nwa,SdkGroupInfo:()=>swa,StringSchema:()=>Lwa,SupportedSdkLanguage:()=>Pwa,Tags:()=>cwa,TextResponse:()=>Jzr,UnDiscriminatedOneOfSchema:()=>eja,Webhook:()=>Twa,WebhookExampleCall:()=>xwa,WebhookHttpMethod:()=>Mwa,WebsocketChannel:()=>Bwa,WebsocketHandshake:()=>Cwa,WebsocketMessageExample:()=>qwa,WebsocketSessionExample:()=>Iwa});var swa=Fn.objectWithoutOptionalProperties({summary:Fn.string().optional(),description:Fn.string().optional()});var cwa=Fn.objectWithoutOptionalProperties({tagsById:Fn.record(EDe,Q1a),orderedTagIds:Fn.list(EDe).optional()});var X7n=Fn.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var Z7n=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),variableReference:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var k7n=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var Wzr=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>X1),env:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var Hzr=Fn.objectWithoutOptionalProperties({groupName:Lzr,methodName:Fn.string()});var eNn=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var lwa=Fn.objectWithoutOptionalProperties({isOptional:Fn.boolean(),isArray:Fn.boolean()});var fwa=Fn.union("type",{file:lwa,json:Fn.object({value:Fn.lazy(()=>X1)})}).transform({transform:e=>{switch(e.type){case"file":return g2e.file(e);case"json":return g2e.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var dwa=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:fwa,contentType:Fn.string().optional()}).extend(M_);var tNn=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),properties:Fn.list(dwa)}).extend(M_).extend(xb);var pwa=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1),contentType:Fn.string().optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(xb);var _wa=Fn.union("type",{octetStream:eNn,multipart:tNn,json:pwa}).transform({transform:e=>{switch(e.type){case"octetStream":return Nzr.octetStream(e);case"multipart":return Nzr.multipart(e);case"json":return Nzr.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var rNn=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var Qzr=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1),responseProperty:Fn.string().optional()}).extend(M_).extend(xb);var Jzr=Fn.objectWithoutOptionalProperties({}).extend(M_).extend(xb);var hwa=Fn.union("type",{file:rNn,json:Qzr,text:Jzr,streamingSse:Qzr,streamingText:Jzr,streamingJson:Qzr}).transform({transform:e=>{switch(e.type){case"file":return fae.file(e);case"json":return fae.json(e);case"text":return fae.text(e);case"streamingSse":return fae.streamingSse(e);case"streamingText":return fae.streamingText(e);case"streamingJson":return fae.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var ywa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),description:Fn.string().optional(),example:Fn.lazy(()=>Y2)});var vwa=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>X1).optional(),examples:Fn.list(ywa).optional()}).extend(M_).extend(pO).extend(xb);var nNn=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),url:Fn.string().optional(),audiences:Fn.list(Fn.string()).optional()});var bwa=Fn.unknown();var gwa=Fn.objectWithoutOptionalProperties({name:Fn.string(),parameterNameOverride:Fn.string().optional(),value:Fn.lazy(()=>Y2)});var iNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),value:Fn.lazy(()=>Y2)});var aNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),value:Fn.lazy(()=>Y2)});var mwa=Fn.union("type",{withStreaming:Fn.object({value:Fn.list(Fn.lazy(()=>Y2))}),withoutStreaming:Fn.object({value:Fn.lazy(()=>Y2)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return EIt.withStreaming(e.value);case"withoutStreaming":return EIt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Owa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),language:Fn.string(),code:Fn.string(),install:Fn.string().optional()}).extend(M_);var Pwa=Fn.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var wwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),sdk:Pwa,code:Fn.string()}).extend(M_);var jwa=Fn.union("type",{language:Owa,sdk:wwa}).transform({transform:e=>{switch(e.type){case"language":return RAr.language(e);case"sdk":return RAr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),pathParameters:Fn.list(gwa).optional(),queryParameters:Fn.list(iNn).optional(),headers:Fn.list(aNn).optional(),request:Fn.lazy(()=>Y2).optional(),response:mwa.optional(),codeSamples:Fn.list(jwa)}).extend(M_);var oNn=Fn.union("type",{unknown:Fn.object({value:bwa}),full:Dwa}).transform({transform:e=>{switch(e.type){case"unknown":return SIt.unknown(e.value);case"full":return SIt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Swa=Fn.objectWithoutOptionalProperties({cursor:Fn.string(),nextCursor:Fn.property("next_cursor",Fn.string()),results:Fn.string()});var Ewa=Fn.objectWithoutOptionalProperties({offset:Fn.string(),results:Fn.string(),step:Fn.string().optional(),hasNextPage:Fn.string().optional()});var uNn=Fn.union("type",{cursor:Swa,offset:Ewa}).transform({transform:e=>{switch(e.type){case"cursor":return zAr.cursor(e);case"offset":return zAr.offset(e);default:return e}},untransform:({_visit:e,...t})=>t});var Awa=Fn.objectWithoutOptionalProperties({authed:Fn.boolean(),internal:Fn.boolean().optional(),idempotent:Fn.boolean().optional(),method:X7n,audiences:Fn.list(Fn.string()),path:Fn.string(),summary:Fn.string().optional(),operationId:Fn.string().optional(),tags:Fn.list(EDe),pathParameters:Fn.list(Z7n),queryParameters:Fn.list(k7n),headers:Fn.list(Wzr),sdkName:Hzr.optional(),generatedRequestName:Fn.string(),requestNameOverride:Fn.string().optional(),request:_wa.optional(),response:hwa.optional(),errors:Fn.record(Uzr,vwa),server:Fn.list(nNn),examples:Fn.list(oNn),pagination:uNn.optional()}).extend(M_).extend(hv).extend(xb).extend(Vzr);var Mwa=Fn.enum_(["GET","POST"]);var xwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),payload:Fn.lazy(()=>Y2)}).extend(M_);var Twa=Fn.objectWithoutOptionalProperties({sdkName:Hzr.optional(),method:Mwa,summary:Fn.string().optional(),operationId:Fn.string(),tags:Fn.list(EDe),headers:Fn.list(Wzr),generatedPayloadName:Fn.string(),payload:Fn.lazy(()=>X1),examples:Fn.list(xwa)}).extend(M_).extend(xb).extend(Vzr);var Cwa=Fn.objectWithoutOptionalProperties({queryParameters:Fn.list(k7n),headers:Fn.list(Wzr),pathParameters:Fn.list(Z7n)});var qwa=Fn.objectWithoutOptionalProperties({messageType:Fn.string(),payload:Fn.lazy(()=>Y2)}).extend(M_);var Iwa=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),queryParameters:Fn.list(iNn).optional(),headers:Fn.list(aNn).optional(),messages:Fn.list(qwa)}).extend(M_);var Bwa=Fn.objectWithoutOptionalProperties({path:Fn.string(),groupName:Lzr,summary:Fn.string().optional(),handshake:Cwa,publish:Fn.lazy(()=>X1).optional(),subscribe:Fn.lazy(()=>X1).optional(),examples:Fn.list(Iwa)}).extend(M_).extend(xb);var Nwa=Fn.objectWithoutOptionalProperties({rootSchemas:Fn.record(sk,Fn.lazy(()=>X1)),namespacedSchemas:Fn.record(nwa,Fn.record(sk,Fn.lazy(()=>X1)))});var zwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional()});var Rwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional()});var Fwa=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional()});var Lwa=Fn.objectWithoutOptionalProperties({default:Fn.string().optional(),pattern:Fn.string().optional(),format:Fn.string().optional(),minLength:Fn.number().optional(),maxLength:Fn.number().optional()});var Uwa=Fn.objectWithoutOptionalProperties({default:Fn.boolean().optional()});var Vwa=Fn.union("type",{int:zwa,int64:Rwa,uint:Fn.object({}),uint64:Fn.object({}),float:Fn.object({}),double:Fwa,string:Lwa,datetime:Fn.object({}),date:Fn.object({}),base64:Fn.object({}),boolean:Uwa}).transform({transform:e=>{switch(e.type){case"int":return jD.int(e);case"int64":return jD.int64(e);case"uint":return jD.uint();case"uint64":return jD.uint64();case"float":return jD.float();case"double":return jD.double(e);case"string":return jD.string(e);case"datetime":return jD.datetime();case"date":return jD.date();case"base64":return jD.base64();case"boolean":return jD.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var Gzr=Fn.objectWithoutOptionalProperties({schema:Vwa}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Wwa=Fn.objectWithoutOptionalProperties({header:Fn.string(),name:Fn.string().optional(),optional:Fn.boolean().optional(),env:Fn.string().optional(),schema:Fn.lazy(()=>X1).optional()});var Hwa=Fn.objectWithoutOptionalProperties({header:Fn.string(),name:Fn.string().optional(),env:Fn.string().optional(),schema:Fn.lazy(()=>X1).optional()});var T4f=Fn.objectWithoutOptionalProperties({apiVersion:Fn.unknown().optional(),title:Fn.string().optional(),description:Fn.string().optional(),basePath:Fn.string().optional(),servers:Fn.list(rwa),groups:Fn.record(Fn.string(),swa),tags:cwa,hasEndpointsMarkedInternal:Fn.boolean(),endpoints:Fn.list(Awa),webhooks:Fn.list(Twa),channel:Fn.list(Bwa),groupedSchemas:Nwa,variables:Fn.record(Fn.string(),Gzr),nonRequestReferencedSchemas:Fn.set(sk),securitySchemes:Fn.record(J1a,twa),globalHeaders:Fn.list(Wwa).optional(),idempotencyHeaders:Fn.list(Hwa).optional()});var E9t=Fn.objectWithoutOptionalProperties({schema:sk}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var Qwa=Fn.union("type",{boolean:Fn.object({value:Fn.boolean()}),string:Fn.object({value:Fn.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return DB.boolean(e.value);case"string":return DB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var sNn=Fn.objectWithoutOptionalProperties({value:Qwa}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var X1=Fn.union("type",{primitive:Gzr,object:Fn.lazyObject(()=>Jwa),array:Fn.lazyObject(()=>Gwa),map:Fn.lazyObject(()=>$wa),optional:Fn.lazyObject(()=>Kwa),enum:$7n,reference:E9t,literal:sNn,oneOf:Fn.object({value:Fn.lazy(()=>Xwa)}),nullable:Fn.lazyObject(()=>Ywa),unknown:pO}).transform({transform:e=>{switch(e.type){case"primitive":return gb.primitive(e);case"object":return gb.object(e);case"array":return gb.array(e);case"map":return gb.map(e);case"optional":return gb.optional(e);case"enum":return gb.enum(e);case"reference":return gb.reference(e);case"literal":return gb.literal(e);case"oneOf":return gb.oneOf(e.value);case"nullable":return gb.nullable(e);case"unknown":return gb.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var cNn=Fn.objectWithoutOptionalProperties({propertyKey:Fn.string(),allOfSchemaIds:Fn.list(sk),conflictingTypeSignatures:Fn.boolean()});var Jwa=Fn.objectWithoutOptionalProperties({allOf:Fn.list(E9t),properties:Fn.list(Fn.lazyObject(()=>Zwa)),allOfPropertyConflicts:Fn.list(cNn),additionalProperties:Fn.boolean()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var lNn=Fn.objectWithoutOptionalProperties({differentSchema:Fn.boolean()});var Zwa=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>X1),readonly:Fn.boolean().optional(),conflict:Fn.record(sk,lNn),generatedName:Fn.string(),nameOverride:Fn.string().optional(),audiences:Fn.list(Fn.string())}).extend(hv);var Gwa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var $wa=Fn.objectWithoutOptionalProperties({key:Gzr,value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(K1);var Kwa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Ywa=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>X1)}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var Xwa=Fn.union("type",{discriminated:Fn.lazyObject(()=>kwa),undisciminated:Fn.lazyObject(()=>eja)}).transform({transform:e=>{switch(e.type){case"discriminated":return FAr.discriminated(e);case"undisciminated":return FAr.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var kwa=Fn.objectWithoutOptionalProperties({discriminantProperty:Fn.string(),commonProperties:Fn.list(Fn.lazyObject(()=>tja)),schemas:Fn.record(Fn.string(),Fn.lazy(()=>X1))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var tja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>X1)});var eja=Fn.objectWithoutOptionalProperties({schemas:Fn.list(Fn.lazy(()=>X1))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var E1u={};kc(E1u,{ArraySchemaWithExample:()=>Oja,Base64WithExample:()=>yja,BooleanWithExample:()=>vja,CommonPropertyWithExample:()=>xja,DateWithExample:()=>hja,DatetimeWithExample:()=>_ja,DiscriminatedOneOfSchemaWithExample:()=>Aja,DoubleWithExample:()=>dja,EndpointWithExample:()=>q4f,EnumSchemaWithExample:()=>gja,FloatWithExample:()=>fja,HeaderWithExample:()=>dNn,HttpErrorWithExample:()=>oja,Int64WithExample:()=>sja,IntWithExample:()=>uja,JsonRequestWithExample:()=>nja,JsonResponseWithExample:()=>fgi,MapSchemaWithExample:()=>Pja,NamedFullExample:()=>A9t,NullableSchemaWithExample:()=>jja,ObjectPropertyWithExample:()=>Eja,ObjectSchemaWithExample:()=>Dja,OneOfSchemaWithExample:()=>Sja,OptionalSchemaWithExample:()=>wja,PathParameterWithExample:()=>rja,PrimitiveSchemaValueWithExample:()=>bja,PrimitiveSchemaWithExample:()=>pNn,QueryParameterWithExample:()=>fNn,RequestWithExample:()=>ija,ResponseWithExample:()=>aja,SchemaWithExample:()=>KC,StringSchemaWithExample:()=>pja,Uint64WithExample:()=>lja,UintWithExample:()=>cja,UnDiscriminatedOneOfSchemaWithExample:()=>Mja,UnknownSchemaWithExample:()=>mja,WebsocketHandshakeWithExample:()=>C4f});var A9t=Fn.objectWithoutOptionalProperties({name:Fn.string().optional(),value:Fn.unknown()}).extend(M_);var fNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var dNn=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),env:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var C4f=Fn.objectWithoutOptionalProperties({queryParameters:Fn.list(fNn),headers:Fn.list(dNn)});var rja=Fn.objectWithoutOptionalProperties({name:Fn.string(),schema:Fn.lazy(()=>KC),variableReference:Fn.string().optional(),parameterNameOverride:Fn.string().optional()}).extend(M_).extend(hv).extend(xb);var nja=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>KC),contentType:Fn.string().optional(),fullExamples:Fn.list(A9t).optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(xb);var ija=Fn.union("type",{octetStream:eNn,multipart:tNn,json:nja}).transform({transform:e=>{switch(e.type){case"octetStream":return m2e.octetStream(e);case"multipart":return m2e.multipart(e);case"json":return m2e.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var fgi=Fn.objectWithoutOptionalProperties({schema:Fn.lazy(()=>KC),responseProperty:Fn.string().optional(),fullExamples:Fn.list(A9t).optional()}).extend(M_).extend(xb);var aja=Fn.union("type",{file:rNn,json:fgi,text:Jzr,streamingSse:Qzr,streamingText:Jzr,streamingJson:fgi}).transform({transform:e=>{switch(e.type){case"file":return SB.file(e);case"json":return SB.json(e);case"text":return SB.text(e);case"streamingSse":return SB.streamingSse(e);case"streamingText":return SB.streamingText(e);case"streamingJson":return SB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var oja=Fn.objectWithoutOptionalProperties({statusCode:Uzr,schema:Fn.lazy(()=>KC),fullExamples:Fn.list(A9t).optional()}).extend(M_).extend(pO).extend(xb);var q4f=Fn.objectWithoutOptionalProperties({authed:Fn.boolean(),internal:Fn.boolean().optional(),idempotent:Fn.boolean().optional(),method:X7n,audiences:Fn.list(Fn.string()),path:Fn.string(),summary:Fn.string().optional(),operationId:Fn.string().optional(),tags:Fn.list(EDe),pathParameters:Fn.list(rja),queryParameters:Fn.list(fNn),headers:Fn.list(dNn),sdkName:Hzr.optional(),generatedRequestName:Fn.string(),requestNameOverride:Fn.string().optional(),request:ija.optional(),response:aja.optional(),errors:Fn.record(Uzr,oja),server:Fn.list(nNn),examples:Fn.list(oNn),pagination:uNn.optional()}).extend(M_).extend(hv).extend(xb).extend(Vzr);var uja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional(),example:Fn.number().optional()});var sja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var cja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var lja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),example:Fn.number().optional()});var fja=Fn.objectWithoutOptionalProperties({example:Fn.number().optional()});var dja=Fn.objectWithoutOptionalProperties({default:Fn.number().optional(),minimum:Fn.number().optional(),maximum:Fn.number().optional(),exclusiveMinimum:Fn.boolean().optional(),exclusiveMaximum:Fn.boolean().optional(),multipleOf:Fn.number().optional(),example:Fn.number().optional()});var pja=Fn.objectWithoutOptionalProperties({default:Fn.string().optional(),pattern:Fn.string().optional(),format:Fn.string().optional(),minLength:Fn.number().optional(),maxLength:Fn.number().optional(),example:Fn.string().optional()});var _ja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var hja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var yja=Fn.objectWithoutOptionalProperties({example:Fn.string().optional()});var vja=Fn.objectWithoutOptionalProperties({default:Fn.boolean().optional(),example:Fn.boolean().optional()});var bja=Fn.union("type",{int:uja,int64:sja,uint:cja,uint64:lja,float:fja,double:dja,string:pja,datetime:_ja,date:hja,base64:yja,boolean:vja}).transform({transform:e=>{switch(e.type){case"int":return Ay.int(e);case"int64":return Ay.int64(e);case"uint":return Ay.uint(e);case"uint64":return Ay.uint64(e);case"float":return Ay.float(e);case"double":return Ay.double(e);case"string":return Ay.string(e);case"datetime":return Ay.datetime(e);case"date":return Ay.date(e);case"base64":return Ay.base64(e);case"boolean":return Ay.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var pNn=Fn.objectWithoutOptionalProperties({schema:bja}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(K1);var gja=Fn.objectWithoutOptionalProperties({default:Fzr.optional(),values:Fn.list(Fzr),example:Fn.string().optional()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var mja=Fn.objectWithoutOptionalProperties({example:Fn.unknown()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var KC=Fn.union("type",{primitive:pNn,object:Fn.lazyObject(()=>Dja),array:Fn.lazyObject(()=>Oja),map:Fn.lazyObject(()=>Pja),optional:Fn.lazyObject(()=>wja),enum:gja,reference:E9t,literal:sNn,oneOf:Fn.object({value:Fn.lazy(()=>Sja)}),nullable:Fn.lazyObject(()=>jja),unknown:mja}).transform({transform:e=>{switch(e.type){case"primitive":return Gp.primitive(e);case"object":return Gp.object(e);case"array":return Gp.array(e);case"map":return Gp.map(e);case"optional":return Gp.optional(e);case"enum":return Gp.enum(e);case"reference":return Gp.reference(e);case"literal":return Gp.literal(e);case"oneOf":return Gp.oneOf(e.value);case"nullable":return Gp.nullable(e);case"unknown":return Gp.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC),example:Fn.list(Fn.unknown()).optional()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var Pja=Fn.objectWithoutOptionalProperties({key:pNn,value:Fn.lazy(()=>KC),example:Fn.unknown().optional()}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(dae).extend(K1);var wja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC)}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var jja=Fn.objectWithoutOptionalProperties({value:Fn.lazy(()=>KC)}).extend(Y1).extend(pO).extend(M_).extend(hv).extend(K1);var Dja=Fn.objectWithoutOptionalProperties({allOf:Fn.list(E9t),properties:Fn.list(Fn.lazyObject(()=>Eja)),allOfPropertyConflicts:Fn.list(cNn),fullExamples:Fn.list(A9t).optional(),additionalProperties:Fn.boolean()}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(xb).extend(K1);var Eja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>KC),readonly:Fn.boolean().optional(),audiences:Fn.list(Fn.string()),conflict:Fn.record(sk,lNn),nameOverride:Fn.string().optional(),generatedName:Fn.string()}).extend(hv);var Sja=Fn.union("type",{discriminated:Fn.lazyObject(()=>Aja),undisciminated:Fn.lazyObject(()=>Mja)}).transform({transform:e=>{switch(e.type){case"discriminated":return uk.discriminated(e);case"undisciminated":return uk.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Aja=Fn.objectWithoutOptionalProperties({discriminantProperty:Fn.string(),commonProperties:Fn.list(Fn.lazyObject(()=>xja)),schemas:Fn.record(Fn.string(),Fn.lazy(()=>KC))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);var xja=Fn.objectWithoutOptionalProperties({key:Fn.string(),schema:Fn.lazy(()=>KC)});var Mja=Fn.objectWithoutOptionalProperties({schemas:Fn.list(Fn.lazy(()=>KC))}).extend(M_).extend(pO).extend(Y1).extend(hv).extend(dae).extend(xb).extend(K1);function Tja(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:xc(e.type)}}function _Nn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:xc(e)}}function PC(e){return typeof e=="string"?e:e.type}function dgi(e){if(typeof e!="string")return e.docs}function I4f(e){if(typeof e!="string")return e.default}function B4f(e){if(typeof e!="string")return e.validation}function zG1(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function N4f(e){let t=e?zG1(e):void 0;if(t==null||t.length===0)return _pi;let r=[];for(let[n,i]of t.entries())if(typeof i=="string")r.push(_A(i));else if(typeof i=="object")switch(i.type){case"namespace":{n<t.length-1?r.push(_A(i.name)):r.push(i.name,_pi);break}default:xc(i.type)}else xc(i);return r.join("/")}function hNn(e){return Ms.of(`${N4f(e)}.yml`)}function A1u({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?_pi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,N4f(r))}function z4f({sdkName:e,namespaceOverride:t}){return Ms.of(`${A1u({sdkName:e,namespaceOverride:t})}.yml`)}function R4f({location:e,namespaceOverride:t}){return t!=null?yf(Ms.of(t),e):e}function I3(e){switch(e){case JH.Deprecated:return"deprecated";case JH.Beta:return"pre-release";case JH.GenerallyAvailable:return"generally-available";default:return}}var RG1=-2147483648,FG1=2147483647,LG1=-17976931348623157e292,UG1=17976931348623157e292;function Z1({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i}){switch(e.type){case"primitive":return Cja(e);case"array":return T1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"map":return C1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"reference":return x1u({schema:e,fileContainingReference:t,context:n,namespace:i});case"unknown":return I1u();case"optional":case"nullable":return q1u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"enum":return YG1({schema:e,fileContainingReference:t,context:n,declarationFile:r});case"literal":return e.value,B1u(e);case"object":return XG1({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i});case"oneOf":return ZG1({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i});default:xc(e)}}function Cja(e){switch(e.schema.type){case"string":return HG1({description:e.description,schema:e.schema});case"int":return QG1({description:e.description,schema:e.schema});case"float":return JG1({description:e.description,schema:e.schema});case"double":return GG1({description:e.description,schema:e.schema});case"boolean":return VG1({description:e.description,schema:e.schema});case"int64":return WG1({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function VG1({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function WG1({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function HG1({description:e,schema:t}){let r="string",n=$G1(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function QG1({description:e,schema:t}){let r="integer",n=F4f(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function JG1({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function GG1({description:e,schema:t}){let r="double",n=F4f(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function $G1(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,a=KG1(t);if(!(a==null&&r==null&&n==null&&i==null))return{format:a,pattern:r,minLength:n,maxLength:i}}function KG1(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function F4f(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=M1u(r,t),n=M1u(n,t),i=M1u(i,t),!(r==null&&n==null&&a==null&&u==null&&i==null))return{min:r,max:n,exclusiveMin:a,exclusiveMax:u,multipleOf:i}}function M1u(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[RG1,FG1]:[LG1,UG1];return e<r||e>n?void 0:e}function x1u({schema:e,fileContainingReference:t,context:r,namespace:n}){let i=r.getSchema(e.schema,n);if(i==null)return"unknown";let a=kG1(i)??e.schema,u=_Nn(i),f=e$1(i),d=qja({context:r,fileContainingReference:t,declarationFile:hNn(u),type:a}),c=i.type==="nullable"?`optional<${d}>`:d;return e.description==null&&f==null?c:{type:i.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function T1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),u=`list<${PC(a)}>`;return e.description==null&&e.title==null?u:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{},type:u}}function C1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Cja(e.key),u=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),f=e.encoding!=null?Tja(e.encoding):void 0,d=`map<${PC(a)}, ${PC(u)}>`;if(e.description==null&&f==null&&e.title==null)return d;let c={type:d};return e.description!=null&&(c.docs=e.description),e.encoding!=null&&(c.encoding=f),e.availability!=null&&(c.availability=I3(e.availability)),c}function q1u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=Z1({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i}),u=PC(a),f=dgi(a),d=I4f(a),c=B4f(a),o=u.startsWith("optional<")?u:`optional<${u}>`;if(e.availability==null&&e.description==null&&f==null&&d==null&&c==null&&e.title==null)return o;let l={type:o};return(e.description!=null||f!=null)&&(l.docs=e.description??f),d!=null&&(l.default=d),c!=null&&(l.validation=c),e.availability!=null&&(l.availability=I3(e.availability)),l}function I1u(){return"unknown"}function B1u(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:xc(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function YG1({schema:e,fileContainingReference:t,declarationFile:r,context:n}){let i=pgi(e),a=e.nameOverride??e.generatedName;n.builder.addType(r,{name:a,schema:i.schema});let u=qja({type:a,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return u;let f={type:u};return e.description!=null&&(f.docs=e.description),e.default!=null&&(f.default=e.default.value),e.availability!=null&&(f.availability=I3(e.availability)),f}function XG1({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=N1u({schema:e,declarationFile:r,context:n,namespace:i}),u=e.nameOverride??e.generatedName;n.builder.addType(r,{name:u,schema:a.schema});let f=qja({type:u,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function ZG1({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i}){let a=z1u({schema:e,declarationFile:r,context:n,namespace:i}),u=e.nameOverride??e.generatedName;n.builder.addType(r,{name:u,schema:a.schema});let f=qja({type:u,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{...e.title!=null?{"display-name":e.title}:{},type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:I3(e.availability)}:{}}}function qja({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function kG1(e){return gb._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function e$1(e){return gb._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function Ann(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:xc(e)}}function U4f({schema:e,context:t,declarationFile:r,namespace:n}){switch(e.type){case"primitive":return n$1(e);case"array":return t$1({schema:e,context:t,declarationFile:r,namespace:n});case"map":return r$1({schema:e,context:t,declarationFile:r,namespace:n});case"reference":return i$1({schema:e,context:t,declarationFile:r,namespace:n});case"unknown":return o$1(e.nameOverride,e.generatedName);case"optional":case"nullable":return a$1({schema:e,context:t,declarationFile:r,namespace:n});case"enum":return pgi(e);case"literal":return u$1(e,e.nameOverride,e.generatedName);case"object":return N1u({schema:e,context:t,declarationFile:r,namespace:n});case"oneOf":return z1u({schema:e.value,context:t,declarationFile:r,namespace:n});default:xc(e)}}function N1u({schema:e,context:t,declarationFile:r,namespace:n}){let i={},a=new Set;for(let c of e.properties){if(Object.keys(c.conflict).length>0){if(Object.entries(c.conflict).every(([j,M])=>!M.differentSchema))continue;Object.entries(c.conflict).forEach(([j])=>{R1u({property:c.key,schemaId:j,context:t,namespace:n}).forEach(q=>{a.add(q)})})}let o=Z1({schema:c.schema,context:t,fileContainingReference:r,namespace:n}),l=c.audiences,g=c.nameOverride,O=I3(c.availability);i[c.key]=l$1(o,l,g,O)}let u=new Set;for(let c of e.allOfPropertyConflicts)c.allOfSchemaIds.forEach(o=>a.add(o)),c.conflictingTypeSignatures&&u.add(c.propertyKey);let f=[];for(let c of e.allOf){let o=V4f({schema:c.schema,context:t,namespace:n});if(o==null||a.has(c.schema)||a.has(o))continue;let l=Z1({schema:gb.reference(c),context:t,fileContainingReference:r,namespace:n});f.push(PC(l))}for(let c of a){let o=F1u(t,c,n);for(let l of o.properties)i[l.key]==null&&(u.has(l.key)&&(i[l.key]="unknown"),i[l.key]=Z1({schema:l.schema,context:t,fileContainingReference:r,namespace:n}));for(let l of o.allOf){if(a.has(l.schema))continue;let g=Z1({schema:gb.reference(l),context:t,fileContainingReference:r,namespace:n});f.push(PC(g))}}let d={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(i).map(([c,o])=>c$1(c)?[c,typeof o=="string"?{type:o,name:`_${c}`}:{...o,name:`_${c}`}]:[c,o]))};return f.length>0&&(d.extends=f),e.additionalProperties&&(d["extra-properties"]=!0),e.availability!=null&&(d.availability=I3(e.availability)),e.source!=null&&(d.source=Ann(e.source)),{name:e.nameOverride??e.generatedName,schema:d}}function R1u({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return R1u({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:a,allOf:u}=F1u(r,t,n),f=a.some(c=>c.key===e),d=[...u.flatMap(c=>R1u({property:e,context:r,schemaId:c.schema,namespace:n}))];if(f||d.length>0)return[t,...d]}return[]}function F1u(e,t,r){let n=e.getSchema(t,r);if(n==null)return{properties:[],allOf:[]};if(n.type==="object")return{properties:n.properties,allOf:n.allOf};if(n.type==="reference")return F1u(e,n.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${n.type}`)}function t$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:T1u({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n})}}function r$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:C1u({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n})}}function n$1(e){let t=Cja(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function L4f(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function pgi(e){let t={enum:e.values.map(i=>{let a=i.nameOverride??i.generatedName,u=i.value;if(a===u&&i.description==null&&(i.casing==null||L4f(i.casing)))return a;let f={value:i.value};if(a!==u&&(f.name=a),i.description!=null&&(f.docs=i.description),i.casing!=null&&!L4f(i.casing)){let d={},c=!1;i.casing.camel!=null&&(d.camel=i.casing.camel,c=!0),i.casing.screamingSnake!=null&&(d["screaming-snake"]=i.casing.screamingSnake,c=!0),i.casing.snake!=null&&(d.snake=i.casing.snake,c=!0),i.casing.pascal!=null&&(d.pascal=i.casing.pascal,c=!0),c&&(f.casing=d)}return f})};e.description!=null&&(t.docs=e.description),e.default!=null&&(t.default=e.default.value);let r=new Set,n={...t,enum:[],source:e.source!=null?Ann(e.source):void 0};for(let i of t.enum){let a=typeof i=="string"?i:i.name??i.value;r.has(a.toLowerCase())||(n.enum.push(i),r.add(a.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function i$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:x1u({schema:e,context:t,fileContainingReference:r,namespace:n})}}function a$1({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:q1u({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n})}}function o$1(e,t){return{name:e??t,schema:I1u()}}function u$1(e,t,r){return{name:t??r,schema:B1u(e)}}function z1u({schema:e,context:t,declarationFile:r,namespace:n}){let i=e.encoding!=null?Tja(e.encoding):void 0;if(e.type==="discriminated"){let u={};for(let d of e.commonProperties)u[d.key]=Z1({schema:d.schema,fileContainingReference:r,context:t,namespace:n});let f={};for(let[d,c]of Object.entries(e.schemas))f[d]=Z1({schema:c,context:t,fileContainingReference:r,namespace:n});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":u,docs:e.description??void 0,availability:e.availability!=null?I3(e.availability):void 0,union:f,encoding:i,source:e.source!=null?Ann(e.source):void 0}}}let a=[];for(let u of e.schemas)a.push(Z1({schema:u,fileContainingReference:r,context:t,namespace:n}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:a,encoding:i,source:e.source!=null?Ann(e.source):void 0}}}var s$1=/^[0-9]/;function c$1(e){return s$1.test(e)}function V4f({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?V4f({context:t,schema:n.schema,namespace:r}):e}function l$1(e,t,r,n){return t.length===0&&r==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{}}}function W4f(e){let t=e.replace(/^x-|^X-/,"");return _A(t)}var H4f="BasicAuthScheme",Ija="BearerAuthScheme";function Q4f(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),e.builder.addAuthScheme({name:H4f,schema:i}),t||(e.builder.setAuth(H4f),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),e.builder.addAuthScheme({name:Ija,schema:i}),t||(e.builder.setAuth(Ija),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??W4f(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:Ija,schema:i}),t||(e.builder.setAuth(Ija),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(Ms.of("__package__.yml"),{name:"OauthScope",schema:pgi(n.scopesEnum).schema})}}function M9t({header:e,context:t,fileContainingReference:r,namespace:n}){let i=Z1({schema:e.schema,context:t,fileContainingReference:r,namespace:n}),a=PC(i),u=e.name.replace(/^x-|^X-/,""),f=e.parameterNameOverride!=null?e.parameterNameOverride:_A(u);if(e.description==null&&e.name===f&&e.env==null&&e.availability==null)return a;let d={type:a};return f!==e.name&&(d.name=f),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=I3(e.availability)),d}function Bja({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Z1({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(e.variableReference==null&&e.description==null&&e.availability==null)return PC(i);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:PC(i)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=I3(e.availability)),a}var xxu=require("fs/promises");var J4f={naming:"v1"};function hh(e,t){let r=Array.isArray(t)?t:[t];for(let n of r){let i=e[n];if(i!=null)return i}}function _gi(e,t,r,n,i=[]){try{let a=hh(e,t);if(a!=null)return r.parse(a)}catch{let u=W8t(i).join(" -> ");n.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}var Nja={of(e){return e}};var kh={SDK_METHOD_NAME:Nja.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:Nja.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:Nja.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};function wy(e){return e.$ref!=null}function O2e(e){switch(hh(e,kh.AVAILABILITY)){case"deprecated":return JH.Deprecated;case"beta":return JH.Beta;case"generally-available":return JH.GenerallyAvailable;default:break}if(!wy(e)&&e.deprecated)return JH.Deprecated}var ADe={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};function G4f({schema:e,logger:t}){return hh(e,kh.ENCODING)??void 0}function $4f(e){return hh(e,kh.FERN_ENUM)}function K4f({nameOverride:e,generatedName:t,title:r,schema:n,description:i,availability:a}){let u=hh(n,kh.SDK_GROUP_NAME),f=hh(n,kh.TYPE_DEFINITION);if(f!=null)return hgi({fernType:f,nameOverride:e,generatedName:t,title:r,description:i,availability:a,groupName:typeof u=="string"?[u]:u})}function hgi({fernType:e,nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u}){return O$({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>{switch(f.v1){case"BASE_64":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.base64({example:void 0})});case"BOOLEAN":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.boolean({default:void 0,example:void 0})});case"DATE":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.date({example:void 0})});case"DATE_TIME":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.datetime({example:void 0})});case"FLOAT":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.float({example:void 0})});case"DOUBLE":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.uint({default:void 0,example:void 0})});case"INTEGER":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.uint64({default:void 0,example:void 0})});case"LONG":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Gp.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,groupName:u,schema:Ay.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:xc(f.v1)}},unknown:()=>Gp.unknown({nameOverride:t,generatedName:r,title:n,example:void 0,description:i,availability:a,groupName:u}),map:({keyType:f,valueType:d})=>f?.type==="primitive"&&d!=null?Gp.map({nameOverride:t,generatedName:r,title:n,key:f,value:d,description:i,availability:a,groupName:u,encoding:void 0,example:void 0}):void 0,list:f=>f!=null?Gp.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u,example:void 0}):void 0,optional:f=>f!=null?Gp.optional({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u}):void 0,set:f=>f!=null?Gp.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,groupName:u,example:void 0}):void 0,literal:f=>Gp.literal({nameOverride:t,generatedName:r,title:n,value:f._visit({string:d=>DB.string(d),boolean:d=>DB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:i,availability:a,groupName:u}),named:()=>{}}})}function Mnn(e){if(e!=null&&typeof e=="boolean")return e}function Y4f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,additionalProperties:i,description:a,availability:u,wrapAsNullable:f,context:d,groupName:c,example:o,encoding:l,source:g,namespace:O}){return typeof i=="boolean"||yNn(i)?zja({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:Gp.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:c,example:o,encoding:l}):zja({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:a1(i,d.options.optionalAdditionalProperties?f:!1,d,[...n,"Value"],g,O),groupName:c,example:o,encoding:l})}function zja({nameOverride:e,generatedName:t,title:r,keySchema:n,valueSchema:i,wrapAsNullable:a,description:u,availability:f,groupName:d,example:c,encoding:o}){return a?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.map({nameOverride:e,generatedName:t,title:r,description:u,availability:n.availability,key:n,value:i,groupName:d,encoding:o,example:c}),description:u,availability:f,groupName:d}):Gp.map({nameOverride:e,generatedName:t,title:r,description:u,availability:f,key:n,value:i,groupName:d,encoding:o,example:c})}function yNn(e){return e==null?!1:typeof e=="boolean"?e:!wy(e)&&Object.keys(e).length===0}function X4f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,item:i,description:a,availability:u,wrapAsNullable:f,context:d,groupName:c,example:o,source:l,namespace:g}){let O=i==null?Gp.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:c}):a1(i,!1,d,[...n,"Item"],l,g);return f$1({nameOverride:e,generatedName:t,title:r,groupName:c,itemSchema:O,wrapAsNullable:f,description:a,availability:u,example:o})}function f$1({nameOverride:e,generatedName:t,title:r,itemSchema:n,wrapAsNullable:i,description:a,availability:u,groupName:f,example:d}){return i?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.array({nameOverride:e,generatedName:t,title:r,value:n,description:a,availability:u,groupName:f,example:d}),description:a,availability:u,groupName:f}):Gp.array({nameOverride:e,generatedName:t,title:r,value:n,description:a,availability:u,groupName:f,example:d})}function L1u({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:u,required:f,wrapAsNullable:d,discriminator:c,context:o,groupName:l,encoding:g,source:O,namespace:P}){let j=c.propertyName,M=Object.fromEntries(Object.entries(c.mapping??{}).map(([B,I])=>{let C=vNn({$ref:I},!1,o,[I],g,O,P);return o.markReferencedByDiscriminatedUnion({$ref:I},j,1),[B,C]})),q=Object.entries(i).filter(([B])=>B!==j).map(([B,I])=>{let C=f!=null&&f.includes(B),F=a1(I,!C,o,[...n,B],O,P);return{key:B,schema:F}});return Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:q,description:a,availability:u,discriminant:j,subtypes:M,groupName:l,source:O})}function U1u({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:u,required:f,wrapAsNullable:d,discriminant:c,variants:o,context:l,groupName:g,encoding:O,source:P,namespace:j}){let M=Object.fromEntries(Object.entries(o).map(([B,I])=>{if(wy(I)){let C=vNn(I,!1,l,[I.$ref],O,P,j);return l.markReferencedByDiscriminatedUnion(I,c,1),[B,C]}else{let C=$zr(I,!1,l,[...n,B],O,P,j,new Set([c]));return[B,C]}})),q=Object.entries(i).filter(([B])=>B!==c).map(([B,I])=>{let C=f!=null&&f.includes(B),F=a1(I,!C,l,[...n,B],P,j);return{key:B,schema:F}});return Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:q,description:a,availability:u,discriminant:c,subtypes:M,groupName:g,source:P})}function Z4f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,properties:i,description:a,availability:u,discriminant:f,subtypes:d,groupName:c,source:o}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.oneOf(uk.discriminated({description:a,availability:u,discriminantProperty:f,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:i,groupName:c,encoding:void 0,source:o})),groupName:c,description:a,availability:u}):Gp.oneOf(uk.discriminated({description:a,availability:u,discriminantProperty:f,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:i,groupName:c,encoding:void 0,source:o}))}function k4f(e){if(e.proto!=null)return V7n.protobuf({typeName:e.proto.type})}var d$1=/^(\d+)/;function Rja(e){let t=e.match(d$1);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let a=bNn(i);return n.length>0?`${a}_${n}`:a}}}function bNn(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],n=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),f=e%10;return f===0?n[u]:`${n[u]}_${t[f]}`}if(e<1e3){let u=Math.floor(e/100),f=e%100;return f===0?`${t[u]}_hundred`:`${t[u]}_hundred_${bNn(f)}`}let i=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[i]}_thousand`:`${t[i]}_thousand_${bNn(a)}`}var gNn=/^[a-zA-Z][a-zA-Z0-9_]*$/;function Kzr({nameOverride:e,generatedName:t,title:r,fernEnum:n,enumVarNames:i,enumValues:a,_default:u,description:f,availability:d,wrapAsNullable:c,groupName:o,context:l,source:g}){let O=h$1(i??[]),P=new Set(a),j=Array.from(P).map((q,B)=>{let I=n?.[q],C=O[B],F=gNn.test(q),K=I?.name??C,ee=F?q:ygi(q);return K!=null&&!gNn.test(K)&&(l?.logger.warn(`Enum name override ${K} is not a valid name. Falling back on ${ee}.`),K=void 0),{nameOverride:K,generatedName:ee,value:q,description:I?.description,availability:d,casing:{snake:I?.casing?.snake??void 0,pascal:I?.casing?.pascal??void 0,screamingSnake:I?.casing?.screamingSnake??void 0,camel:I?.casing?.camel??void 0}}}),M=u!=null?j.find(q=>q.value===u):void 0;return p$1({wrapAsNullable:c,nameOverride:e,generatedName:t,title:r,values:j,_default:M,description:f,availability:d,groupName:o,source:g})}function p$1({wrapAsNullable:e,nameOverride:t,generatedName:r,title:n,values:i,_default:a,description:u,availability:f,groupName:d,source:c}){return e?Gp.nullable({nameOverride:t,generatedName:r,title:n,value:Gp.enum({nameOverride:t,generatedName:r,title:n,values:i,description:u,default:a,availability:f,example:void 0,groupName:d,source:c}),description:u,availability:f,groupName:d}):Gp.enum({nameOverride:t,generatedName:r,title:n,values:i,description:u,availability:f,default:a,example:void 0,groupName:d,source:c})}var _$1={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function ygi(e){let t=Rja(e),r=_$1[e];return t!=null?rH(_A(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":rH(_A(e)))}function h$1(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(n=>n[r]===t[r]);)r++;return e.map(n=>n.substring(r))}function e3f({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,description:o,availability:l,wrapAsNullable:g,example:O,groupName:P}){return n==="int64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P})}function t3f(e){return typeof e=="string"?DB.string(e):typeof e=="boolean"?DB.boolean(e):DB.string(`${e}`)}function r3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,value:i,description:a,availability:u,groupName:f}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.literal({nameOverride:e,generatedName:t,title:r,value:t3f(i),description:a,availability:u,groupName:f}),description:a,availability:u,groupName:f}):Gp.literal({nameOverride:e,generatedName:t,title:r,value:t3f(i),description:a,availability:u,groupName:f})}function V1u({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,description:o,availability:l,wrapAsNullable:g,example:O,groupName:P}){return n==null||n==="double"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.double({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="float"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="int32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int({default:i,minimum:a,maximum:u,exclusiveMinimum:f,exclusiveMaximum:d,multipleOf:c,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="int64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.int64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint32"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="uint64"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.uint64({default:i,example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):n==="time-delta"?wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P}):wU({nameOverride:e,generatedName:t,title:r,primitive:Ay.float({example:O}),wrapAsNullable:g,description:o,availability:l,groupName:P})}var y$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},v$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},b$1={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},g$1={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},m$1={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},O$1={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},P$1={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},w$1={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function Fja(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],n=[y$1,v$1,b$1,g$1,m$1,O$1,P$1,w$1],i;do{i=t;for(let a of n)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:f}=a.applyStrategy(t);t=u,r=[...r,...f]}}while(t.join("")!==i.join(""));return r}function WF(e){let t=e.join("_"),r=rH(_A(t));return/^\d/.test(r)?Rja(r)??r:r}function W1u(e){let t=e.join("_");return _A(t)}function YC(e){switch(e.type){case"object":return gb.object({allOf:e.allOf,properties:e.properties.map(t=>D$1(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source});case"array":return gb.array({description:e.description,availability:e.availability,value:YC(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"enum":return gb.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source});case"literal":return gb.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return gb.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:YC(e.value),groupName:e.groupName});case"optional":return gb.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:YC(e.value),groupName:e.groupName});case"primitive":return gb.primitive({description:e.description,availability:e.availability,schema:n3f(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return gb.map({description:e.description,availability:e.availability,key:gb.primitive({description:e.key.description,availability:e.key.availability,schema:n3f(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:YC(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding});case"reference":return gb.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return gb.oneOf(j$1(e.value));case"unknown":return gb.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:xc(e)}}function j$1(e){switch(e.type){case"discriminated":return FAr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:YC(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,YC(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source});case"undisciminated":return FAr.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>YC(t)),groupName:e.groupName,encoding:e.encoding,source:e.source});default:xc(e)}}function n3f(e){switch(e.type){case"string":return jD.string(e);case"base64":return jD.base64();case"boolean":return jD.boolean(e);case"date":return jD.date();case"datetime":return jD.datetime();case"double":return jD.double(e);case"float":return jD.float();case"int":return jD.int(e);case"int64":return jD.int64(e);case"uint":return jD.uint();case"uint64":return jD.uint64();default:xc(e)}}function D$1(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:YC(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function Lja(e,t){return MDe(YC(e),YC(t))}function MDe(e,t){return e.type==="primitive"&&t.type==="primitive"?i3f(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?S$1(e.values,t.values):e.type==="array"&&t.type==="array"?MDe(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?MDe(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?E$1(e.value,t.value):e.type==="object"&&t.type==="object"?A$1(e,t):e.type==="map"&&t.type==="map"?i3f(e.key.schema,t.key.schema)&&MDe(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function i3f(e,t){return e.type===t.type}function S$1(e,t){let r=new Set(...e.map(i=>i.value)),n=new Set(...t.map(i=>i.value));return Yqt(r,n)}function E$1(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,n])=>{let i=t.schemas[r];return i==null?!1:MDe(n,i)}):e.type==="undisciminated"&&t.type==="undisciminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,n)=>{let i=t.schemas[n];return i==null?!1:MDe(r,i)}):!1}function A$1(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(n=>[n.key,n.schema]));return Object.entries(t.properties).every(([n,i])=>{let a=r[n];return a==null?!1:MDe(a,i.schema)})}function a3f({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,required:u,wrapAsNullable:f,allOf:d,context:c,propertiesToExclude:o,groupName:l,fullExamples:g,additionalProperties:O,availability:P,encoding:j,source:M,namespace:q}){let B=[...u??[]],I={...i},C=[],F=[];for(let G of d)if(wy(G)){let te=c.resolveSchemaReference(G);if(te.discriminator!=null&&te.discriminator.mapping!=null)continue;if(te.oneOf!=null){for(let Re of te.oneOf){let wt=wy(Re)?c.resolveSchemaReference(Re):Re,Ct=a1(wt,!1,c.DUMMY,n,M,q);Ct.type==="object"&&C.push(...Ct.properties.map(Wt=>Wt.schema.type!=="optional"&&Wt.schema.type!=="nullable"?{...Wt,schema:Gp.optional({nameOverride:void 0,generatedName:"",title:void 0,value:Wt.schema,description:void 0,availability:Wt.availability,groupName:void 0})}:Wt))}continue}let Ye=Yzr(G);if(Ye==null)continue;F.push({schemaId:Ye,convertedSchema:H1u(G,[Ye],M),properties:o3f({schema:G,context:c,breadcrumbs:n,source:M,namespace:q})}),c.markSchemaAsReferencedByNonRequest(Ye)}else{let te=a1(G,!1,c,n,M,q);te.type==="object"&&C.push(...te.properties)}let K={};for(let G of F)for(let[te,Ye]of Object.entries(G.properties)){let Re=K[te];Re!=null?(Re.schemaIds.push(G.schemaId),Re.schemas.some(Ct=>Lja(Ct,Ye))||Re.schemas.push(Ye)):K[te]={schemaIds:[G.schemaId],schemas:[Ye]}}let ee=[];for(let[G,te]of Object.entries(K))te.schemaIds.length>1&&ee.push({propertyKey:G,allOfSchemaIds:te.schemaIds,conflictingTypeSignatures:te.schemas.length>1});let J=Object.entries(I).map(([G,te])=>{let Ye=B.includes(G),Re=hh(te,kh.AUDIENCES)??[],wt=O2e(te),Ct=wy(te)?!1:te.readOnly,Wt=hh(te,kh.FERN_PROPERTY_NAME),Bt=[...n,G],or=W1u(Bt),jr=Ye?a1(te,!1,c,Bt,M,q):Gp.optional({nameOverride:e,generatedName:or,title:r,description:void 0,availability:wt,value:a1(te,!1,c,Bt,M,q),groupName:l}),Vr={};for(let It of F){let cr=It.properties[G];cr!=null&&!Lja(jr,cr)?Vr[It.schemaId]={differentSchema:!0}:cr!=null&&(Vr[It.schemaId]={differentSchema:!1})}return{key:G,schema:jr,nameOverride:Wt,audiences:Re,conflict:Vr,generatedName:W1u([...n,G]),availability:wt,readonly:Ct}});return J.push(...C.map(G=>{let te=G.conflict;for(let Ye of F){let Re=Ye.properties[G.key];Re!=null&&!Lja(G.schema,Re)?te[Ye.schemaId]={differentSchema:!0}:Re!=null&&(te[Ye.schemaId]={differentSchema:!1})}return{...G,conflict:te}})),M$1({nameOverride:e,generatedName:t,title:r,wrapAsNullable:f,properties:J.filter(G=>!o.has(G.key)),description:a,allOf:F.map(G=>G.convertedSchema),allOfPropertyConflicts:ee,groupName:l,fullExamples:g,additionalProperties:O,availability:P,source:M})}function M$1({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,properties:i,description:a,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:o,availability:l,source:g}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.object({description:a,properties:i,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:yNn(o),availability:void 0,source:g}),description:a,availability:l,groupName:d}):Gp.object({description:a,properties:i,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:f,groupName:d,fullExamples:c,additionalProperties:yNn(o),availability:l,source:g})}function o3f({schema:e,context:t,breadcrumbs:r,source:n,namespace:i}){let a={},[u,f]=wy(e)?[t.resolveSchemaReference(e),Fja(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...o3f({schema:d,context:t,breadcrumbs:f,source:n,namespace:i})};for(let[d,c]of Object.entries(u.properties??{})){let o=a1(c,!1,t,[...f,d],n,i);a[d]=o}return a}function mNn({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,description:i,availability:a,wrapAsNullable:u,context:f,subtypes:d,groupName:c,encoding:o,source:l,subtypePrefixOverrides:g,namespace:O}){let P=x$1({schemas:d}),j=d.flatMap((B,I)=>{if(!wy(B)&&B.enum!=null&&f.options.cooerceEnumsToLiterals)return B.enum.map(F=>Gp.literal({nameOverride:void 0,generatedName:WF([t,F]),title:void 0,value:DB.string(F),groupName:void 0,description:void 0,availability:F.availability}));let C=P[I];if(g!=null){let F=g[I];F!=null&&"name"in F&&(C=F.name)}return[a1(B,!1,f,[...n,C??`${I}`],l,O)]}),M=[];for(let B=0;B<j.length;++B){let I=j[B],C=!1;for(let F=B+1;F<j.length;++F){let K=j[F];if(I!=null&&K!=null&&MDe(I,K)){C=!0;break}}I!=null&&!C&&M.push(I)}if(Object.entries(M).every(([B,I])=>I.type==="literal")){let B={},I=[];return Object.entries(M).forEach(([C,F])=>{F.type==="literal"&&F.value.type==="string"&&(I.push(F.value.value),F.description!=null&&(B[F.value.value]={description:F.description}))}),Kzr({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:i,availability:a,fernEnum:B,enumVarNames:void 0,enumValues:I,_default:void 0,groupName:c,context:f,source:l})}return M.length===1&&M[0]!=null?M[0]:u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:i,availability:a,subtypes:M,groupName:c,encoding:o,source:l})}function Q1u({nameOverride:e,generatedName:t,title:r,description:n,availability:i,wrapAsNullable:a,context:u,groupName:f,discriminator:d,encoding:c,source:o,namespace:l}){let g=Object.entries(d.mapping??{}).map(([j,M],q)=>{let B={$ref:M},I=vNn(B,!1,u,[M],c,o,l);return u.markSchemaWithDiscriminantValue(B,d.propertyName,j),I.type==="object"&&(I.properties={[d.propertyName]:Gp.literal({nameOverride:void 0,generatedName:WF([t,j]),title:void 0,value:DB.string(j),groupName:void 0,description:void 0,availability:void 0}),...I.properties.filter(C=>C.key!==d.propertyName)}),I}),O=[];for(let j=0;j<g.length;++j){let M=g[j],q=!1;for(let B=j+1;B<g.length;++B){let I=g[B];if(M!=null&&I!=null&&MDe(M,I)){q=!0;break}}M!=null&&!q&&O.push(M)}if(Object.entries(O).every(([j,M])=>M.type==="literal")){let j={},M=[];return Object.entries(O).forEach(([q,B])=>{B.type==="literal"&&B.value.type==="string"&&(M.push(B.value.value),B.description!=null&&(j[B.value.value]={description:B.description}))}),Kzr({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:n,availability:i,fernEnum:j,enumVarNames:void 0,enumValues:M,_default:void 0,groupName:f,context:u,source:o})}return O.length===1&&O[0]!=null?O[0]:u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:n,availability:i,subtypes:O,groupName:f,encoding:c,source:o})}function x$1({schemas:e}){let t={},r=0;for(let a of e){if(!wy(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),f={},d=u;for(let[c,o]of Object.entries(t)){let l=yXi(o,u);d=yXi(d,o),f[c]=l}f[r]=d,t=f}}r++}let n=[],i=0;for(let a of e){let u=t[i];if(u!=null&&u.length>0){let f=u.sort();if(f[0]!=null){n.push(f[0]),++i;continue}}wy(a)?n.push(bNn(i)??`${i}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?n.push(""):n.push(bNn(i)??`${i}`),++i}return n}function u3f({nameOverride:e,generatedName:t,title:r,wrapAsNullable:n,description:i,availability:a,subtypes:u,groupName:f,encoding:d,source:c}){return n?Gp.nullable({nameOverride:e,generatedName:t,title:r,value:Gp.oneOf(uk.undisciminated({description:i,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:f,encoding:d,source:c})),description:i,availability:a,groupName:f}):Gp.oneOf(uk.undisciminated({description:i,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:f,encoding:d,source:c}))}function ONn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function Uja({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;if(r&&typeof r=="number")return r;r&&t.warn(`Expected fallback to be a number, but got ${typeof r}`)}function s3f({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;if(r&&typeof r=="boolean")return r;r&&t.warn(`Expected fallback to be a boolean, but got ${typeof r}`)}function x9t({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;if(r&&typeof r=="string")return r;r&&t.warn(`Expected fallback to be a string, but got ${typeof r}`)}function c3f({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;if(r&&Array.isArray(r))return r;r&&t.warn(`Expected fallback to be a array, but got ${typeof r}`)}var xnn="#/components/schemas/";function a1(e,t,r,n,i,a,u=!1,f=new Set,d){let c=z$1({schema:e,logger:r.logger});if(wy(e)){let o=Yzr(e);return o!=null?(u?r.markSchemaAsReferencedByRequest(o):r.markSchemaAsReferencedByNonRequest(o),vNn(e,t,r,n,c,i,a)):$zr(r.resolveSchemaReference(e),t,r,Fja(e.$ref),c,i,a,f,u,d)}return $zr(e,t,r,n,c,i,a,f,u,d)}function vNn(e,t,r,n,i,a,u){let f=e.$ref.includes("properties")?$zr(r.resolveSchemaReference(e),t,r,n,i,a,u,new Set):Gp.reference(H1u(e,n,a));return t?Gp.nullable({title:void 0,nameOverride:void 0,generatedName:WF(n),value:f,description:void 0,availability:void 0,groupName:void 0}):f}function T$1(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function $zr(e,t,r,n,i,a,u,f=new Set,d=!1,c){let o=hh(e,kh.TYPE_NAME)??(r.options.useTitlesAsName?T$1(e.title):void 0),l=hh(e,kh.SDK_GROUP_NAME)??hh(e,ADe.TAGS)?.[0],g=(typeof l=="string"?[l]:l)??[];g=r.resolveGroupName(g);let O=WF(n),P=e.title,j=e.description,M=O2e(e),q=hh(e,ADe.EXAMPLES),B=[];e.example!=null&&B.push({name:void 0,value:e.example,description:void 0}),q!=null&&Object.keys(q).length>0&&B.push(...Object.entries(q).map(([C,F])=>({name:F.summary??C,value:F.value,description:F.description})));let I=K4f({schema:e,description:j,title:P,nameOverride:o,generatedName:O,availability:M});if(I!=null)return I;if(!t&&e.nullable===!0)return $zr(e,!0,r,n,i,a,u,f,d,c);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!vgi(e.enum))return wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.string({default:ONn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g,wrapAsNullable:t,description:j,availability:M});let C=$4f(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?r3f({nameOverride:o,generatedName:O,title:P,wrapAsNullable:t,value:e.enum[0],description:j,availability:M,groupName:g}):Kzr({nameOverride:o,generatedName:O,title:P,fernEnum:C,enumVarNames:hh(e,[ADe.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:j,availability:M,wrapAsNullable:t,groupName:g,context:r,source:a})}if(vgi(e.type)&&e.type[1]!=null&&e.type[0]!=null){let C=e.type[0],F=e.type[1];if(C==="null")return Gp.nullable({nameOverride:o,generatedName:O,title:P,value:$zr({...e,type:F},t,r,n,i,a,u,f,d,c),groupName:g,description:e.description,availability:M});if(F==="null")return Gp.nullable({nameOverride:o,generatedName:O,title:P,value:$zr({...e,type:C},t,r,n,i,a,u,f,d,c),groupName:g,description:e.description,availability:M})}if(vgi(e.type)&&e.type.length>1){let C=e.type.includes("null"),F=e.type.filter(K=>K!=="null").map(K=>({type:K,nullable:C}));return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t,context:r,subtypes:F,groupName:g,encoding:i,source:a,namespace:u})}if(e==="boolean"||e.type==="boolean"){let C=hh(e,kh.BOOLEAN_LITERAL);return C!=null?f3f({nameOverride:o,generatedName:O,title:P,literal:DB.boolean(C),wrapAsNullable:t,description:j,availability:M,groupName:g}):wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.boolean({default:e.default,example:s3f({schema:e,logger:r.logger,fallback:c})}),wrapAsNullable:t,description:j,availability:M,groupName:g})}if(e==="number"||e.type==="number")return V1u({nameOverride:o,generatedName:O,title:P,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="integer"||e.type==="integer")return e3f({nameOverride:o,generatedName:O,title:P,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="float")return V1u({nameOverride:o,generatedName:O,title:P,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Mnn(e.exclusiveMinimum),exclusiveMaximum:Mnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:j,availability:M,wrapAsNullable:t,example:Uja({schema:e,logger:r.logger,fallback:c}),groupName:g});if(e==="string"||e.type==="string"){if(e.format==="date-time")return wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.datetime({example:x9t({schema:e,logger:r.logger,fallback:c})}),wrapAsNullable:t,description:j,availability:M,groupName:g});if(e.format==="json-string")return Gp.unknown({nameOverride:o,generatedName:O,title:P,description:j,availability:M,groupName:g,example:void 0});let C=_3f(e,"const");return C!=null?f3f({nameOverride:o,generatedName:O,title:P,literal:DB.string(C),wrapAsNullable:t,description:j,availability:M,groupName:g}):wU({nameOverride:o,generatedName:O,title:P,primitive:Ay.string({default:ONn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g,wrapAsNullable:t,description:j,availability:M})}if(e.type==="array")return X4f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,item:e.items,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,example:c3f({schema:e,logger:r.logger,fallback:c}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&l3f(e))return Y4f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,additionalProperties:e.additionalProperties,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,encoding:i,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?Q1u({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,discriminator:e.discriminator,encoding:i,source:a,namespace:u}):L1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:g,encoding:i,source:a,namespace:u});if(Array.isArray(e.type)&&(e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type)),e.oneOf!=null&&e.oneOf.length>0){let C=hh(e,kh.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?Q1u({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,context:r,groupName:g,discriminator:e.discriminator,encoding:i,source:a,namespace:u}):L1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:g,encoding:i,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let F=a1(e.oneOf[0],t,r,n,a,u,d);return PNn(F,j,g)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let J=e.oneOf[0],G=e.oneOf[1];if(!wy(J)&&J.type==="null")return a1(G,!0,r,n,a,u);if(!wy(G)&&G.type==="null")return a1(J,!0,r,n,a,u)}let F=I$1({schemas:e.oneOf});if(F!=null)return Kzr({nameOverride:o,generatedName:O,title:P,fernEnum:void 0,enumVarNames:void 0,enumValues:F,_default:e.default,description:j,availability:M,wrapAsNullable:t,groupName:g,context:r,source:a});let K=d3f({schemas:e.oneOf,context:r});if(K!=null&&!r.options.discriminatedUnionV2&&!C)return U1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},required:e.required,description:j,availability:M,wrapAsNullable:t,discriminant:K.discriminant,variants:K.schemas,context:r,groupName:g,encoding:i,source:a,namespace:u});let ee=e.oneOf.filter(J=>!wy(J)&&J.type==="null").length>0;return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t||ee,context:r,subtypes:e.oneOf.filter(J=>wy(J)||J.type!=="null"),encoding:i,groupName:g,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let K=a1(e.anyOf[0],t,r,n,a,u,d);return PNn(K,j,g)}if(e.anyOf.length===2){let[K,ee]=e.anyOf;if(K!=null&&ee!=null){if(!wy(K)&&K.type==="null"){let J=a1(ee,!0,r,n,a,u);return PNn(J,j,g)}else if(!wy(ee)&&ee.type==="null"){let J=a1(K,!0,r,n,a,u);return PNn(J,j,g)}}}let C=d3f({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return U1u({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},required:e.required,description:j,availability:M,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:g,encoding:i,source:a,namespace:u});let F=e.anyOf.filter(K=>!wy(K)&&K.type==="null").length>0;return mNn({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,description:j,availability:M,wrapAsNullable:t||F,context:r,subtypes:e.anyOf.filter(K=>wy(K)||K.type!=="null"),encoding:i,groupName:g,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let K of e.allOf??[])(wy(K)||Object.keys(K).length>0)&&C.push(K);if((e.properties==null||e.properties.length===0)&&C.length===1&&C[0]!=null){let K=a1(C[0],t,r,n,a,u,d);return PNn(K,j,g)}let F=C.filter(K=>{let ee=Vja(K);return ee||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(K)}`),ee});if((e.properties==null||e.properties.length===0)&&F.length===1&&F[0]!=null){let K=a1(F[0],t,r,n,a,u,d);return PNn(K,j,g)}return a3f({nameOverride:o,generatedName:O,title:P,breadcrumbs:n,properties:e.properties??{},description:j,required:e.required,wrapAsNullable:t,allOf:F,context:r,propertiesToExclude:f,groupName:g,fullExamples:B,additionalProperties:e.additionalProperties,availability:M,encoding:i,source:a,namespace:u})}if(e.type==="object"&&C$1(e)&&q$1(e)&&l3f(e))return zja({nameOverride:o,generatedName:O,title:P,description:j,availability:M,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${O}Key`,title:void 0,description:void 0,availability:void 0,schema:Ay.string({default:ONn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:x9t({schema:e,logger:r.logger,fallback:c})}),groupName:g},valueSchema:Gp.unknown({nameOverride:void 0,generatedName:`${O}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:g}),groupName:g,encoding:i,example:e.example});if(e.type==null){let C=e.example??e.default;return Gp.unknown({nameOverride:o,generatedName:O,title:P,description:j,availability:M,groupName:g,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(n)} value=${JSON.stringify(e)}`)}function Yzr(e){if(e.$ref.startsWith(xnn))return e.$ref.replace(xnn,"")}function H1u(e,t,r){let n=hh(e,kh.TYPE_NAME),i=WF(t),a=e.description,u=O2e(e),f=Yzr(e);if(f==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return gb.reference({generatedName:i,nameOverride:n,title:void 0,schema:f,description:a??void 0,availability:u,groupName:void 0,source:r})}function C$1(e){return e.oneOf==null||e.oneOf.length===0}function q$1(e){return e.allOf==null||e.allOf.length===0}function l3f(e){return e.properties==null||Object.keys(e.properties).length===0}function vgi(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function PNn(e,t,r){return e.type==="reference"?Gp.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?Gp.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r}):e.type==="nullable"?Gp.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r}):e}function Vja(e){return wy(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Vja(t)):e.oneOf!=null?e.oneOf.every(t=>Vja(t)):e.anyOf!=null?e.anyOf.every(t=>Vja(t)):!1}function f3f({literal:e,wrapAsNullable:t,groupName:r,description:n,availability:i,nameOverride:a,generatedName:u,title:f}){return t?Gp.nullable({nameOverride:a,generatedName:u,title:f,value:Gp.literal({nameOverride:a,generatedName:u,title:f,value:e,description:n,availability:i,groupName:r}),groupName:r,description:n,availability:i}):Gp.literal({nameOverride:a,generatedName:u,title:f,value:e,groupName:r,description:n,availability:i})}function wU({primitive:e,wrapAsNullable:t,groupName:r,description:n,availability:i,generatedName:a,nameOverride:u,title:f}){return r=typeof r=="string"?[r]:r,t?Gp.nullable({nameOverride:u,generatedName:a,title:f,value:Gp.primitive({nameOverride:u,generatedName:a,title:f,schema:e,description:n,availability:i,groupName:r}),groupName:r,description:n,availability:i}):Gp.primitive({nameOverride:u,generatedName:a,title:f,schema:e,description:n,availability:i,groupName:r})}function I$1({schemas:e}){let t=new Set;for(let r of e){if(wy(r))return;if(r.enum!=null&&vgi(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function d3f({schemas:e,context:t}){let r={};for(let n of e){let i=p3f({schema:n,context:t});for(let[a,u]of Object.entries(i)){let f=r[a];f!=null?f[u]=n:r[a]={[u]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length)return{discriminant:n,schemas:i}}function p3f({schema:e,context:t}){let r=wy(e)?t.resolveSchemaReference(e):e;return B$1({schema:r,context:t})}function B$1({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=p3f({schema:n,context:t});for(let[a,u]of Object.entries(i??{}))r[a]=u}return r}for(let[n,i]of Object.entries(e.properties??{})){let a=wy(i)?t.resolveSchemaReference(i):i;a.type==="string"&&a.enum!=null&&vgi(a.enum)&&N$1(a.enum).length===1&&a.enum[0]!=null&&(r[n]=a.enum[0]);let u=_3f(a,"const");a.type==="string"&&u!=null&&(r[n]=u),n==="type"&&a.example!=null&&(r[n]=a.example)}return r}function N$1(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function _3f(e,t){let r=e[t];if(r!=null)return r}function z$1({schema:e,logger:t}){let r=G4f({schema:e,logger:t});if(r!=null)return k4f(r)}function Wja(e,t){let r={},n={};return e==null?r=t:n={[e]:t},{rootSchemas:r,namespacedSchemas:n}}var h3f="#/components/messages/",J1u=class{logger;document;taskContext;DUMMY;options;namespace;constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(this.document.components==null||this.document.components.schemas==null||!t.$ref.startsWith(xnn))throw new Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(xnn.length).split("/");if(n[0]==null)throw new Error(`${t.$ref} is undefined`);let i=this.document.components.schemas[n[0]];if(i==null)throw new Error(`${n[0]} is undefined`);if(wy(i)&&(i=this.resolveSchemaReference(i)),n[1]==="properties"&&n[2]!=null){let a=i.properties?.[n[2]];if(a==null)throw new Error(`${t.$ref} is undefiened. Property does not exist on object.`);wy(a)?i=this.resolveSchemaReference(a):i=a}return i}resolveMessageReference(t){if(this.document.components==null||this.document.components.messages==null||!t.$ref.startsWith(h3f))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(h3f.length),n=this.document.components.messages[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}},Hja=class extends J1u{constructor({document:t,taskContext:r,options:n,namespace:i}){super({document:t,taskContext:r,options:n,namespace:i})}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}};function Xzr(e){if(typeof e=="string")return i1.primitive(h0.string(e));if(typeof e=="number")return Number.isInteger(e)?i1.primitive(h0.int(e)):i1.primitive(h0.double(e));if(typeof e=="boolean")return i1.primitive(h0.boolean(e));if(Array.isArray(e)){let t=e.map(r=>Xzr(r));return t.length===0?void 0:i1.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=Xzr(n);i!=null&&t.push({key:h0.string(r),value:i})}return i1.map(t)}}function bgi(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function y3f(e){if(e!=null&&Array.isArray(e))return e}var Zzr=class{schemas;constructor(t){this.schemas=t}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:a,options:u,skipReadonly:f}){switch(n.type){case"enum":return typeof r=="string"&&v3f({schema:n,value:r})?i1.enum(r):n.values[0]!=null?i1.enum(n.values[0]?.value):void 0;case"literal":return i1.literal(n.value);case"nullable":{if(r==null&&!this.hasExample(n.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(i,u)))return;let d=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:u,skipReadonly:!1});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(n.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(i,u)))return;let d=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:u,skipReadonly:!1});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:u});return i1.primitive(d)}case"reference":{let d=this.schemas[n.schema];if(d!=null&&!a.has(n.schema)){a.add(n.schema);let c=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:i,options:u,skipReadonly:!1});return a.delete(n.schema),c}return}case"oneOf":switch(n.value.type){case"discriminated":{let d={},c={},o={},l=bgi(r),g=l?.[n.value.discriminantProperty],O=n.value.schemas[g],P=[],j=this.getDiscriminatedUnionVariantSchema(n.value,l);j!=null&&P.push(j),P.push(...Object.entries(n.value.schemas));for(let M of P)if(g!=null&&O!=null&&O.type==="object"){c=this.getAllProperties(O),o=this.getAllRequiredProperties(O),d[n.value.discriminantProperty]=i1.primitive(h0.string(g));break}else{let q=this.getObjectSchema(M[1]);if(q==null)continue;c=this.getAllProperties(q),o=this.getAllRequiredProperties(q),d[n.value.discriminantProperty]=i1.primitive(h0.string(M[0]))}for(let M of n.value.commonProperties){c[M.key]={schema:M.schema,readonly:!1};let q=this.getResolvedSchema(M.schema);q.type!=="optional"&&q.type!=="nullable"&&(o[M.key]=M.schema)}for(let[M,q]of Object.entries(c)){let B=M in o;if(B&&l?.[M]!=null){let I=this.buildExampleHelper({schema:q.schema,exampleId:t,example:l[M],visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});if(I!=null)d[M]=I;else return}else{let I=this.buildExampleHelper({exampleId:t,schema:q.schema,example:l?.[M],visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});if(I!=null)d[M]=I;else if(B)return}}return i1.oneOf(Bzr.discriminated(d))}case"undisciminated":{let d=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:i,options:u,skipReadonly:!1});break}}return;case"unknown":if(r!=null){let d=Xzr(r);if(d!=null)return i1.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(i,u)?void 0:u.isParameter?i1.primitive(h0.string(u.name??"string")):i1.map([{key:h0.string("key"),value:i1.primitive(h0.string("value"))}]);case"array":{let d=y3f(r),c=[];if(d!=null&&d.length>0)for(let o of d){let l=this.buildExampleHelper({exampleId:t,example:o,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});l!=null&&c.push(l)}else if(n.example!=null&&n.example.length>0)for(let o of n.example){let l=this.buildExampleHelper({exampleId:t,example:o,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});l!=null&&c.push(l)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:a,options:u,skipReadonly:!1});o!=null&&c.push(o)}return i1.array(c)}case"map":{let d=bgi(r??n.example);if(d!=null&&Object.entries(d).length>0){let l=[];for(let[g,O]of Object.entries(d)){let P=this.buildExampleFromPrimitive({schema:n.key.schema,example:g,options:u}),j=this.buildExampleHelper({exampleId:t,example:O,schema:n.value,visitedSchemaIds:a,depth:i+1,options:u,skipReadonly:!1});j!=null&&l.push({key:P,value:j})}return i1.map(l)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return i1.map([{key:h0.string("key"),value:i1.unknown(i1.primitive(h0.string("value")))}]);let c=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:a,depth:i+1,options:{...u,name:"value"},skipReadonly:!1});return o!=null?i1.map([{key:c,value:o}]):i1.map([])}case"object":{let d={},c=n.fullExamples?.find(O=>O.name===t)??n.fullExamples?.find(O=>O.name==null)??n.fullExamples?.[0],o=bgi(r)??(c!=null?bgi(c.value):{})??{},l=this.getAllProperties(n),g=this.getAllRequiredProperties(n);for(let[O,P]of Object.entries(l)){if(f&&P.readonly)continue;let j=O in g,M=Object.keys(o).includes(O),q=this.buildExampleHelper({schema:P.schema,exampleId:t,example:o[O],visitedSchemaIds:a,depth:i+1,options:{...u,name:O},skipReadonly:!1});if(j&&q!=null)d[O]=q;else{if(j)return;(M&&q!=null||!u.ignoreOptionals&&q!=null)&&(d[O]=q)}}return i1.object({properties:d})}default:xc(n)}}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return v3f({schema:t,value:r})?5:0;case"object":{if(!lS(r))return 0;let n=this.getAllProperties(t),i=0;for(let[a,u]of Object.entries(n))r[a]!=null?(i++,i+=this.calcExampleHeuristic(u.schema,r[a])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!lS(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,a)=>a-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!n.has(t.schema)){n.add(t.schema);let u=this.hasExample(a,r,n,i);return n.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,n,i));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(r[n.key]=n.schema)}for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?h0.string(t):r.example!=null?h0.string(r.example):h0.string(n.name??aD.STRING);case"base64":return t!=null&&typeof t=="string"?h0.base64(t):r.example!=null?h0.base64(r.example):h0.base64(aD.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?h0.boolean(t):r.example!=null?h0.boolean(r.example):h0.boolean(aD.BOOLEAN);case"date":return t!=null&&typeof t=="string"?h0.date(t):r.example!=null?h0.date(r.example):h0.date(aD.DATE);case"datetime":return t!=null&&typeof t=="string"?h0.datetime(t):r.example!=null?h0.datetime(r.example):h0.datetime(aD.DATE_TIME);case"double":return t!=null&&typeof t=="number"?h0.double(t):r.example!=null?h0.double(r.example):h0.double(aD.DOUBLE);case"float":return t!=null&&typeof t=="number"?h0.float(t):r.example!=null?h0.float(r.example):h0.float(aD.FLOAT);case"int":return t!=null&&typeof t=="number"?h0.int(t):r.example!=null?h0.int(r.example):h0.int(aD.INT);case"int64":return t!=null&&typeof t=="number"?h0.int64(t):r.example!=null?h0.int64(r.example):h0.int64(aD.INT64);case"uint":return t!=null&&typeof t=="number"?h0.uint(t):r.example!=null?h0.uint(r.example):h0.uint(aD.UINT);case"uint64":return t!=null&&typeof t=="number"?h0.uint64(t):r.example!=null?h0.uint64(r.example):h0.uint64(aD.UINT64);default:xc(r)}}};function v3f({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function T9t(e){switch(e.type){case"object":return Gp.object({allOf:e.allOf,properties:e.properties.map(t=>F$1(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source});case"array":return Gp.array({description:e.description,availability:e.availability,value:T9t(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0});case"enum":return Gp.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source});case"literal":return Gp.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return Gp.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:T9t(e.value),groupName:e.groupName});case"optional":return Gp.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:T9t(e.value),groupName:e.groupName});case"primitive":return Gp.primitive({description:e.description,availability:e.availability,schema:b3f(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return Gp.map({description:e.description,availability:e.availability,key:Gp.primitive({description:e.key.description,availability:e.key.availability,schema:b3f(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:T9t(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0});case"reference":return Gp.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return Gp.oneOf(R$1(e.value));case"unknown":return Gp.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:xc(e)}}function R$1(e){switch(e.type){case"discriminated":return uk.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:T9t(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,T9t(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source});case"undisciminated":return uk.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>T9t(t)),groupName:e.groupName,encoding:e.encoding,source:e.source});default:xc(e)}}function b3f(e){switch(e.type){case"string":return Ay.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Ay.base64({example:void 0});case"boolean":return Ay.boolean({default:e.default,example:void 0});case"date":return Ay.date({example:void 0});case"datetime":return Ay.datetime({example:void 0});case"double":return Ay.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Ay.float({example:void 0});case"int":return Ay.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Ay.int64({default:e.default,example:void 0});case"uint":return Ay.uint({default:void 0,example:void 0});case"uint64":return Ay.uint64({default:void 0,example:void 0});default:xc(e)}}function F$1(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:T9t(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function Qja(e){return e.type!=="optional"&&e.type!=="nullable"}function ggi(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var Jja=class{exampleTypeFactory;logger;schemas;constructor(t,r){this.schemas=t,this.exampleTypeFactory=new Zzr(t),this.logger=r}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=U$1(t.request),n=V$1(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let g=this.exampleTypeFactory.buildExample({skipReadonly:t.method==="POST"||t.method==="PUT",schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});g!=null&&i.push([void 0,g])}else for(let{name:g,value:O}of r.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:t.method==="POST"||t.method==="PUT",schema:r.schema,exampleId:g,example:O,options:{isParameter:!1,ignoreOptionals:!0}});P!=null&&i.push([g,P])}if(l&&i.length===0)return this.logger.warn(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(n!=null&&n.type==="present"){let l=this.isSchemaRequired(n.schema);if(n.examples.length===0){let g=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:3,isParameter:!1,ignoreOptionals:!1}});g!=null&&(t.response?.type==="json"?a.push([void 0,EIt.withoutStreaming(g)]):t.response?.type==="streamingJson"&&a.push([void 0,EIt.withStreaming([g])]))}else for(let{name:g,value:O}of n.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:g,example:O,options:{maxDepth:3,isParameter:!1,ignoreOptionals:!1}});P!=null&&(t.response?.type==="json"?a.push([g,EIt.withoutStreaming(P)]):t.response?.type==="streamingJson"&&a.push([g,EIt.withStreaming([P])]))}if(l&&a.length===0)return this.logger.warn(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let l of t.pathParameters){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&u.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:O})}let f=[];for(let l of t.queryParameters){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&f.push({name:l.name,value:O})}let d=[];for(let l of t.headers){let g=this.isSchemaRequired(l.schema),O=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(O!=null&&!C9t(O)&&(this.logger.warn(`Expected a primitive example but got ${O.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),O=void 0),g&&O==null)return[];O!=null&&d.push({name:l.name,value:O})}let c=[];t.request!=null&&t.response!=null?c=L$1(i,a):t.request!=null?c=i.map(([l,g])=>({id:l,request:g,response:void 0})):t.response!=null&&(c=a.map(([l,g])=>({id:l,request:void 0,response:g})));let o=t.examples.filter(l=>ggi(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let g=l.value["code-samples"];if(g!=null)return this.convertCodeSamples(g)}return}else return l.codeSamples}).filter(l=>$M(l));return c.length===0?[SIt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:f,headers:d,request:void 0,response:void 0,codeSamples:o})]:c.map(({id:l,request:g,response:O})=>SIt.full({name:l,description:void 0,pathParameters:u,queryParameters:f,headers:d,request:g,response:O,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?RAr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):RAr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GH.Csharp:r.sdk,code:r.code})).filter($M)}isSchemaRequired(t){return Qja(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function L$1(e,t){let r=[];if(e.length<=1){let[i,a]=e[0]??[];if(t.length===0)return r.push({id:i,request:a,response:void 0}),r;for(let[u,f]of t)r.push({id:u??i,request:a,response:f});return r}if(t.length<=1){let[i,a]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:a}),r;for(let[u,f]of e)r.push({id:u??i,request:f,response:a});return r}let n=new Set;for(let[i,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(i==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let f=!1;for(let d=0;d<t.length;d++){let[c,o]=t[d];c!=null||n.has(d)||i===c&&(r.push({id:i,request:a,response:o}),c!=null&&n.add(d),f=!0)}!f&&u!=null&&r.push({id:i,request:a,response:u})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[a,u]=t[i],f=e.find(([d])=>d==null)?.[1]??e[0]?.[1];f!=null&&r.push({id:a,request:f,response:u})}return r}function U$1(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:W$1(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function V$1(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function C9t(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return C9t(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undisciminated":return C9t(e.value.value);default:return!1}default:xc(e)}}function W$1(e){return Gp.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:T9t(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0}).filter($M),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source})}var Gja=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Zzr(t),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:n,subscribe:i,handshake:a,source:u,namespace:f}){let d=[];for(let c of r){let o=[];for(let O of a.queryParameters){let P=this.isSchemaRequired(O.schema),j=this.exampleTypeFactory.buildExample({schema:O.schema,exampleId:void 0,example:c.queryParameters?.[O.name],options:{name:O.name,isParameter:!0,ignoreOptionals:!0}});j!=null&&!C9t(j)&&(j=void 0),!(P&&j==null)&&j!=null&&o.push({name:O.name,value:j})}let l=[];for(let O of a.headers){let P=this.isSchemaRequired(O.schema),j=this.exampleTypeFactory.buildExample({schema:O.schema,exampleId:void 0,example:c.headers?.[O.name],options:{name:O.name,isParameter:!0,ignoreOptionals:!0}});j!=null&&!C9t(j)&&(j=void 0),!(P&&j==null)&&j!=null&&l.push({name:O.name,value:j})}let g=[];for(let O of c.messages){let P=t.resolveMessageReference({$ref:`#/components/messages/${O.messageId}`}),j=wy(P.payload)?t.resolveSchemaReference(P.payload):P.payload,M=this.exampleTypeFactory.buildExample({schema:a1(j,!1,t,[O.messageId],u,f),exampleId:void 0,example:O.value,options:{isParameter:!1,ignoreOptionals:!0}});M!=null&&g.push({messageType:O.type,payload:M,description:void 0})}d.push({name:c.summary,queryParameters:o,headers:l,description:c.description,messages:g})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:n}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let f of n.queryParameters){let d=this.isSchemaRequired(f.schema),c=this.exampleTypeFactory.buildExample({schema:f.schema,exampleId:void 0,example:void 0,options:{name:f.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!C9t(c)&&(c=void 0),d&&c==null)return;c!=null&&a.push({name:f.name,value:c})}let u=[];for(let f of n.headers){let d=this.isSchemaRequired(f.schema),c=this.exampleTypeFactory.buildExample({schema:f.schema,exampleId:void 0,example:void 0,options:{name:f.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!C9t(c)&&(c=void 0),d&&c==null)return;c!=null&&u.push({name:f.name,value:c})}if(t!=null){let f=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});f!=null&&i.messages.push({messageType:"publish",payload:f,description:void 0})}if(r!=null){let f=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});f!=null&&i.messages.push({messageType:"subscribe",payload:f,description:void 0})}return i}isSchemaRequired(t){return Qja(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var mgi={FERN_DISPLAY_NAME:"x-fern-display-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path"};function g3f(e){return hh(e,mgi.FERN_EXAMPLES)??[]}function O3f({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:a}){let u=[];a!=null&&u.push(a),e.tags?.[0]!=null?u.push(e.tags[0].name):i.naming!=="v2"&&u.push("websocket");let f=new Hja({document:e,taskContext:t,options:r,namespace:a}),d={},c;for(let[l,g]of Object.entries(e.components?.schemas??{})){let O=a1(g,!1,f,[l],n,a);d[l]=O}let o=new Gja(d,t.logger);for(let[l,g]of Object.entries(e.channels??{})){if(g.bindings?.ws==null){f.logger.error(`Channel ${l} does not have websocket bindings. Skipping.`);continue}let O=[];if(g.parameters!=null)for(let[B,I]of Object.entries(g.parameters??{}))O.push({name:B,description:I.description,parameterNameOverride:void 0,schema:I.schema!=null?a1(I.schema,!1,f,u,n,a):Gp.primitive({schema:Ay.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:O2e(I),source:n});let P=[];if(g.bindings.ws.headers!=null){let B=g.bindings.ws.headers.required??[];for(let[I,C]of Object.entries(g.bindings.ws.headers.properties??{})){let F=wy(C)?f.resolveSchemaReference(C):C;P.push({name:I,schema:a1(F,!B.includes(I),f,u,n,a),description:F.description,parameterNameOverride:void 0,env:void 0,availability:O2e(F),source:n})}}let j=[];if(g.bindings.ws.query!=null){let B=g.bindings.ws.query.required??[];for(let[I,C]of Object.entries(g.bindings.ws.query.properties??{})){let F=wy(C)?f.resolveSchemaReference(C):C;j.push({name:I,schema:a1(F,!B.includes(I),f,u,n,a),description:F.description,parameterNameOverride:void 0,availability:O2e(F),source:n})}}let M;g.publish!=null&&(M=m3f({generatedName:g.publish.operationId??"PublishEvent",event:g.publish,breadcrumbs:u,context:f,source:n,options:r,asyncApiOptions:i}));let q;if(g.subscribe!=null&&(q=m3f({generatedName:g.subscribe.operationId??"SubscribeEvent",event:g.subscribe,breadcrumbs:u,context:f,source:n,options:r,asyncApiOptions:i})),P.length>0||j.length>0||M!=null||q!=null){let B=g3f(g),I=[];if(B.length>0)I=o.buildWebsocketSessionExamplesForExtension({context:f,extensionExamples:B,handshake:{headers:P,queryParameters:j},publish:M,subscribe:q,source:n,namespace:a});else{let F=o.buildWebsocketSessionExample({handshake:{headers:P,queryParameters:j},publish:M,subscribe:q});F!=null&&I.push(F)}let C=e.tags?.[0]?.name!=null?[e.tags?.[0].name]:void 0;c={handshake:{headers:P.map(F=>({...F,schema:YC(F.schema),env:F.env})),queryParameters:j.map(F=>({...F,schema:YC(F.schema)})),pathParameters:O.map(F=>({...F,parameterNameOverride:void 0,schema:YC(F.schema)}))},groupName:f.resolveTags(C,"Websocket"),publish:M!=null?YC(M):M,subscribe:q!=null?YC(q):q,summary:hh(g,mgi.FERN_DISPLAY_NAME),path:l,description:void 0,examples:I,source:n};break}}return{groupedSchemas:Wja(a,d),channel:c,basePath:hh(e,mgi.BASE_PATH)}}function m3f({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:a,asyncApiOptions:u}){if(t.message.oneOf!=null){let f=[],d=[];for(let c of t.message.oneOf){let o,l={type:"notFound"};if(wy(c)){let g=r.resolveMessageReference(c);!wy(g.payload)&&u.naming==="v2"?(l=g.name?{type:"name",name:g.name}:l,o={...g.payload,title:g.name??g.payload.title,description:g.name??g.payload.description}):o=g.payload}else o=c;d.push(l),f.push(o)}return mNn({description:t.description??t.message.description,availability:O2e(t.message),subtypes:f,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}var lin=Xo(uUf(),1);var sUf=require("fs/promises");async function rAa({absoluteFilepathToOverrides:e,data:t,context:r}){let n=null;try{let i=(await(0,sUf.readFile)(e,"utf8")).toString();try{n=JSON.parse(i)}catch{n=d0.load(i,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return BKo({data:t,overrides:n})}var tbw={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},rbw={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:tbw,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}};async function lUf({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,context:r}){let n=await cUf({absolutePathToOpenAPI:e}),i;if(t!=null?i=t:typeof n=="object"&&n[kh.OPENAPI_OVERIDES_FILEPATH]!=null&&(i=yf(cb(e),Ms.of(n[kh.OPENAPI_OVERIDES_FILEPATH]))),i!=null){let a=await rAa({absoluteFilepathToOverrides:i,context:r,data:n});return await cUf({absolutePathToOpenAPI:e,parsed:a})}return n}async function cUf({absolutePathToOpenAPI:e,parsed:t}){let r={config:new lin.Config({apis:{},styleguide:{plugins:[rbw],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};return(t!=null?await(0,lin.bundle)({...r,doc:{source:new lin.Source(e,"<openapi>"),parsed:t}}):await(0,lin.bundle)({...r,ref:e})).bundle.parsed}var PJf=Xo(bQf(),1);function gQf(e){return hh(e,kh.ASYNC_CONFIG)}var mQf="$request.";function OQf(e){let t=hh(e,kh.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:_ww(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function _ww(e){return e.startsWith(mQf)?e.slice(mQf.length):e}function PQf(e){let t=e;if(t.cursor!=null)return zAr.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;return zAr.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}function wQf(e,t){let r=hh(t,kh.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=hh(e,kh.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:PQf(n)}return PQf(r)}}function jQf(e){let t=hww(e),r={};return yxu({obj:t,occurrences:r,breadcrumbs:[]}),r}function yxu({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)yxu({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)yxu({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function hww(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?gOi(r.get):void 0,put:r?.put!=null?gOi(r.put):void 0,post:r?.post!=null?gOi(r.post):void 0,patch:r?.patch!=null?gOi(r.patch):void 0,delete:r?.delete!=null?gOi(r.delete):void 0}]))}}function gOi(e){return{...e,requestBody:e.requestBody!=null?wy(e.requestBody)?e.requestBody:yww(e.requestBody):void 0}}function yww(e){let t,r;for(let n in e.content){let i=D4.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[D4.MULTIPART_FORM_DATA]:r}}:e}var DQf="#/components/parameters/",SQf="#/components/responses/",EQf="#/components/examples/",AQf="#/components/requestBodies/",z8n=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;namespace;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=jQf(t),this.options=i,this.source=a,this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown",additionalProperties:!0};n=n[i]}return n==null?{"x-fern-type":"unknown",additionalProperties:!0}:(wy(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(DQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(DQf.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(AQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(AQf.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(SQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(SQf.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(EQf))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(EQf.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return wy(n)?this.resolveExampleReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}};var R8n=class extends z8n{constructor({document:t,taskContext:r,options:n,source:i,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var Sx;(function(e){e.assertEqual=i=>i;function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let a={};for(let u of i)a[u]=u;return a},e.getValidEnumValues=i=>{let a=e.objectKeys(i).filter(f=>typeof i[i[f]]!="number"),u={};for(let f of a)u[f]=i[f];return e.objectValues(u)},e.objectValues=i=>e.objectKeys(i).map(function(a){return i[a]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let u in i)Object.prototype.hasOwnProperty.call(i,u)&&a.push(u);return a},e.find=(i,a)=>{for(let u of i)if(a(u))return u},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,a=" | "){return i.map(u=>typeof u=="string"?`'${u}'`:u).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Sx||(Sx={}));var bxu;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(bxu||(bxu={}));var C0=Sx.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),V5r=e=>{switch(typeof e){case"undefined":return C0.undefined;case"string":return C0.string;case"number":return isNaN(e)?C0.nan:C0.number;case"boolean":return C0.boolean;case"function":return C0.function;case"bigint":return C0.bigint;case"symbol":return C0.symbol;case"object":return Array.isArray(e)?C0.array:e===null?C0.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C0.promise:typeof Map<"u"&&e instanceof Map?C0.map:typeof Set<"u"&&e instanceof Set?C0.set:typeof Date<"u"&&e instanceof Date?C0.date:C0.object;default:return C0.unknown}},vh=Sx.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),vww=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),NDe=class e extends Error{constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){let r=t||function(a){return a.message},n={_errors:[]},i=a=>{for(let u of a.issues)if(u.code==="invalid_union")u.unionErrors.map(i);else if(u.code==="invalid_return_type")i(u.returnTypeError);else if(u.code==="invalid_arguments")i(u.argumentsError);else if(u.path.length===0)n._errors.push(r(u));else{let f=n,d=0;for(;d<u.path.length;){let c=u.path[d];d===u.path.length-1?(f[c]=f[c]||{_errors:[]},f[c]._errors.push(r(u))):f[c]=f[c]||{_errors:[]},f=f[c],d++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Sx.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};NDe.create=e=>new NDe(e);var U8n=(e,t)=>{let r;switch(e.code){case vh.invalid_type:e.received===C0.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case vh.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Sx.jsonStringifyReplacer)}`;break;case vh.unrecognized_keys:r=`Unrecognized key(s) in object: ${Sx.joinValues(e.keys,", ")}`;break;case vh.invalid_union:r="Invalid input";break;case vh.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Sx.joinValues(e.options)}`;break;case vh.invalid_enum_value:r=`Invalid enum value. Expected ${Sx.joinValues(e.options)}, received '${e.received}'`;break;case vh.invalid_arguments:r="Invalid function arguments";break;case vh.invalid_return_type:r="Invalid function return type";break;case vh.invalid_date:r="Invalid date";break;case vh.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Sx.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case vh.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case vh.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case vh.custom:r="Invalid input";break;case vh.invalid_intersection_types:r="Intersection results could not be merged";break;case vh.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case vh.not_finite:r="Number must be finite";break;default:r=t.defaultError,Sx.assertNever(e)}return{message:r}},TQf=U8n;function bww(e){TQf=e}function lMa(){return TQf}var fMa=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,a=[...r,...i.path||[]],u={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let f="",d=n.filter(c=>!!c).slice().reverse();for(let c of d)f=c(u,{data:t,defaultError:f}).message;return{...i,path:a,message:f}},gww=[];function u0(e,t){let r=lMa(),n=fMa({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===U8n?void 0:U8n].filter(i=>!!i)});e.common.issues.push(n)}var H$=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return aP;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let a=await i.key,u=await i.value;n.push({key:a,value:u})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:a,value:u}=i;if(a.status==="aborted"||u.status==="aborted")return aP;a.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof u.value<"u"||i.alwaysSet)&&(n[a.value]=u.value)}return{status:t.value,value:n}}},aP=Object.freeze({status:"aborted"}),L8n=e=>({status:"dirty",value:e}),wk=e=>({status:"valid",value:e}),gxu=e=>e.status==="aborted",mxu=e=>e.status==="dirty",POi=e=>e.status==="valid",wOi=e=>typeof Promise<"u"&&e instanceof Promise;function dMa(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}function CQf(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r}var Sg;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Sg||(Sg={}));var mOi,OOi,B2e=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},MQf=(e,t)=>{if(POi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new NDe(e.common.issues);return this._error=r,this._error}}};function Ej(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(u,f)=>{var d,c;let{message:o}=e;return u.code==="invalid_enum_value"?{message:o??f.defaultError}:typeof f.data>"u"?{message:(d=o??n)!==null&&d!==void 0?d:f.defaultError}:u.code!=="invalid_type"?{message:f.defaultError}:{message:(c=o??r)!==null&&c!==void 0?c:f.defaultError}},description:i}}var Aj=class{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return V5r(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:V5r(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new H$,ctx:{common:t.parent.common,data:t.data,parsedType:V5r(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(wOi(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){var n;let i={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:V5r(t)},a=this._parseSync({data:t,path:i.path,parent:i});return MQf(i,a)}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:V5r(t)},i=this._parse({data:t,path:n.path,parent:n}),a=await(wOi(i)?i:Promise.resolve(i));return MQf(n,a)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let u=t(i),f=()=>a.addIssue({code:vh.custom,...n(i)});return typeof Promise<"u"&&u instanceof Promise?u.then(d=>d?!0:(f(),!1)):u?!0:(f(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new zDe({schema:this,typeName:CO.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return I2e.create(this,this._def)}nullable(){return Y9t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return iMr.create(this,this._def)}promise(){return Q5r.create(this,this._def)}or(t){return Ain.create([this,t],this._def)}and(t){return Min.create(this,t,this._def)}transform(t){return new zDe({...Ej(this._def),schema:this,typeName:CO.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Iin({...Ej(this._def),innerType:this,defaultValue:r,typeName:CO.ZodDefault})}brand(){return new jOi({typeName:CO.ZodBranded,type:this,...Ej(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Bin({...Ej(this._def),innerType:this,catchValue:r,typeName:CO.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return DOi.create(this,t)}readonly(){return Nin.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mww=/^c[^\s-]{8,}$/i,Oww=/^[0-9a-z]+$/,Pww=/^[0-9A-HJKMNP-TV-Z]{26}$/,www=/^[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}$/i,jww=/^[a-z0-9_-]{21}$/i,Dww=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Sww=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eww="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vxu,Aww=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mww=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,xww=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qQf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Tww=new RegExp(`^${qQf}$`);function IQf(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Cww(e){return new RegExp(`^${IQf(e)}$`)}function BQf(e){let t=`${qQf}T${IQf(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function qww(e,t){return!!((t==="v4"||!t)&&Aww.test(e)||(t==="v6"||!t)&&Mww.test(e))}var W5r=class e extends Aj{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C0.string){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.string,received:a.parsedType}),aP}let n=new H$,i;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let u=t.data.length>a.value,f=t.data.length<a.value;(u||f)&&(i=this._getOrReturnCtx(t,i),u?u0(i,{code:vh.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):f&&u0(i,{code:vh.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Sww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"email",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")vxu||(vxu=new RegExp(Eww,"u")),vxu.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"emoji",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")www.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"uuid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")jww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"nanoid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")mww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"cuid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Oww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"cuid2",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Pww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"ulid",code:vh.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),u0(i,{validation:"url",code:vh.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"regex",code:vh.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?BQf(a).test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Tww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Cww(a).test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Dww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"duration",code:vh.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?qww(t.data,a.version)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"ip",code:vh.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?xww.test(t.data)||(i=this._getOrReturnCtx(t,i),u0(i,{validation:"base64",code:vh.invalid_string,message:a.message}),n.dirty()):Sx.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:vh.invalid_string,...Sg.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Sg.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Sg.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Sg.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Sg.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Sg.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Sg.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Sg.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Sg.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Sg.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Sg.errToObj(t)})}datetime(t){var r,n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(r=t?.offset)!==null&&r!==void 0?r:!1,local:(n=t?.local)!==null&&n!==void 0?n:!1,...Sg.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Sg.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Sg.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Sg.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Sg.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Sg.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Sg.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Sg.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Sg.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Sg.errToObj(r)})}nonempty(t){return this.min(1,Sg.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};W5r.create=e=>{var t;return new W5r({checks:[],typeName:CO.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Ej(e)})};function Iww(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,a=parseInt(e.toFixed(i).replace(".","")),u=parseInt(t.toFixed(i).replace(".",""));return a%u/Math.pow(10,i)}var Pin=class e extends Aj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==C0.number){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.number,received:a.parsedType}),aP}let n,i=new H$;for(let a of this._def.checks)a.kind==="int"?Sx.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Iww(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_finite,message:a.message}),i.dirty()):Sx.assertNever(a);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Sg.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Sg.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Sg.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Sg.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Sg.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Sg.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sg.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sg.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sg.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sg.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Sg.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Sg.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sg.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sg.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Sx.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Pin.create=e=>new Pin({checks:[],typeName:CO.ZodNumber,coerce:e?.coerce||!1,...Ej(e)});var win=class e extends Aj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==C0.bigint){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.bigint,received:a.parsedType}),aP}let n,i=new H$;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),u0(n,{code:vh.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Sx.assertNever(a);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Sg.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Sg.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Sg.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Sg.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Sg.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sg.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sg.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sg.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sg.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Sg.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};win.create=e=>{var t;return new win({checks:[],typeName:CO.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Ej(e)})};var jin=class extends Aj{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C0.boolean){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.boolean,received:n.parsedType}),aP}return wk(t.data)}};jin.create=e=>new jin({typeName:CO.ZodBoolean,coerce:e?.coerce||!1,...Ej(e)});var Din=class e extends Aj{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C0.date){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_type,expected:C0.date,received:a.parsedType}),aP}if(isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return u0(a,{code:vh.invalid_date}),aP}let n=new H$,i;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(i=this._getOrReturnCtx(t,i),u0(i,{code:vh.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Sx.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Sg.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Sg.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Din.create=e=>new Din({checks:[],coerce:e?.coerce||!1,typeName:CO.ZodDate,...Ej(e)});var V8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.symbol){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.symbol,received:n.parsedType}),aP}return wk(t.data)}};V8n.create=e=>new V8n({typeName:CO.ZodSymbol,...Ej(e)});var Sin=class extends Aj{_parse(t){if(this._getType(t)!==C0.undefined){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.undefined,received:n.parsedType}),aP}return wk(t.data)}};Sin.create=e=>new Sin({typeName:CO.ZodUndefined,...Ej(e)});var Ein=class extends Aj{_parse(t){if(this._getType(t)!==C0.null){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.null,received:n.parsedType}),aP}return wk(t.data)}};Ein.create=e=>new Ein({typeName:CO.ZodNull,...Ej(e)});var H5r=class extends Aj{constructor(){super(...arguments),this._any=!0}_parse(t){return wk(t.data)}};H5r.create=e=>new H5r({typeName:CO.ZodAny,...Ej(e)});var nMr=class extends Aj{constructor(){super(...arguments),this._unknown=!0}_parse(t){return wk(t.data)}};nMr.create=e=>new nMr({typeName:CO.ZodUnknown,...Ej(e)});var LIt=class extends Aj{_parse(t){let r=this._getOrReturnCtx(t);return u0(r,{code:vh.invalid_type,expected:C0.never,received:r.parsedType}),aP}};LIt.create=e=>new LIt({typeName:CO.ZodNever,...Ej(e)});var W8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.undefined){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.void,received:n.parsedType}),aP}return wk(t.data)}};W8n.create=e=>new W8n({typeName:CO.ZodVoid,...Ej(e)});var iMr=class e extends Aj{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==C0.array)return u0(r,{code:vh.invalid_type,expected:C0.array,received:r.parsedType}),aP;if(i.exactLength!==null){let u=r.data.length>i.exactLength.value,f=r.data.length<i.exactLength.value;(u||f)&&(u0(r,{code:u?vh.too_big:vh.too_small,minimum:f?i.exactLength.value:void 0,maximum:u?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(u0(r,{code:vh.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(u0(r,{code:vh.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((u,f)=>i.type._parseAsync(new B2e(r,u,r.path,f)))).then(u=>H$.mergeArray(n,u));let a=[...r.data].map((u,f)=>i.type._parseSync(new B2e(r,u,r.path,f)));return H$.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Sg.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Sg.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Sg.toString(r)}})}nonempty(t){return this.min(1,t)}};iMr.create=(e,t)=>new iMr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:CO.ZodArray,...Ej(t)});function F8n(e){if(e instanceof Oae){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=I2e.create(F8n(n))}return new Oae({...e._def,shape:()=>t})}else return e instanceof iMr?new iMr({...e._def,type:F8n(e.element)}):e instanceof I2e?I2e.create(F8n(e.unwrap())):e instanceof Y9t?Y9t.create(F8n(e.unwrap())):e instanceof K9t?K9t.create(e.items.map(t=>F8n(t))):e}var Oae=class e extends Aj{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Sx.objectKeys(t);return this._cached={shape:t,keys:r}}_parse(t){if(this._getType(t)!==C0.object){let c=this._getOrReturnCtx(t);return u0(c,{code:vh.invalid_type,expected:C0.object,received:c.parsedType}),aP}let{status:n,ctx:i}=this._processInputParams(t),{shape:a,keys:u}=this._getCached(),f=[];if(!(this._def.catchall instanceof LIt&&this._def.unknownKeys==="strip"))for(let c in i.data)u.includes(c)||f.push(c);let d=[];for(let c of u){let o=a[c],l=i.data[c];d.push({key:{status:"valid",value:c},value:o._parse(new B2e(i,l,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof LIt){let c=this._def.unknownKeys;if(c==="passthrough")for(let o of f)d.push({key:{status:"valid",value:o},value:{status:"valid",value:i.data[o]}});else if(c==="strict")f.length>0&&(u0(i,{code:vh.unrecognized_keys,keys:f}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let o of f){let l=i.data[o];d.push({key:{status:"valid",value:o},value:c._parse(new B2e(i,l,i.path,o)),alwaysSet:o in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let o of d){let l=await o.key,g=await o.value;c.push({key:l,value:g,alwaysSet:o.alwaysSet})}return c}).then(c=>H$.mergeObjectSync(n,c)):H$.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(t){return Sg.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var i,a,u,f;let d=(u=(a=(i=this._def).errorMap)===null||a===void 0?void 0:a.call(i,r,n).message)!==null&&u!==void 0?u:n.defaultError;return r.code==="unrecognized_keys"?{message:(f=Sg.errToObj(t).message)!==null&&f!==void 0?f:d}:{message:d}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:CO.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};return Sx.objectKeys(t).forEach(n=>{t[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}omit(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{t[n]||(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}deepPartial(){return F8n(this)}partial(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}),new e({...this._def,shape:()=>r})}required(t){let r={};return Sx.objectKeys(this.shape).forEach(n=>{if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof I2e;)a=a._def.innerType;r[n]=a}}),new e({...this._def,shape:()=>r})}keyof(){return NQf(Sx.objectKeys(this.shape))}};Oae.create=(e,t)=>new Oae({shape:()=>e,unknownKeys:"strip",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});Oae.strictCreate=(e,t)=>new Oae({shape:()=>e,unknownKeys:"strict",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});Oae.lazycreate=(e,t)=>new Oae({shape:e,unknownKeys:"strip",catchall:LIt.create(),typeName:CO.ZodObject,...Ej(t)});var Ain=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(a){for(let f of a)if(f.result.status==="valid")return f.result;for(let f of a)if(f.result.status==="dirty")return r.common.issues.push(...f.ctx.common.issues),f.result;let u=a.map(f=>new NDe(f.ctx.common.issues));return u0(r,{code:vh.invalid_union,unionErrors:u}),aP}if(r.common.async)return Promise.all(n.map(async a=>{let u={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(i);{let a,u=[];for(let d of n){let c={...r,common:{...r.common,issues:[]},parent:null},o=d._parseSync({data:r.data,path:r.path,parent:c});if(o.status==="valid")return o;o.status==="dirty"&&!a&&(a={result:o,ctx:c}),c.common.issues.length&&u.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let f=u.map(d=>new NDe(d));return u0(r,{code:vh.invalid_union,unionErrors:f}),aP}}get options(){return this._def.options}};Ain.create=(e,t)=>new Ain({options:e,typeName:CO.ZodUnion,...Ej(t)});var rMr=e=>e instanceof xin?rMr(e.schema):e instanceof zDe?rMr(e.innerType()):e instanceof Tin?[e.value]:e instanceof Cin?e.options:e instanceof qin?Sx.objectValues(e.enum):e instanceof Iin?rMr(e._def.innerType):e instanceof Sin?[void 0]:e instanceof Ein?[null]:e instanceof I2e?[void 0,...rMr(e.unwrap())]:e instanceof Y9t?[null,...rMr(e.unwrap())]:e instanceof jOi||e instanceof Nin?rMr(e.unwrap()):e instanceof Bin?rMr(e._def.innerType):[],pMa=class e extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.object)return u0(r,{code:vh.invalid_type,expected:C0.object,received:r.parsedType}),aP;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(u0(r,{code:vh.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),aP)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let a of r){let u=rMr(a.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of u){if(i.has(f))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);i.set(f,a)}}return new e({typeName:CO.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ej(n)})}};function Oxu(e,t){let r=V5r(e),n=V5r(t);if(e===t)return{valid:!0,data:e};if(r===C0.object&&n===C0.object){let i=Sx.objectKeys(t),a=Sx.objectKeys(e).filter(f=>i.indexOf(f)!==-1),u={...e,...t};for(let f of a){let d=Oxu(e[f],t[f]);if(!d.valid)return{valid:!1};u[f]=d.data}return{valid:!0,data:u}}else if(r===C0.array&&n===C0.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let a=0;a<e.length;a++){let u=e[a],f=t[a],d=Oxu(u,f);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return r===C0.date&&n===C0.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Min=class extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(a,u)=>{if(gxu(a)||gxu(u))return aP;let f=Oxu(a.value,u.value);return f.valid?((mxu(a)||mxu(u))&&r.dirty(),{status:r.value,value:f.data}):(u0(n,{code:vh.invalid_intersection_types}),aP)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,u])=>i(a,u)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Min.create=(e,t,r)=>new Min({left:e,right:t,typeName:CO.ZodIntersection,...Ej(r)});var K9t=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.array)return u0(n,{code:vh.invalid_type,expected:C0.array,received:n.parsedType}),aP;if(n.data.length<this._def.items.length)return u0(n,{code:vh.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),aP;!this._def.rest&&n.data.length>this._def.items.length&&(u0(n,{code:vh.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((u,f)=>{let d=this._def.items[f]||this._def.rest;return d?d._parse(new B2e(n,u,n.path,f)):null}).filter(u=>!!u);return n.common.async?Promise.all(a).then(u=>H$.mergeArray(r,u)):H$.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};K9t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K9t({items:e,typeName:CO.ZodTuple,rest:null,...Ej(t)})};var _Ma=class e extends Aj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.object)return u0(n,{code:vh.invalid_type,expected:C0.object,received:n.parsedType}),aP;let i=[],a=this._def.keyType,u=this._def.valueType;for(let f in n.data)i.push({key:a._parse(new B2e(n,f,n.path,f)),value:u._parse(new B2e(n,n.data[f],n.path,f)),alwaysSet:f in n.data});return n.common.async?H$.mergeObjectAsync(r,i):H$.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Aj?new e({keyType:t,valueType:r,typeName:CO.ZodRecord,...Ej(n)}):new e({keyType:W5r.create(),valueType:t,typeName:CO.ZodRecord,...Ej(r)})}},H8n=class extends Aj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.map)return u0(n,{code:vh.invalid_type,expected:C0.map,received:n.parsedType}),aP;let i=this._def.keyType,a=this._def.valueType,u=[...n.data.entries()].map(([f,d],c)=>({key:i._parse(new B2e(n,f,n.path,[c,"key"])),value:a._parse(new B2e(n,d,n.path,[c,"value"]))}));if(n.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let d of u){let c=await d.key,o=await d.value;if(c.status==="aborted"||o.status==="aborted")return aP;(c.status==="dirty"||o.status==="dirty")&&r.dirty(),f.set(c.value,o.value)}return{status:r.value,value:f}})}else{let f=new Map;for(let d of u){let c=d.key,o=d.value;if(c.status==="aborted"||o.status==="aborted")return aP;(c.status==="dirty"||o.status==="dirty")&&r.dirty(),f.set(c.value,o.value)}return{status:r.value,value:f}}}};H8n.create=(e,t,r)=>new H8n({valueType:t,keyType:e,typeName:CO.ZodMap,...Ej(r)});var Q8n=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==C0.set)return u0(n,{code:vh.invalid_type,expected:C0.set,received:n.parsedType}),aP;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(u0(n,{code:vh.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(u0(n,{code:vh.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function u(d){let c=new Set;for(let o of d){if(o.status==="aborted")return aP;o.status==="dirty"&&r.dirty(),c.add(o.value)}return{status:r.value,value:c}}let f=[...n.data.values()].map((d,c)=>a._parse(new B2e(n,d,n.path,c)));return n.common.async?Promise.all(f).then(d=>u(d)):u(f)}min(t,r){return new e({...this._def,minSize:{value:t,message:Sg.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Sg.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Q8n.create=(e,t)=>new Q8n({valueType:e,minSize:null,maxSize:null,typeName:CO.ZodSet,...Ej(t)});var hMa=class e extends Aj{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.function)return u0(r,{code:vh.invalid_type,expected:C0.function,received:r.parsedType}),aP;function n(f,d){return fMa({data:f,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lMa(),U8n].filter(c=>!!c),issueData:{code:vh.invalid_arguments,argumentsError:d}})}function i(f,d){return fMa({data:f,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lMa(),U8n].filter(c=>!!c),issueData:{code:vh.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},u=r.data;if(this._def.returns instanceof Q5r){let f=this;return wk(async function(...d){let c=new NDe([]),o=await f._def.args.parseAsync(d,a).catch(O=>{throw c.addIssue(n(d,O)),c}),l=await Reflect.apply(u,this,o);return await f._def.returns._def.type.parseAsync(l,a).catch(O=>{throw c.addIssue(i(l,O)),c})})}else{let f=this;return wk(function(...d){let c=f._def.args.safeParse(d,a);if(!c.success)throw new NDe([n(d,c.error)]);let o=Reflect.apply(u,this,c.data),l=f._def.returns.safeParse(o,a);if(!l.success)throw new NDe([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:K9t.create(t).rest(nMr.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||K9t.create([]).rest(nMr.create()),returns:r||nMr.create(),typeName:CO.ZodFunction,...Ej(n)})}},xin=class extends Aj{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};xin.create=(e,t)=>new xin({getter:e,typeName:CO.ZodLazy,...Ej(t)});var Tin=class extends Aj{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return u0(r,{received:r.data,code:vh.invalid_literal,expected:this._def.value}),aP}return{status:"valid",value:t.data}}get value(){return this._def.value}};Tin.create=(e,t)=>new Tin({value:e,typeName:CO.ZodLiteral,...Ej(t)});function NQf(e,t){return new Cin({values:e,typeName:CO.ZodEnum,...Ej(t)})}var Cin=class e extends Aj{constructor(){super(...arguments),mOi.set(this,void 0)}_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return u0(r,{expected:Sx.joinValues(n),received:r.parsedType,code:vh.invalid_type}),aP}if(dMa(this,mOi,"f")||CQf(this,mOi,new Set(this._def.values),"f"),!dMa(this,mOi,"f").has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return u0(r,{received:r.data,code:vh.invalid_enum_value,options:n}),aP}return wk(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};mOi=new WeakMap;Cin.create=NQf;var qin=class extends Aj{constructor(){super(...arguments),OOi.set(this,void 0)}_parse(t){let r=Sx.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==C0.string&&n.parsedType!==C0.number){let i=Sx.objectValues(r);return u0(n,{expected:Sx.joinValues(i),received:n.parsedType,code:vh.invalid_type}),aP}if(dMa(this,OOi,"f")||CQf(this,OOi,new Set(Sx.getValidEnumValues(this._def.values)),"f"),!dMa(this,OOi,"f").has(t.data)){let i=Sx.objectValues(r);return u0(n,{received:n.data,code:vh.invalid_enum_value,options:i}),aP}return wk(t.data)}get enum(){return this._def.values}};OOi=new WeakMap;qin.create=(e,t)=>new qin({values:e,typeName:CO.ZodNativeEnum,...Ej(t)});var Q5r=class extends Aj{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==C0.promise&&r.common.async===!1)return u0(r,{code:vh.invalid_type,expected:C0.promise,received:r.parsedType}),aP;let n=r.parsedType===C0.promise?r.data:Promise.resolve(r.data);return wk(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Q5r.create=(e,t)=>new Q5r({type:e,typeName:CO.ZodPromise,...Ej(t)});var zDe=class extends Aj{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===CO.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,a={addIssue:u=>{u0(n,u),u.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let u=i.transform(n.data,a);if(n.common.async)return Promise.resolve(u).then(async f=>{if(r.value==="aborted")return aP;let d=await this._def.schema._parseAsync({data:f,path:n.path,parent:n});return d.status==="aborted"?aP:d.status==="dirty"||r.value==="dirty"?L8n(d.value):d});{if(r.value==="aborted")return aP;let f=this._def.schema._parseSync({data:u,path:n.path,parent:n});return f.status==="aborted"?aP:f.status==="dirty"||r.value==="dirty"?L8n(f.value):f}}if(i.type==="refinement"){let u=f=>{let d=i.refinement(f,a);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(n.common.async===!1){let f=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return f.status==="aborted"?aP:(f.status==="dirty"&&r.dirty(),u(f.value),{status:r.value,value:f.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(f=>f.status==="aborted"?aP:(f.status==="dirty"&&r.dirty(),u(f.value).then(()=>({status:r.value,value:f.value}))))}if(i.type==="transform")if(n.common.async===!1){let u=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!POi(u))return u;let f=i.transform(u.value,a);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:f}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(u=>POi(u)?Promise.resolve(i.transform(u.value,a)).then(f=>({status:r.value,value:f})):u);Sx.assertNever(i)}};zDe.create=(e,t,r)=>new zDe({schema:e,typeName:CO.ZodEffects,effect:t,...Ej(r)});zDe.createWithPreprocess=(e,t,r)=>new zDe({schema:t,effect:{type:"preprocess",transform:e},typeName:CO.ZodEffects,...Ej(r)});var I2e=class extends Aj{_parse(t){return this._getType(t)===C0.undefined?wk(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};I2e.create=(e,t)=>new I2e({innerType:e,typeName:CO.ZodOptional,...Ej(t)});var Y9t=class extends Aj{_parse(t){return this._getType(t)===C0.null?wk(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Y9t.create=(e,t)=>new Y9t({innerType:e,typeName:CO.ZodNullable,...Ej(t)});var Iin=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===C0.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Iin.create=(e,t)=>new Iin({innerType:e,typeName:CO.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ej(t)});var Bin=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return wOi(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new NDe(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new NDe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Bin.create=(e,t)=>new Bin({innerType:e,typeName:CO.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ej(t)});var J8n=class extends Aj{_parse(t){if(this._getType(t)!==C0.nan){let n=this._getOrReturnCtx(t);return u0(n,{code:vh.invalid_type,expected:C0.nan,received:n.parsedType}),aP}return{status:"valid",value:t.data}}};J8n.create=e=>new J8n({typeName:CO.ZodNaN,...Ej(e)});var Bww=Symbol("zod_brand"),jOi=class extends Aj{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},DOi=class e extends Aj{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?aP:a.status==="dirty"?(r.dirty(),L8n(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?aP:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:CO.ZodPipeline})}},Nin=class extends Aj{_parse(t){let r=this._def.innerType._parse(t),n=i=>(POi(i)&&(i.value=Object.freeze(i.value)),i);return wOi(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Nin.create=(e,t)=>new Nin({innerType:e,typeName:CO.ZodReadonly,...Ej(t)});function zQf(e,t={},r){return e?H5r.create().superRefine((n,i)=>{var a,u;if(!e(n)){let f=typeof t=="function"?t(n):typeof t=="string"?{message:t}:t,d=(u=(a=f.fatal)!==null&&a!==void 0?a:r)!==null&&u!==void 0?u:!0,c=typeof f=="string"?{message:f}:f;i.addIssue({code:"custom",...c,fatal:d})}}):H5r.create()}var Nww={object:Oae.lazycreate},CO;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(CO||(CO={}));var zww=(e,t={message:`Input not instance of ${e.name}`})=>zQf(r=>r instanceof e,t),RQf=W5r.create,FQf=Pin.create,Rww=J8n.create,Fww=win.create,LQf=jin.create,Lww=Din.create,Uww=V8n.create,Vww=Sin.create,Www=Ein.create,Hww=H5r.create,Qww=nMr.create,Jww=LIt.create,Gww=W8n.create,$ww=iMr.create,Kww=Oae.create,Yww=Oae.strictCreate,Xww=Ain.create,Zww=pMa.create,kww=Min.create,ejw=K9t.create,tjw=_Ma.create,rjw=H8n.create,njw=Q8n.create,ijw=hMa.create,ajw=xin.create,ojw=Tin.create,ujw=Cin.create,sjw=qin.create,cjw=Q5r.create,xQf=zDe.create,ljw=I2e.create,fjw=Y9t.create,djw=zDe.createWithPreprocess,pjw=DOi.create,_jw=()=>RQf().optional(),hjw=()=>FQf().optional(),yjw=()=>LQf().optional(),vjw={string:e=>W5r.create({...e,coerce:!0}),number:e=>Pin.create({...e,coerce:!0}),boolean:e=>jin.create({...e,coerce:!0}),bigint:e=>win.create({...e,coerce:!0}),date:e=>Din.create({...e,coerce:!0})},bjw=aP,RDe=Object.freeze({__proto__:null,defaultErrorMap:U8n,setErrorMap:bww,getErrorMap:lMa,makeIssue:fMa,EMPTY_PATH:gww,addIssueToContext:u0,ParseStatus:H$,INVALID:aP,DIRTY:L8n,OK:wk,isAborted:gxu,isDirty:mxu,isValid:POi,isAsync:wOi,get util(){return Sx},get objectUtil(){return bxu},ZodParsedType:C0,getParsedType:V5r,ZodType:Aj,datetimeRegex:BQf,ZodString:W5r,ZodNumber:Pin,ZodBigInt:win,ZodBoolean:jin,ZodDate:Din,ZodSymbol:V8n,ZodUndefined:Sin,ZodNull:Ein,ZodAny:H5r,ZodUnknown:nMr,ZodNever:LIt,ZodVoid:W8n,ZodArray:iMr,ZodObject:Oae,ZodUnion:Ain,ZodDiscriminatedUnion:pMa,ZodIntersection:Min,ZodTuple:K9t,ZodRecord:_Ma,ZodMap:H8n,ZodSet:Q8n,ZodFunction:hMa,ZodLazy:xin,ZodLiteral:Tin,ZodEnum:Cin,ZodNativeEnum:qin,ZodPromise:Q5r,ZodEffects:zDe,ZodTransformer:zDe,ZodOptional:I2e,ZodNullable:Y9t,ZodDefault:Iin,ZodCatch:Bin,ZodNaN:J8n,BRAND:Bww,ZodBranded:jOi,ZodPipeline:DOi,ZodReadonly:Nin,custom:zQf,Schema:Aj,ZodSchema:Aj,late:Nww,get ZodFirstPartyTypeKind(){return CO},coerce:vjw,any:Hww,array:$ww,bigint:Fww,boolean:LQf,date:Lww,discriminatedUnion:Zww,effect:xQf,enum:ujw,function:ijw,instanceof:zww,intersection:kww,lazy:ajw,literal:ojw,map:rjw,nan:Rww,nativeEnum:sjw,never:Jww,null:Www,nullable:fjw,number:FQf,object:Kww,oboolean:yjw,onumber:hjw,optional:ljw,ostring:_jw,pipeline:pjw,preprocess:djw,promise:cjw,record:tjw,set:njw,strictObject:Yww,string:RQf,symbol:Uww,transformer:xQf,tuple:ejw,undefined:Vww,union:Xww,unknown:Qww,void:Gww,NEVER:bjw,ZodIssueCode:vh,quotelessJson:vww,ZodError:NDe});var gjw=RDe.object({lang:RDe.string(),label:RDe.optional(RDe.string()),source:RDe.string()}),Pxu=RDe.array(gjw);var UQf={README_EXT:"x-readme"};function mjw(e){if(!Array.isArray(e))return!1;for(let t of e)if(!lS(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function VQf(e){let t=hh(e,UQf.README_EXT);if(!lS(t))return[];let r=t["code-samples"];if(!mjw(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function WQf(e,t,r){let n=hh(t,kh.EXAMPLES)??[],i=_gi(t,ADe.REDOCLY_CODE_SAMPLES_KEBAB,Pxu,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],u=[..._gi(t,ADe.REDOCLY_CODE_SAMPLES_CAMEL,Pxu,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...i];u.length>0&&n.push({"code-samples":u.map(d=>({name:d.label??d.lang,language:d.lang,code:d.source,install:void 0,docs:void 0}))});let f=VQf(t);return f.length>0&&n.push({"code-samples":f}),n.map(SIt.unknown)}function HQf(e){let t=hh(e,kh.AVAILABILITY);if(t==="ga"||t==="generally-available")return JH.GenerallyAvailable;if(t==="beta"||t==="pre-release")return JH.Beta;if(t==="deprecated")return JH.Deprecated;if(e.deprecated)return JH.Deprecated}function yMa(e){return{url:Ojw({url:e.url,variables:e.variables??{}}),description:e.description,name:Pjw(e),audiences:hh(e,kh.AUDIENCES)}}function Ojw({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,i);return e}function Pjw(e){let t=hh(e,[kh.SERVER_NAME_V1,kh.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function QQf(e){return hh(e,kh.PARAMETER_NAME)}function JQf(e){return hh(e,kh.SDK_VARIABLE)}function vMa({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let f of r){let d=hh(f,kh.IGNORE);if(d!=null&&d){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let c=wy(f)?n.resolveParameterReference(f):f,o=c.required??!1,l=O2e(c),g=[...i,c.name],O=WF(g);x9t({schema:c,logger:n.logger})?.includes(" ")&&n.logger.warn("Parameter example contains a space, which is ambiguous. Consider using enums for multiple examples, or use an encoding if a space is part of the parameter.");let P=c.schema!=null?a1(c.schema,!o,n,g,a,n.namespace,!1,new Set,x9t({schema:c,logger:n.logger})):o?Gp.primitive({nameOverride:void 0,generatedName:O,title:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:x9t({schema:c,logger:n.logger})}),description:void 0,availability:l,groupName:void 0}):Gp.optional({nameOverride:void 0,generatedName:O,title:void 0,value:Gp.primitive({nameOverride:void 0,generatedName:O,title:void 0,schema:Ay.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:x9t({schema:c,logger:n.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:l,groupName:void 0});if(c.in==="header"&&c.schema!=null&&!wy(c.schema)&&c.schema.default!=null){let M=c.schema.default;typeof M=="string"&&M.length>0&&(P=Gp.literal({nameOverride:void 0,generatedName:O,title:void 0,value:DB.string(M),description:void 0,availability:l,groupName:void 0}))}let j={name:c.name,schema:P,description:c.description,parameterNameOverride:QQf(c),availability:l,source:a};c.in==="query"?u.queryParameters.push(j):c.in==="path"?u.pathParameters.push({...j,variableReference:JQf(c)}):c.in==="header"?!wjw.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?u.headers.push({...j,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return u}var wjw=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function GQf(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r,schema:i??{},examples:wxu(n,t)}}}function G8n(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r.includes("*")?void 0:r,schema:i??{},examples:wxu(n,t)}}}function $Qf(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:wxu(n,t)}}}function wxu(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=hh(e,ADe.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,a])=>({name:a.summary??i,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,a])=>{let u=wy(a)?t.resolveExampleReference(a):a;return{name:u.summary??i,value:u.value,description:u.description}})),r}function jjw(e){for(let[t,r]of Object.entries(e.content))if(D4.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function Djw(e){for(let t in e.content)if(D4.parse(t)?.isOctetStream())return!0;return!1}function Sjw(e,t){let r=wy(e)?jxu(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!wy(i)&&i.type==="string"&&i.format==="binary")!=null}function $8n({requestBody:e,document:t,context:r,requestBreadcrumbs:n,source:i,namespace:a}){let u=wy(e)?r.resolveRequestBodyReference(e):e,f=jjw(u),d=f?.schema,c=f?.encoding,o=G8n(u.content,r);if(Djw(u))return m2e.octetStream({description:u.description,source:i});if(d!=null&&o==null||d!=null&&Sjw(d,t)){let g=wy(d)?jxu(d,t):{id:void 0,schema:d},O=a1(g.schema,!1,r,n,i,a),P=[];if(O.type==="object")for(let j of O.properties){if(j.schema.type==="primitive"&&j.schema.schema.type==="string"&&j.schema.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!1,isArray:!1}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="optional"&&j.schema.value.type==="primitive"&&j.schema.value.schema.type==="string"&&j.schema.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!0,isArray:!1}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="array"&&j.schema.value.type==="primitive"&&j.schema.value.schema.type==="string"&&j.schema.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!1,isArray:!0}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}if(j.schema.type==="optional"&&j.schema.value.type==="array"&&j.schema.value.value.type==="primitive"&&j.schema.value.value.schema.type==="string"&&j.schema.value.value.schema.format==="binary"){P.push({key:j.key,schema:g2e.file({isOptional:!0,isArray:!0}),description:j.schema.description,contentType:c?.[j.key]?.contentType});continue}P.push({key:j.key,schema:g2e.json(j.schema),description:void 0,contentType:c?.[j.key]?.contentType})}return m2e.multipart({name:wy(d)&&r.getNumberOfOccurrencesForRef(d)===1?g.id:void 0,description:g.schema.description,properties:P,source:i})}if(o==null)return;let l=a1(o.schema,!1,r,n,i,a,!0);return m2e.json({description:void 0,schema:l,contentType:o.contentType,fullExamples:o.examples,additionalProperties:!wy(o.schema)&&yNn(o.schema.additionalProperties),source:i})}function jxu(e,t){if(!e.$ref.startsWith(xnn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Yzr(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return wy(n)?jxu(n,t):{id:r,schema:n}}var Dxu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},KQf=new Set(Object.values(Dxu));var Ejw=["200","201","202","204"];function XQf({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let f=Ajw({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,c;for(let o of i!=null?[i]:Ejw){let l=t[o];l!=null&&(d=!0,c==null&&(c=YQf({operationContext:e,response:l,context:r,responseBreadcrumbs:n,streamFormat:a,source:u,namespace:r.namespace})))}if(c==null&&!d&&t.default!=null&&(c=YQf({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:a,source:u,namespace:r.namespace})),c!=null)switch(c.type){case"json":return{value:c,errors:f};case"streamingJson":case"streamingSse":return{value:c,errors:f};case"file":case"text":case"streamingText":return{value:c,errors:f};default:xc(c)}return{value:void 0,errors:f}}function YQf({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:a,namespace:u}){let f=wy(r)?n.resolveResponseReference(r):r;if(f.content!=null&&Object.entries(f.content).find(([l,g])=>{if(g.schema==null)return!1;let O=wy(g.schema)?n.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return SB.file({description:f.description,source:a});let d=GQf(f.content??{},n);if(d!=null&&t!=null)switch(t){case"json":return SB.streamingJson({description:f.description,responseProperty:hh(e.operation,kh.RESPONSE_PROPERTY),fullExamples:d.examples,schema:a1(d.schema,!1,n,i,a,u),source:a});case"sse":return SB.streamingSse({description:f.description,responseProperty:void 0,schema:YC(a1(d.schema,!1,n,i,a,u)),source:a})}let c=G8n(f.content??{},n);if(c!=null){if(t!=null)switch(t){case"json":return SB.streamingJson({description:f.description,responseProperty:void 0,fullExamples:c.examples,schema:a1(c.schema,!1,n,i,a,u),source:a});case"sse":return SB.streamingSse({description:f.description,responseProperty:void 0,schema:YC(a1(c.schema,!1,n,i,a,u)),source:a})}return SB.json({description:f.description,schema:a1(c.schema,!1,n,i,a,u),responseProperty:hh(e.operation,kh.RESPONSE_PROPERTY),fullExamples:c.examples,source:a})}for(let[o,l]of Object.entries(f.content??{})){let g=D4.parse(o);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo())return SB.file({description:f.description,source:a});if(g.isPlainText()){let O=l.schema;if(O==null)return SB.text({description:f.description,source:a});let P=wy(O)?n.resolveSchemaReference(O):O;return P.type==="string"&&P.format==="byte"?SB.file({description:f.description,source:a}):SB.text({description:f.description,source:a})}}}}function Ajw({responses:e,context:t,source:r,namespace:n}){let i={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let f=parseInt(a);if(f<400||f>600)continue;let d=wy(u)?t.resolveResponseReference(u):u,c=$Qf(d.content??{},t),o=Dxu[f];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}i[f]={statusCode:f,nameOverride:void 0,generatedName:o,description:d.description,schema:a1(c?.schema??{},!1,t,[o,"Body"],r,n),fullExamples:c?.examples,source:r}}return i}function aMr({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:a}){let{document:u,operation:f,path:d,method:c,baseBreadcrumbs:o,sdkMethodName:l}=e,g=hh(f,kh.IDEMPOTENT),O=hh(f,[kh.REQUEST_NAME_V1,kh.REQUEST_NAME_V2]),P=[...o,"Request"],j=vMa({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:P,path:d,httpMethod:c,source:a}),M=f.requestBody!=null?$8n({requestBody:f.requestBody,document:u,context:new R8n({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:P,source:a,namespace:t.namespace}):void 0;(j.queryParameters.length>0||j.headers.length>0)&&M!=null&&M.type==="json"&&M.schema.type!=="object"&&f.requestBody!=null?M=$8n({requestBody:f.requestBody,document:u,context:t,requestBreadcrumbs:[...P,"Body"],source:a,namespace:t.namespace}):f.requestBody!=null&&(M=$8n({requestBody:f.requestBody,document:u,context:t,requestBreadcrumbs:[...P],source:a,namespace:t.namespace}));let q=[...o,"Response"],B=XQf({operationContext:e,streamFormat:i,responses:f.responses,context:t,responseBreadcrumbs:q,responseStatusCode:r,source:a}),I=HQf(f),C=WQf(e,f,t),F=hh(f,kh.SERVER_NAME_V2);return{summary:f.summary,internal:hh(f,ADe.INTERNAL),idempotent:g,audiences:hh(f,kh.AUDIENCES)??[],operationId:f.operationId!=null&&n!=null?f.operationId+"_"+n:f.operationId,tags:t.resolveTagsToTagIds(f.tags),namespace:t.namespace,sdkName:l,pathParameters:j.pathParameters,queryParameters:j.queryParameters,headers:j.headers,requestNameOverride:O??void 0,generatedRequestName:WF(P),request:M,response:B.value,errors:B.errors,server:F!=null?[{name:F,url:void 0,audiences:void 0}]:(f.servers??[]).map(K=>yMa(K)),description:f.description,authed:Mjw(f,u),availability:I,method:c,path:d,examples:C,pagination:e.pagination,source:a}}function Mjw(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function kQf({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:a,operationParameters:u}=e,f=r.discriminant.name,d=r.discriminant.value,c=r["response-status-code"],o=ZQf({context:t,headerToIgnore:f,parameters:a}),l=ZQf({context:t,headerToIgnore:f,parameters:u}),g=aMr({operationContext:{...e,pathItemParameters:o,operationParameters:l,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([P])=>parseInt(P)!==c))}},context:t,streamFormat:void 0,source:n}),O=aMr({operationContext:{...e,pathItemParameters:o,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:c,streamFormat:void 0,source:n});return O.headers.push({name:f,schema:Gp.literal({nameOverride:void 0,generatedName:WF([f]),title:void 0,description:void 0,availability:void 0,value:DB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n}),{sync:g,async:O}}function ZQf({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=wy(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var Sxu="stream";function nJf({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:aMr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let n=eJf({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let c=Yzr(n.schemaReference);c!=null&&t.excludeSchema(c)}let i=tJf({operation:e.operation,response:r.responseStream}),a=aMr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Sxu}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Sxu]},context:t,streamFormat:r.format,suffix:Sxu,source:t.source});a.examples=a.examples.filter(c=>rJf(c,t)!==!1);let u=eJf({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),f=tJf({operation:e.operation,response:r.response}),d=aMr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:f}},context:t,source:t.source});return d.examples=d.examples.filter(c=>rJf(c,t)!==!0),{streaming:a,nonStreaming:d}}default:xc(r)}}function eJf({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=wy(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=G8n(i.content,e);if(a==null)return;let u=wy(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let f=u.properties?.[r.streamConditionProperty];f!=null&&wy(f)&&(f=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...f??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[D4.APPLICATION_JSON]:{schema:d}}},schemaReference:wy(a.schema)?a.schema:void 0}}function tJf({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[D4.APPLICATION_JSON]:{schema:t}}}}}function rJf(e,t){return e._visit({unknown:r=>{let n=zie.serialization.ExampleEndpointCallSchema.parse(r);if(!n.ok){t.logger.error("Failed to parse example",n.errors.toString());return}if(n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}function iJf({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:a,method:u,baseBreadcrumbs:f,sdkMethodName:d}=t,c=[...f,"Payload"],o=vMa({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:c,path:a,httpMethod:u,source:r});if(i.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let l=$8n({requestBody:i.requestBody,document:n,context:e,requestBreadcrumbs:[...f,"Payload"],source:r,namespace:e.namespace});if(l==null||l.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(i.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:i.summary,sdkName:d,namespace:e.namespace,method:u,operationId:i.operationId,tags:e.resolveTagsToTagIds(i.tags),headers:o.headers,generatedPayloadName:WF(c),payload:l.schema,description:i.description,examples:xjw(l.fullExamples),source:r}}function xjw(e){if(e==null)return[];let t=[];for(let r of e){let n=Xzr(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function Exu({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=hh(r,kh.IGNORE);if(i!=null&&i){e.logger.info(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=Tjw(r,e),u=wQf(e.document,r),f={...t,sdkMethodName:a,baseBreadcrumbs:Cjw({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path}),operation:r,operationParameters:r.parameters??[],pagination:u};if(n){let l=iJf({context:e,operationContext:f,source:e.source});return l!=null?{type:"webhook",value:l}:void 0}let d=OQf(r);if(d!=null){let l=nJf({context:e,operationContext:f,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let c=gQf(r);if(c!=null){let l=kQf({context:e,operationContext:f,asyncExtension:c,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:aMr({context:e,operationContext:f,streamFormat:void 0,source:e.source})}}function Tjw(e,t){let r=hh(e,kh.SDK_METHOD_NAME),n=hh(e,kh.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function Cjw({sdkMethodName:e,operation:t,httpMethod:r,path:n}){let i=[];if(e!=null){if(e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&i.push(typeof a=="string"?a:a.name)}i.push(e.methodName)}else t.operationId!=null?i.push(t.operationId):i.push(_A(`${r}_${n.split("/").join("_")}`));return i}function aJf(e,t,r,n){let i=[],a=uJf(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let f of a){let d=qjw({operation:f.operation}),c=Exu({context:n,pathItemContext:{...u,method:f.method},operation:f.operation,convertToWebhook:d});c!=null&&i.push(c)}return i}function oJf(e,t,r,n){let i=[],a=uJf(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let f of a){let d=Exu({context:n,pathItemContext:{...u,method:f.method},operation:f.operation,convertToWebhook:!0});d!=null&&i.push(d)}return i}function uJf(e){let t=[];return e.get!=null&&t.push({method:C$.Get,operation:e.get}),e.post!=null&&t.push({method:C$.Post,operation:e.post}),e.put!=null&&t.push({method:C$.Put,operation:e.put}),e.delete!=null&&t.push({method:C$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:C$.Patch,operation:e.patch}),t}function qjw({operation:e}){return hh(e,[kh.WEBHOOK])??!1}function sJf(e){let t=hh(e,kh.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=hh(e,kh.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function cJf(e){return hh(e,kh.FERN_BASIC_AUTH)}function Axu(e,t){if(wy(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return Ijw(e,t)}function Ijw(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=hh(e,ADe.BEARER_FORMAT),n=hh(e,kh.FERN_HEADER_AUTH);return PU.header({headerName:e.name,prefix:r!=null?"Bearer":n?.prefix,headerVariableName:n?.name??hh(e,kh.HEADER_VARIABLE_NAME),headerEnvVar:n?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=hh(e,kh.FERN_BEARER_TOKEN);return PU.bearer({tokenVariableName:r?.name??hh(e,kh.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=cJf(e),n=sJf(e);return PU.basic({usernameVariableName:r?.username?.name??n.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??n.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return PU.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return PU.oauth({scopesEnum:Bjw(e,t)})}throw new Error(`Failed to convert security scheme ${JSON.stringify(e)}`)}function Bjw(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Kzr({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t}),i=YC(n);if(i.type==="enum")return i}}function lJf(e){return hh(e,kh.BASE_PATH)}var Njw=RDe.record(RDe.string(),RDe.object({summary:RDe.string().optional(),description:RDe.string().optional()}));function fJf({document:e,context:t}){return _gi(e,kh.GROUPS,Njw,t.logger)}function dJf({context:e,document:t}){return hh(t,kh.FERN_VERSION)??void 0}function pJf(e){let t=hh(e,kh.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?hgi({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function _Jf(e){let t=hh(e,kh.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?hgi({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function hJf(e){let t=hh(e,kh.SDK_VARIABLES);return t==null?{}:Object.fromEntries(Object.entries(t).map(([r,n])=>{if(n.type==="string")return[r,{nameOverride:void 0,generatedName:WF([r]),title:n.title,schema:jD.string({default:ONn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${r} has unsupported schema ${JSON.stringify(n)}`)}))}var zjw="webhooks";function yJf(e){return hh(e,zjw)??{}}var bMa=class extends z8n{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discrminatedUnionReferences={};discrminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:u})}getDummy(){return new R8n({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discrminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discrminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discrminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discrminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discrminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discrminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function vJf(e){return hh(e,kh.RESOLUTIONS)}function bJf({openapi:e}){let t=vJf(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let a of n.resolutions)e=Rjw({openapi:e,schemaReference:a,schemaName:n.name}),e=gJf({openapi:e,replaceReference:a,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(u=>[i,u]))}}return e}function Rjw({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(a=>a.replace("~1","/")),i=e;for(let a of n){let u=i[a];if(u==null)return e;i=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function gJf({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(d=>t.startsWith(d)).sort((d,c)=>c.length-d.length)[0];if(i!=null){let d=n[i];if(d!=null){let c=r.replace(i,d);return gJf({openapi:e,replaceReference:t,schemaReference:c,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replace("~1","/")),u=e;for(let d of a.slice(0,-1)){let c=u[d];if(c==null)return e;u=c}let f=a[a.length-1];return f==null||(u[f]={$ref:r}),e}function gMa({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=bJf({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([ee,J])=>Axu(J,n)==null?[]:[ee,Axu(J,n)])),u=new Set(...Object.entries(a).map(([ee,J])=>J.type==="basic"||J.type==="bearer"?"Authorization":J.type==="header"?J.headerName:null)),f=new bMa({document:e,taskContext:t,authHeaders:u,options:r,source:n,namespace:i}),d=hJf(e),c=pJf(e),o=_Jf(e),l=r.audiences??[],g=[],O=[];Object.entries(e.paths??{}).forEach(([ee,J])=>{if(J==null)return;t.logger.debug(`Converting path ${ee}`);let G=aJf(ee,J,e,f);for(let te of G){let Ye=mJf({operation:te});if(!(l.length>0&&!l.some(Re=>Ye.includes(Re))))switch(te.type){case"async":g.push(te.sync),g.push(te.async);break;case"http":g.push(te.value);break;case"streaming":g.push(te.streaming),te.nonStreaming&&g.push(te.nonStreaming);break;case"webhook":O.push(te.value);break;default:xc(te)}}}),Object.entries(yJf(e)).forEach(([ee,J])=>{if(J==null)return;t.logger.debug(`Converting path ${ee}`);let G=oJf(ee,J,e,f);for(let te of G){let Ye=mJf({operation:te});l.length>0&&!l.some(Re=>Ye.includes(Re))||O.push(te.value)}});let P=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([ee,J])=>{if(!wy(J)){let G=hh(J,kh.IGNORE);if(G!=null&&G)return[];if(KQf.has(ee))return[ee,a1({...J,"x-fern-type-name":`${ee}Body`},!1,f,[ee],n,i)]}return[ee,a1(J,!1,f,[ee],n,i)]}).filter(ee=>ee.length>0)),j=Fjw(P,f,n),M=Ljw(j,f),q={};for(let[ee,J]of Object.entries(M)){let G=YC(J);f.isSchemaExcluded(ee)||(q[ee]=G,t.logger.debug(`Converted schema ${ee}`))}let B=new Zzr(M),I=new Jja(M,f.logger),C=g.map(ee=>{let J=ee.examples,G=J;if(!r.disableExamples&&(J.length===0||J.every(ggi))){let Re=I.buildEndpointExample(ee);Re.length>0&&(G=[...Re,...J.filter(wt=>!ggi(wt))])}let te=ee.request,Ye=ee.response;return{...ee,request:te?.type==="json"?{...te,schema:YC(te.schema)}:te,response:Ye?.type==="json"?{...Ye,schema:YC(Ye.schema)}:Ye,queryParameters:ee.queryParameters.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,availability:Re.availability,source:Re.source})),pathParameters:ee.pathParameters.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,variableReference:Re.variableReference,availability:Re.availability,source:Re.source})),headers:ee.headers.map(Re=>({description:Re.description,name:Re.name,schema:YC(Re.schema),parameterNameOverride:Re.parameterNameOverride,env:Re.env,availability:Re.availability,source:Re.source})),examples:G,errors:by(ee.errors,Re=>{let wt=Re.fullExamples?.map(Ct=>{let Wt=Xzr(Ct.value);if(Wt!=null)return{name:Ct.name,description:Ct.description,example:Wt}}).filter($M);if(wt?.length===0){let Ct=B.buildExample({schema:Re.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Ct!=null&&wt.push({name:void 0,description:void 0,example:Ct})}return{generatedName:Re.generatedName,nameOverride:Re.nameOverride,schema:YC(Re.schema),description:Re.description,source:Re.source,examples:wt}})}}),F=fJf({document:e,context:f});return{apiVersion:dJf({context:f,document:e}),basePath:lJf(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(F??{}).map(([ee,J])=>[ee,{summary:J.summary??void 0,description:J.description??void 0}])),servers:(e.servers??[]).map(ee=>yMa(ee)),tags:{tagsById:Object.fromEntries((e.tags??[]).map(ee=>[ee.name,{id:ee.name,description:ee.description}])),orderedTagIds:e.tags?.map(ee=>ee.name)},endpoints:C,webhooks:O,channel:[],groupedSchemas:Wja(i,q),securitySchemes:a,hasEndpointsMarkedInternal:C.some(ee=>ee.internal),nonRequestReferencedSchemas:f.getReferencedSchemas(),variables:d,globalHeaders:c,idempotencyHeaders:o}}function Fjw(e,t,r){let n={};for(let[i,a]of Object.entries(e)){if(a.type!=="object"){n[i]=a;continue}let u={$ref:`#/components/schemas/${i}`},f=t.getReferencesFromDiscriminatedUnion(u);if(f==null){n[i]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!f.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!f.discriminants.has(o.propertyKey)),source:r};n[i]=d;let c=OJf({schema:a,schemas:e});for(let o of[...new Set(c)]){let l=n[o]??e[o];l==null||l.type!=="object"||(n[o]={...l,type:"object",properties:l.properties.filter(g=>!f.discriminants.has(g.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(g=>!f.discriminants.has(g.propertyKey))})}}return n}function Ljw(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let a={$ref:`#/components/schemas/${n}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[n]=i;continue}let f=[];for(let c of i.properties)if(u.discriminants.has(c.key)){let o=u.discriminants.get(c.key);o!=null&&f.push({...c,schema:Gp.literal({nameOverride:void 0,generatedName:WF([i.generatedName,o]),title:void 0,value:DB.string(o),groupName:void 0,description:void 0,availability:i.availability})})}else f.push(c);let d={...i,type:"object",properties:f};r[n]=d}return r}function OJf({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...OJf({schema:i,schemas:t}))}return r}function mJf({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:xc(e)}return t}async function wJf({openApi:e,taskContext:t,options:r,source:n,namespace:i}){let a=await(0,PJf.convertObj)(e,{});return gMa({openApi:a.openapi,taskContext:t,options:r,source:n,namespace:i})}var zin={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,cooerceEnumsToLiterals:!0};async function Rin({absoluteFilePathToWorkspace:e,specs:t,taskContext:r,optionOverrides:n}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channel:[],groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let a of t){let u=(await(0,xxu.readFile)(a.absoluteFilepath)).toString(),f=jq(e,a.source.file);a.source.relativePathToDependency!=null&&(f=yf(a.source.relativePathToDependency,f));let d=a.source.type==="protobuf"?NAr.protobuf({file:f}):NAr.openapi({file:f});if(u.includes("openapi")||u.includes("swagger")){let c=await lUf({absolutePathToOpenAPI:a.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:a.absoluteFilepathToOverrides});if(Wjw(c)){let o=gMa({openApi:c,taskContext:r,options:Mxu({specSettings:a.settings,overrides:n}),source:d,namespace:a.namespace});i=jJf(i,o)}else if(Hjw(c)){let o=await wJf({openApi:c,taskContext:r,options:Mxu({specSettings:a.settings}),source:d,namespace:a.namespace});i=jJf(i,o)}}else if(u.includes("asyncapi")){let c=await Vjw({absoluteFilePathToAsyncAPI:a.absoluteFilepath,context:r,absoluteFilePathToAsyncAPIOverrides:a.absoluteFilepathToOverrides}),o=O3f({document:c,taskContext:r,options:Mxu({specSettings:a.settings}),source:d,asyncApiOptions:Ujw({specSettings:a.settings}),namespace:a.namespace});o.channel!=null&&i.channel.push(o.channel),o.groupedSchemas!=null&&(i.groupedSchemas=DJf(i.groupedSchemas,o.groupedSchemas)),o.basePath!=null&&(i.basePath=o.basePath)}else r.failAndThrow(`${a.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}function Mxu({specSettings:e,overrides:t}){return{disableExamples:t?.disableExamples??zin.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.shouldUseUndiscriminatedUnionsWithLiterals??zin.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.shouldUseTitleAsName??zin.useTitlesAsName,audiences:t?.audiences??e?.audiences??zin.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??zin.optionalAdditionalProperties,cooerceEnumsToLiterals:t?.cooerceEnumsToLiterals??e?.cooerceEnumsToLiterals??zin.cooerceEnumsToLiterals}}function Ujw({specSettings:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??J4f.naming}}function jJf(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channel:[...e.channel,...t.channel],groupedSchemas:DJf(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function DJf(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,n]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...n}:e.namespacedSchemas[r]=n;return e}async function Vjw({absoluteFilePathToAsyncAPI:e,absoluteFilePathToAsyncAPIOverrides:t,context:r}){let n=(await(0,xxu.readFile)(e)).toString(),i=await d0.load(n);return t!=null?await rAa({absoluteFilepathToOverrides:t,context:r,data:i}):i}function Wjw(e){return e.openapi!=null}function Hjw(e){return e.swagger!=null}function OMa({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Txu({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let a=PC(i.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!i.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let u={type:a};return i.allowMultiple&&(u["allow-multiple"]=!0),e.description!=null&&(u.docs=e.description),e.parameterNameOverride!=null&&(u.name=e.parameterNameOverride),e.availability!=null&&(u.availability=I3(e.availability)),u}function Txu({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,groupName:void 0}),context:t,declarationFile:Ms.of($A),fileContainingReference:r,namespace:n}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undisciminated"){let a=[];for(let[u,f]of Object.entries(i.value.schemas))f.type==="literal"&&f.value.type==="string"&&(gNn.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:ygi(f.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(i.value.schemas.length===2){let[u,f]=i.value.schemas;if(u!=null&&f!=null&&mMa({array:u,primitive:f}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:f,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(u!=null&&f!=null&&mMa({array:u,primitive:f}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}}for(let[u,f]of Object.entries(i.value.schemas))return Txu({schema:f,context:t,fileContainingReference:r,namespace:n})}else if(i.type==="object")return}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let i=t.getSchema(e.value.schema,n);if(i==null)return;if(i.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,declarationFile:Ms.of($A),namespace:n}),allowMultiple:!0}}if(e.value.type==="array")return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undisciminated"){let i=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(gNn.test(u.value.value)?i.push(u.value.value):i.push({value:u.value.value,name:ygi(u.value.value)}));if(i.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:i}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&mMa({array:a,primitive:u}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0};if(a!=null&&u!=null&&mMa({array:u,primitive:a}))return{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return Txu({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return;return{value:Z1({schema:e,context:t,fileContainingReference:r,namespace:n}),allowMultiple:!1}}return e.type==="array"?{value:Z1({schema:gb.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0}),context:t,fileContainingReference:r,namespace:n}),allowMultiple:!0}:{value:Z1({schema:e,context:t,fileContainingReference:r,namespace:n}),allowMultiple:!1}}function mMa({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function SJf({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=Qjw(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=Jjw({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=J5r(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function Qjw(e){let t={};return e.forEach(r=>{let n=J5r(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function Jjw({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=J5r(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function J5r(e){switch(e.type){case"primitive":return EJf(e.value);case"object":return AJf(e.properties);case"array":return Gjw(e.value);case"map":return $jw(e.value);case"oneOf":return Kjw(e.value);case"enum":return e.value;case"literal":return Yjw(e.value);case"unknown":return J5r(e.value);default:xc(e)}}function EJf(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:xc(e)}}function AJf(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,J5r(r)]))}function Gjw(e){return e.map(t=>J5r(t))}function $jw(e){return Object.fromEntries(e.map(t=>[EJf(t.key),J5r(t.value)]))}function Kjw(e){return e.type==="discriminated"?AJf(e.value):J5r(e.value)}function Yjw(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:xc(e)}}function oMr(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function PMa(e,t){return t??(e?.groupName!=null?oMr(e.groupName):void 0)}function MJf({channel:e,context:t,declarationFile:r}){let n={path:e.path,auth:!1};e.summary!=null&&(n["display-name"]=e.summary);let i=oMr(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=Bja({pathParameter:d,context:t,fileContainingReference:r,namespace:i});Object.keys(a).length>0&&(n["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let c=OMa({queryParameter:d,context:t,fileContainingReference:r,namespace:i});c!=null&&(u[d.name]=c)}Object.keys(u).length>0&&(n["query-parameters"]=u);let f={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let c=M9t({header:d,context:t,fileContainingReference:r,namespace:i});f[d.name]=c}Object.keys(f).length>0&&(n.headers=f),t.builder.addChannel(r,{channel:n}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:Z1({schema:e.subscribe,context:t,fileContainingReference:r,namespace:i})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:Z1({schema:e.publish,context:t,fileContainingReference:r,namespace:i})}});for(let d of e.examples){let c=SJf({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:c})}}var xJf="Production",TJf="Default";function CJf(e){return Object.entries(e).reduce((t,[r,n])=>(BIn(n)?Object.entries(n.urls).forEach(([i,a])=>{t[i]=a}):t[r]=typeof n=="string"?n:n.url,t),{})}function qJf(e){if(e.environmentOverrides!=null){for(let[f,d]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:f,schema:d});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let f of e.ir.servers){let d=f.audiences?{url:f.url,audiences:f.audiences}:f.url;if(f.name==null){r.push(d);continue}t[f.name]=d}let n={},i=[];for(let f of e.ir.endpoints)for(let d of f.server){if(d.url==null)continue;let c=d.audiences?{url:d.url,audiences:d.audiences}:d.url;if(d.name==null){i.push(c);continue}n[d.name]=c}let a=Object.keys(t).length,u=Object.keys(n).length;if(a===0&&u===0){let f=e.ir.servers[0]?.url,d=e.ir.servers[0]?.audiences;f!=null&&(e.builder.addEnvironment({name:TJf,schema:d?{url:f,audiences:d}:f}),e.builder.setDefaultEnvironment(TJf))}else if(a>0&&u===0){let f=0;r.length>0&&e.logger.error(`Skipping servers ${r.map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);for(let[d,c]of Object.entries(t))f===0&&e.builder.setDefaultEnvironment(d),e.builder.addEnvironment({name:d,schema:c}),f+=1}else if(u>0){(r.length>0||i.length>0)&&e.logger.error(`Skipping servers ${[...r,...i].map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);let f=Object.entries(t)[0];if(f!=null){let[d,c]=f;e.setDefaultServerName(d)}e.builder.addEnvironment({name:xJf,schema:{urls:{...CJf(t),...CJf(n)}}}),e.builder.setDefaultEnvironment(xJf)}}function wMa(e){return PC(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var Cxu=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},Xjw=.75,Zjw=new Set("authorization");function IJf(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let i="optional<string>";if(n.name==null&&n.env==null&&typeof n.schema=="string")i=n.schema;else if(n!=null){let a=n.schema?_Nn(n.schema):void 0,u=a!=null?oMr(a):void 0,f=Ms.of("api.yml");i={name:n.name,env:n.env,type:n.schema!=null?PC(Z1({schema:n.schema,context:e,fileContainingReference:u?yf(Ms.of(_A(u)),f):f,namespace:u}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:i})}if(e.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let a of i.headers){if(Zjw.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let f=t[a.name],d=M9t({header:{...a,schema:f?.schema??a.schema,name:f?.name??a.name},fileContainingReference:Ms.of(m5),context:e,namespace:void 0});u=new Cxu(d),r[a.name]=u}u.increment()}let n=e.ir.endpoints.length*Xjw;for(let[i,a]of Object.entries(r)){let u=t[i],f=a.count===e.ir.endpoints.length,d=a.count>=n;u==null&&(f?e.builder.addGlobalHeader({name:i,schema:a.schema}):d&&e.builder.addGlobalHeader({name:i,schema:wMa(a.schema)}))}}}function BJf(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?_Nn(t.schema):void 0,n=r!=null?oMr(r):void 0,i=M9t({header:{...t,schema:t.schema??gb.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:jD.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Ms.of(m5),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:wMa(i)})}}function jk(e){switch(e.type){case"primitive":return zJf(e.value);case"object":return RJf(e.properties);case"array":return FJf(e.value);case"map":return kjw(e.value);case"oneOf":return eDw(e.value);case"enum":return e.value;case"literal":return tDw(e.value);case"unknown":return jk(e.value);default:xc(e)}}function NJf(e){switch(e.type){case"withStreaming":return{stream:FJf(e.value)};case"withoutStreaming":return{body:jk(e.value)};default:xc(e)}}function zJf(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:xc(e)}}function RJf(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,jk(r)]))}function FJf(e){return e.map(t=>jk(t))}function kjw(e){return Object.fromEntries(e.map(t=>[zJf(t.key),jk(t.value)]))}function eDw(e){return e.type==="discriminated"?RJf(e.value):jk(e.value)}function tDw(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:xc(e)}}function LJf({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=rDw(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=nDw(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=iDw({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=jk(e.request)),e.response!=null&&(r.response=NJf(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(n=>n.type==="language"?{name:n.name??void 0,docs:n.description??void 0,language:n.language,code:n.code,install:n.install??void 0}:{name:n.name??void 0,docs:n.description??void 0,sdk:n.sdk,code:n.code}).filter($M)),r)}function rDw(e){let t={};return e.forEach(r=>{let n=jk(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function nDw(e){let t={};return e.forEach(r=>{let n=jk(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function iDw({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=jk(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function UJf(e){return C$._visit(e,{get:()=>zie.HttpMethodSchema.Get,post:()=>zie.HttpMethodSchema.Post,put:()=>zie.HttpMethodSchema.Put,patch:()=>zie.HttpMethodSchema.Patch,delete:()=>zie.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unkown http method is unsupported")}})}function VJf({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:n}=r.ir,i=[],a=new Set,u=e.path,f=PMa(e.sdkName,e.namespace),d={};for(let j of e.pathParameters)j.parameterNameOverride&&(u=u.replace(j.name,j.parameterNameOverride)),d[j.parameterNameOverride??j.name]=Bja({pathParameter:j,context:r,fileContainingReference:t,namespace:f}),a.add(j.name);let c={};for(let j of e.queryParameters){let M=OMa({queryParameter:j,context:r,fileContainingReference:t,namespace:f});M!=null&&(c[j.name]=M,a.add(j.name))}let o;e.pagination!=null&&(e.pagination.type==="cursor"?o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results}:o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage});let l={path:u,method:UJf(e.method),auth:e.authed,docs:e.description??void 0,pagination:o};Object.keys(d).length>0&&(l["path-parameters"]=d),e.summary!=null&&(l["display-name"]=e.summary);let g={},O=r.builder.getGlobalHeaderNames(),P=e.headers.filter(j=>!O.has(j.name));for(let j of P){let M=M9t({header:j,context:r,fileContainingReference:t,namespace:f});g[j.name]=M,a.add(typeof M=="string"?j.name:M.name??j.name)}if(e.request!=null){let j=oDw({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,queryParameters:Object.keys(c).length>0?c:void 0,nonRequestReferencedSchemas:Array.from(n),headers:Object.keys(g).length>0?g:void 0,usedNames:a,namespace:f});l.request=j.value,i=[...i,...j.schemaIdsToExclude??[]]}else{let j=Object.keys(c).length>0,M=Object.keys(g).length>0,q={};(j||M)&&(q.name=e.requestNameOverride??e.generatedRequestName),j&&(q["query-parameters"]=c),M&&(q.headers=g),Object.keys(q).length>0&&(l.request=q)}if(e.response!=null&&e.response._visit({json:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l.response={docs:j.description??void 0,type:PC(M)},j.responseProperty!=null&&(l.response.property=j.responseProperty)},streamingJson:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l["response-stream"]={docs:j.description??void 0,type:PC(M),format:"json"}},streamingSse:j=>{let M=Z1({schema:j.schema,context:r,fileContainingReference:t,namespace:f});l["response-stream"]={docs:j.description??void 0,type:PC(M),format:"sse"}},file:j=>{l.response={docs:j.description??void 0,type:"file"}},streamingText:j=>{l["response-stream"]={docs:j.description??void 0,type:"text"}},text:j=>{l.response={docs:j.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let j=r.getDefaultServerName(),M=e.server[0];M==null?j!=null&&(l.url=j):l.url=M.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=I3(e.availability)),Object.entries(e.errors).forEach(([j,M])=>{let q=M.generatedName,B=Ms.of($A);r.builder.enableUniqueErrorsPerEndpoint&&(q=`${e.generatedRequestName}${M.generatedName}`,M.schema!=null&&(M.schema.type!=="reference"&&M.schema.type!=="oneOf"?M.schema.generatedName=`${e.generatedRequestName}${M.schema.generatedName}`:M.schema.type==="oneOf"&&(M.schema.value.generatedName=`${e.generatedRequestName}${M.schema.value.generatedName}`)));let I={"status-code":parseInt(j)},C=R4f({location:WJf,namespaceOverride:f});if(M.schema!=null){let ee=Z1({schema:M.schema,context:r,fileContainingReference:C,declarationFile:C,namespace:f});I.type=PC(ee),I.docs=M.description}r.builder.addError(C,{name:q,schema:r.isErrorUnknownSchema(parseInt(j))?{...I,type:"unknown"}:I}),l.errors==null&&(l.errors=[]);let F=r.builder.addImport({file:t,fileToImport:C});l.errors.push(F!=null?`${F}.${q}`:q),I.type!=null&&M.examples?.forEach(ee=>{let J={value:jk(ee.example),name:ee.name,docs:ee.description};r.builder.addErrorExample(C,{name:q,example:J})})}),e.examples.length>0&&(l.examples=aDw({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[qxu,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:i}}function aDw({endpointExamples:e,context:t}){return e.map(r=>{try{return LJf({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function oDw({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:a,queryParameters:u,nonRequestReferencedSchemas:f,headers:d,usedNames:c,namespace:o}){if(n.type==="json"){let l=n.schema.type==="reference"?n.schema.schema:void 0,g=n.schema.type==="reference"?r.getSchema(n.schema.schema,o):n.schema;if(g?.type!=="object"||l!=null&&f.includes(l)){let q=Z1({schema:n.schema,fileContainingReference:t,context:r,namespace:o}),B={schemaIdsToExclude:[],value:{body:q}},I=Object.keys(u??{}).length>0,C=Object.keys(d??{}).length>0;return I&&(B.value["query-parameters"]=u),C&&(B.value.headers=d),(I||C)&&(B.value.name=i??a),n.contentType!=null&&(B.value["content-type"]=n.contentType),n.description!=null&&(B.value.docs=n.description),B}let O=Object.fromEntries(g.properties.filter(q=>q.readonly==null?!0:!((e.method==="POST"||e.method==="PUT")&&q.readonly)).map(q=>{let B=Z1({schema:q.schema,fileContainingReference:t,context:r,namespace:o}),I=q.nameOverride??q.key,C=I3(q.availability);if(!c.has(I)&&q.audiences.length<=0)return c.add(I),q.nameOverride!=null?[q.key,{type:PC(B),docs:dgi(B),name:q.nameOverride,availability:C}]:[q.key,C?{...typeof B=="string"?{type:B}:B,availability:C}:B];let F={type:PC(B),docs:dgi(B)};return c.has(I)&&(F.name=q.generatedName),q.audiences.length>0&&(F.audiences=q.audiences),C!=null&&(F.availability=C),c.add(I),[q.key,F]})),P=g.allOf.map(q=>{let B=Z1({schema:gb.reference(q),fileContainingReference:t,context:r,namespace:o});return PC(B)}),j={properties:O};P.length>0&&(j.extends=P),n.additionalProperties&&(j["extra-properties"]=!0);let M={name:i??g.nameOverride??g.generatedName,"query-parameters":u,headers:d,body:j};return n.contentType!=null&&(M["content-type"]=n.contentType),n.description!=null&&(M.docs=n.description),{schemaIdsToExclude:l!=null?[l]:[],value:M}}else{if(n.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":D4.APPLICATION_OCTET_STREAM,...n.description?{docs:n.description}:{}}};if(n.type==="multipart"){let l=Object.fromEntries(n.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let P={type:O};return g.description!=null&&(P.docs=g.description),g.contentType!=null&&(P["content-type"]=g.contentType),[g.key,P]}return[g.key,O]}else{let O=Z1({schema:g.schema.value,fileContainingReference:t,context:r,namespace:o});return g.contentType!=null&&(typeof O=="string"?O={type:O,"content-type":g.contentType}:O["content-type"]=g.contentType),[g.key,O]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??a,"query-parameters":u,headers:d,body:{properties:l},"content-type":D4.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else xc(n)}}function uDw({location:e,namespaceOverride:t}){return t!=null?{...e,file:yf(Ms.of(t),e.file)}:e}function sDw(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:Ms.of(`${_A(r)}.yml`),endpointId:e.summary!=null?_A(e.summary):_A(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Ms.of($A),endpointId:_A(e.summary)}:{file:Ms.of($A),endpointId:_A(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Ms.of($A),endpointId:n};let i=SOi(r),a=SOi(n);if(Yqt(i,a))return{file:Ms.of("__package__.yml"),endpointId:r};let u=fDw({operationId:n,tag:r,path:e.path,method:e.method});if(u!=null)return u;let f=[];for(let d=0;d<i.length;++d){let c=i[d];if(c!=null&&c===a[d])f.push(c);else{let o=_A(r);return{file:Ms.of(`${o}.yml`),endpointId:n,tag:r}}}if(f.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Ms.of(_A(f.join("_"))+".yml"),endpointId:_A(a.slice(f.length).join("_")),tag:r}}function EOi(e){let t=e.tags[0];if(e.sdkName!=null){let r=A1u({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Ms.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return uDw({namespaceOverride:e.namespace,location:sDw(e)})}function SOi(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=W8t(t),t}var cDw=new RegExp("[^a-zA-Z0-9{}]+"),lDw=new RegExp("[{}]","g");function fDw({operationId:e,tag:t,path:r,method:n}){let a=`${r.split(cDw).join("_").replaceAll(lDw,"_")}_${n.toLowerCase()}`;if(e.endsWith(a))return{file:Ms.of(_A(t)+".yml"),endpointId:_A(e.slice(0,-1*a.length)),tag:t}}function HJf(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let a of r){let{endpointId:u,file:f,tag:d}=EOi(a),c=f.split(".")[0];c!=null&&t.add(c);let o;if(a.sdkName!=null){let O=e.ir.groups;for(let P of a.sdkName.groupName){let j=typeof P=="string"?P:P.name,M=O[j];if(M==null)break;if(M.summary!=null||M.description!=null){o=O[j];break}}}let l=d==null?void 0:n.tagsById[d],g=VJf({context:e,endpoint:a,declarationFile:f});i=[...i,...g.schemaIdsToExclude],e.builder.addEndpoint(f,{name:u,schema:g.value,source:a.source!=null?Ann(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(f,{"display-name":o?.summary??l?.id,docs:o?.description??l?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}function QJf(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?oMr(r.groupName):void 0,i=Z1({schema:gb.primitive(r),context:e,fileContainingReference:Ms.of($A),namespace:n});e.builder.addVariable({name:t,schema:{type:PC(i),docs:r.description??void 0}})}}function JJf(e){for(let t of e.ir.webhooks){let r=_Dw({webhook:t,context:e});if(r==null)continue;let n=PMa(t.sdkName,t.namespace),i={};for(let u of t.headers)i[u.name]=M9t({header:u,context:e,fileContainingReference:r.file,namespace:n});let a={method:t.method,"display-name":t.summary??void 0,headers:i,payload:Z1({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:jk(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function dDw({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:yf(Ms.of(t),e.file)}:e}function pDw({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:Ms.of($A),endpointId:n};let i=SOi(r),a=SOi(n);if(Yqt(i,a))return{file:Ms.of("__package__.yml"),endpointId:r};let u=[];for(let f=0;f<i.length;++f){let d=i[f];if(d!=null&&d===a[f])u.push(d);else{let c=_A(r);return{file:Ms.of(`${c}.yml`),endpointId:n,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Ms.of(_A(u.join("_"))+".yml"),endpointId:_A(a.slice(u.length).join("_")),tag:r}}function _Dw({webhook:e,context:t}){return e.sdkName!=null?{file:z4f({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:dDw({namespaceOverride:e.namespace,location:pDw({webhook:e,context:t})})}var hDw=Ms.of($A);function GJf(e){switch(e.type){case"object":return X9t(e.groupName);case"enum":return X9t(e.groupName);case"oneOf":return X9t(e.value.groupName);case"array":return X9t(e.groupName);case"map":return X9t(e.groupName);case"reference":return X9t(e.groupName);case"literal":return X9t(e.groupName);case"optional":return X9t(e.groupName);case"nullable":return X9t(e.groupName);case"primitive":return X9t(e.groupName);case"unknown":return hDw;default:xc(e)}}function X9t(e){return hNn(e)}var qxu="external",WJf=Ms.of($A);function $Jf({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,a]of Object.entries(e)){if(t.includes(i))continue;let u=GJf(a),f=U4f({schema:a,context:n,declarationFile:u,namespace:r});if(zIn(f.schema)){let d=PC(f.schema);if(d===(f.name??i)||d===`optional<${f.name??i}>`)continue}n.builder.addType(u,{name:f.name??i,schema:f.schema})}}function KJf(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),qJf(e),IJf(e),BJf(e),Q4f(e),QJf(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(qxu);let{schemaIdsToExclude:t,sdkGroups:r}=HJf(e);JJf(e);for(let n of e.ir.channel){let i=hNn(n.groupName);MJf({channel:n,context:e,declarationFile:i})}$Jf({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:t,namespace:void 0,context:e});for(let[n,i]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))$Jf({schemas:i,schemaIdsToExclude:t,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(i=>r.has(i))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}var AOi=class{context;constructor(t){this.context=t}};var G5r=Xo(require("path"),1);var jMa=Xo(require("path"),1),DMa=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[u,f]of Object.entries(n.files)){let d=i!=null?Ms.of(`${i}${jMa.default.sep}${u}`):Ms.of(u);t[d]=f}let a=Object.keys(n.directories).sort();for(let u of a){let f=i!=null?`${i}${jMa.default.sep}${u}`:u,d=n.directories[u];r(d,f)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(jMa.default.sep))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Ms.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}};var Fin=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new DMa,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),n!=null&&(u.service["base-path"]=n),i!=null&&(u.service["display-name"]=i),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return NEr(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{}),r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:n}){if(t===r)return;let i=n??_A((cb(r)+"/"+(0,G5r.basename)(r,(0,G5r.extname)(r))).replaceAll("__package__","root"));if(t===Ms.of(m5))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=jq(cb(y_.of(`/${t}`)),y_.of(`/${r}`)),i;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[i]=jq(cb(y_.of(`/${t}`)),y_.of(`/${r}`)),i}addType(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let a=i.types[r];a!=null&&(typeof a=="string"?i.types[r]={type:a,examples:[n]}:(a.examples==null&&(a.examples=[]),a.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let a=i.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(f=>Yqt(f,n))??!1)||a.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(a.service.source=i),a.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=G5r.default.join(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([i,a])=>[i,{...a,path:G5r.default.join(r,a.path)}]))});for(let i of Object.values(t))i.service!=null&&(i.service={...i.service,endpoints:Object.fromEntries(Object.entries(i.service.endpoints).map(([a,u])=>[a,{...u,path:G5r.default.join(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===$A?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};var SMa=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;constructor({taskContext:t,ir:r,enableUniqueErrorsPerEndpoint:n,detectGlobalHeaders:i,environmentOverrides:a,globalHeaderOverrides:u,authOverrides:f}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.enableUniqueErrorsPerEndpoint=n,this.builder=new Fin(n),r.title!=null&&this.builder.setDisplayName({displayName:r.title}),this.detectGlobalHeaders=i,this.environmentOverrides=a,this.authOverrides=f,this.globalHeaderOverrides=u;let d={};if(!this.enableUniqueErrorsPerEndpoint)for(let c of r.endpoints)for(let[o,l]of Object.entries(c.errors)){let g=parseInt(o),O=d[g];O==null&&l.schema!=null?d[g]=l.schema:O!=null&&l.schema!=null&&MDe(O,l.schema)||this.unknownSchema.add(g)}}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}};function Ixu(e){let t=new SMa(e);return KJf(t)}function EMa(e,t){return by(e,t)}var N2e=class extends jIt{specs;sources;constructor({specs:t,...r}){super(r),this.specs=t,this.sources=this.convertSpecsToIdentifiableSources(t)}async getOpenAPIIr({context:t,relativePathToDependency:r},n){let i=await _nn({context:t,specs:this.specs,relativePathToDependency:r});return await Rin({absoluteFilePathToWorkspace:this.absoluteFilePath,specs:i,taskContext:t,optionOverrides:yDw(n)})}async getDefinition({context:t,relativePathToDependency:r},n){let i=await this.getOpenAPIIr({context:t,relativePathToDependency:r},n),a=Ixu({authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0,taskContext:t,ir:i,enableUniqueErrorsPerEndpoint:n?.enableUniqueErrorsPerEndpoint??!1,detectGlobalHeaders:n?.detectGlobalHeaders??!0});return{absoluteFilePath:y_.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:d0.dump(a.rootApiFile)},namedDefinitionFiles:{...EMa(a.definitionFiles,u=>({absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(u),contents:u})),[Ms.of($A)]:{absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}async toFernWorkspace({context:t},r){let n=await this.getDefinition({context:t},r);return new DIt({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter($M)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,n=[];return t.reduce((i,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),i.push({type:a.type,id:izr(),absoluteFilePath:u})),i},n)}};function MOi(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.enableDiscriminatedUnionV2=!0),t}function yDw(e){if(e==null)return;let t={};return e.enableDiscriminatedUnionV2&&(t.discriminatedUnionV2=!0),e.optionalAdditionalProperties&&(t.optionalAdditionalProperties=!0),e.cooerceEnumsToLiterals&&(t.cooerceEnumsToLiterals=!0),t}function YJf(e,t){if(vDw(e))return t.alias(e);if(bDw(e))return t.enum(e);if(gDw(e))return t.object(e);if(mDw(e))return t.union(e);xc(e)}function vDw(e){return e?.alias!=null}function bDw(e){return e?.values!=null}function gDw(e){return e?.fields!=null}function mDw(e){return e?.union!=null}var KMa={};kc(KMa,{ConjureAliasDeclaration:()=>IMa,ConjureArgument:()=>JMa,ConjureArgumentWithParamType:()=>QMa,ConjureDefinitions:()=>VMa,ConjureEndpoint:()=>GMa,ConjureEnumDeclaration:()=>LMa,ConjureEnumVariant:()=>FMa,ConjureEnumWithDocs:()=>RMa,ConjureObjectDeclaration:()=>zMa,ConjureParamType:()=>HMa,ConjurePrimitive:()=>qMa,ConjureService:()=>$Ma,ConjureServiceName:()=>CMa,ConjureType:()=>Y5r,ConjureTypeDeclaration:()=>UMa,ConjureTypeReference:()=>X5r,ConjureTypeWithDocs:()=>BMa,ConjureTypes:()=>WMa,ConjureUnionDeclaration:()=>NMa,DefinitionFile:()=>wGf,WithDocs:()=>k9t,commons:()=>Fxu,conjure:()=>Lxu,services:()=>Uxu,types:()=>Vxu});var Fxu={};kc(Fxu,{WithDocs:()=>k9t});var Vy={};kc(Vy,{JsonError:()=>K8n,ParseError:()=>Y8n,any:()=>lGf,boolean:()=>fGf,booleanLiteral:()=>cGf,date:()=>ZJf,discriminant:()=>mGf,enum_:()=>MMa,getObjectLikeUtils:()=>Z9t,getObjectUtils:()=>Z8n,getSchemaUtils:()=>O6,isProperty:()=>K5r,lazy:()=>kJf,lazyObject:()=>oGf,list:()=>TMa,number:()=>dGf,object:()=>xMa,objectWithoutOptionalProperties:()=>aGf,optional:()=>Bxu,property:()=>tGf,record:()=>yGf,set:()=>vGf,string:()=>pGf,stringLiteral:()=>sGf,transform:()=>Nxu,undiscriminatedUnion:()=>gGf,union:()=>PGf,unknown:()=>_Gf,withParsedProperties:()=>Rxu});var gE={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 Z2(e,t){return`Expected ${t}. Received ${ODw(e)}.`}function ODw(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 Q$(e){return{...e,json:XJf(e.json),parse:XJf(e.parse)}}function XJf(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
1957
|
+
`)),{ok:!0,value:t}):n}}function AMa(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var K8n=class e extends Error{errors;constructor(t){super(t.map(AMa).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Y8n=class e extends Error{errors;constructor(t){super(t.map(AMa).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function O6(e){return{optional:()=>Bxu(e),transform:t=>Nxu(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Y8n(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new K8n(n.errors)}}}function Bxu(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>gE.OPTIONAL};return{...t,...O6(t)}}function Nxu(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...O6(r)}}var PDw=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function ZJf(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:Z2(t,"string")}]}:PDw.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:Z2(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:Z2(t,"Date object")}]},getType:()=>gE.DATE};return{...Q$(e),...O6(e)}}function J$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...Q$(r),...O6(r)}}}function MMa(e){let t=new Set(e);return J$(gE.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:Z2(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:Z2(n,"enum")}]}:{ok:!0,value:n})()}function kJf(e){let t=zxu(e);return{...t,...O6(t)}}function zxu(e){return{parse:(t,r)=>X8n(e).parse(t,r),json:(t,r)=>X8n(e).json(t,r),getType:()=>X8n(e).getType()}}function X8n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function xOi(e){return Object.entries(e)}function TOi(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function $5r(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function COi(e){return Object.keys(e)}function eGf(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function Z9t(e){return{withParsedProperties:t=>Rxu(e,t)}}function Rxu(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let u=Object.entries(t).reduce((f,[d,c])=>({...f,[d]:typeof c=="function"?c(a.value):c}),{});return{ok:!0,value:{...a.value,...u}}},json:(n,i)=>{if(!$5r(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:Z2(n,"object")}]};let a=new Set(Object.keys(t)),u=TOi(n,Object.keys(n).filter(f=>!a.has(f)));return e.json(u,i)},getType:()=>e.getType()};return{...r,...O6(r),...Z9t(r)}}function tGf(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function K5r(e){return e.isProperty}function xMa(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>K5r(n)?n.rawKey:r),_getParsedProperties:()=>COi(e),parse:(r,n)=>{let i={},a=[];for(let[u,f]of xOi(e)){let d=K5r(f)?f.rawKey:u,c=K5r(f)?f.valueSchema:f,o={rawKey:d,parsedKey:u,valueSchema:c};i[d]=o,iGf(c)&&a.push(d)}return rGf({value:r,requiredKeys:a,getProperty:u=>{let f=i[u];if(f!=null)return{transformedKey:f.parsedKey,transform:d=>f.valueSchema.parse(d,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,u]of xOi(e)){let f=K5r(u)?u.valueSchema:u;iGf(f)&&i.push(a)}return rGf({value:r,requiredKeys:i,getProperty:a=>{let u=e[a];if(u!=null)return K5r(u)?{transformedKey:u.rawKey,transform:f=>u.valueSchema.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:f=>u.json(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>gE.OBJECT};return{...Q$(t),...O6(t),...Z9t(t),...Z8n(t)}}function rGf({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!$5r(e))return{ok:!1,errors:[{path:a,message:Z2(e,"object")}]};let u=new Set(t),f=[],d={};for(let[c,o]of Object.entries(e)){let l=r(c);if(l!=null){u.delete(c);let g=l.transform(o);g.ok?d[l.transformedKey]=g.value:(d[c]=o,f.push(...g.errors))}else switch(n){case"fail":f.push({path:[...a,c],message:`Unexpected key "${c}"`});break;case"strip":break;case"passthrough":d[c]=o;break}}return f.push(...t.filter(c=>u.has(c)).map(c=>({path:a,message:`Missing required key "${c}"`}))),f.length===0||i?{ok:!0,value:d}:{ok:!1,errors:f}}function Z8n(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>nGf({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>nGf({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>gE.OBJECT};return{...r,...O6(r),...Z9t(r),...Z8n(r)}}}}function nGf({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,u]=eGf(COi(t),c=>i.has(c)),f=r(TOi(t,u)),d=n(TOi(t,a));return f.ok&&d.ok?{ok:!0,value:{...f.value,...d.value}}:{ok:!1,errors:[...f.ok?[]:f.errors,...d.ok?[]:d.errors]}}function iGf(e){return!wDw(e)}function wDw(e){switch(e.getType()){case gE.ANY:case gE.UNKNOWN:case gE.OPTIONAL:return!0;default:return!1}}function aGf(e){return xMa(e)}function oGf(e){let t={...zxu(e),_getRawProperties:()=>X8n(e)._getRawProperties(),_getParsedProperties:()=>X8n(e)._getParsedProperties()};return{...t,...O6(t),...Z9t(t),...Z8n(t)}}function TMa(e){let t={parse:(r,n)=>uGf(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>uGf(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>gE.LIST};return{...Q$(t),...O6(t)}}function uGf(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:Z2(e,"list"),path:[]}]}}function sGf(e){return J$(gE.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:Z2(r,`"${e}"`)}]})()}function cGf(e){return J$(gE.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:Z2(r,`${e.toString()}`)}]})()}var lGf=J$(gE.ANY,e=>({ok:!0,value:e}));var fGf=J$(gE.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"boolean")}]});var dGf=J$(gE.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"number")}]});var pGf=J$(gE.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:Z2(e,"string")}]});var _Gf=J$(gE.UNKNOWN,e=>({ok:!0,value:e}));function yGf(e,t){let r={parse:(n,i)=>hGf({value:n,isKeyNumeric:e.getType()===gE.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>hGf({value:n,isKeyNumeric:e.getType()===gE.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>gE.RECORD};return{...Q$(r),...O6(r)}}function hGf({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return $5r(e)?xOi(e).reduce((a,[u,f])=>{if(f==null)return a;let d=a,c=u;if(t){let O=u.length>0?Number(u):NaN;isNaN(O)||(c=O)}let o=r(c),l=n(f,c);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let g=[];return d.ok||g.push(...d.errors),o.ok||g.push(...o.errors),l.ok||g.push(...l.errors),{ok:!1,errors:g}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:Z2(e,"object")}]}}function vGf(e){let t=TMa(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:Z2(n,"Set")}]},getType:()=>gE.SET};return{...Q$(r),...O6(r)}}function gGf(e){let t={parse:(r,n)=>bGf((i,a)=>i.parse(r,a),e,n),json:(r,n)=>bGf((i,a)=>i.json(r,a),e,n),getType:()=>gE.UNDISCRIMINATED_UNION};return{...Q$(t),...O6(t)}}function bGf(e,t,r){let n=[];for(let[i,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let f of u.errors)n.push({path:f.path,message:`[Variant ${i}] ${f.message}`})}return{ok:!1,errors:n}}function mGf(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function PGf(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=MMa(COi(t)),a={parse:(u,f)=>OGf({value:u,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:d=>i.parse(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.parse(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),json:(u,f)=>OGf({value:u,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:d=>i.json(d,{allowUnrecognizedEnumValues:f?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...f?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:f?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,c)=>c.json(d,f),breadcrumbsPrefix:f?.breadcrumbsPrefix}),getType:()=>gE.UNION};return{...Q$(a),...O6(a),...Z9t(a)}}function OGf({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:f=[]}){if(!$5r(e))return{ok:!1,errors:[{path:f,message:Z2(e,"object")}]};let{[t]:d,...c}=e;if(d==null)return{ok:!1,errors:[{path:f,message:`Missing discriminant ("${t}")`}]};let o=n(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=i(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...c}}:{ok:!1,errors:[{path:[...f,t],message:"Unexpected discriminant value"}]};let g=u(c,l);return g.ok?{ok:!0,value:{[r]:d,...g.value}}:g}var k9t=Vy.objectWithoutOptionalProperties({docs:Vy.string().optional()});var Lxu={};kc(Lxu,{ConjureServiceName:()=>CMa,DefinitionFile:()=>wGf});var CMa=Vy.string();var qMa=Vy.enum_(["rid","string","safelong","integer","double","boolean"]);var Y5r=Vy.undiscriminatedUnion([qMa,Vy.string()]);var IMa=Vy.objectWithoutOptionalProperties({alias:Y5r,docs:Vy.string().optional()});var BMa=Vy.objectWithoutOptionalProperties({type:Y5r,docs:Vy.string().optional()});var X5r=Vy.undiscriminatedUnion([Y5r,BMa]);var NMa=Vy.objectWithoutOptionalProperties({union:Vy.record(Vy.string(),X5r)});var zMa=Vy.objectWithoutOptionalProperties({fields:Vy.record(Vy.string(),X5r)});var RMa=Vy.objectWithoutOptionalProperties({value:Vy.string()}).extend(k9t);var FMa=Vy.undiscriminatedUnion([Vy.string(),RMa]);var LMa=Vy.objectWithoutOptionalProperties({values:Vy.list(FMa)});var UMa=Vy.undiscriminatedUnion([IMa,NMa,zMa,LMa]);var VMa=Vy.objectWithoutOptionalProperties({objects:Vy.record(Vy.string(),UMa).optional()});var WMa=Vy.objectWithoutOptionalProperties({conjureImports:Vy.property("conjure-imports",Vy.record(Vy.string(),Vy.string()).optional()),definitions:VMa.optional()});var HMa=Vy.enum_(["path","query","body"]);var QMa=Vy.objectWithoutOptionalProperties({paramType:Vy.property("param-type",HMa),type:Vy.string()}).extend(k9t);var JMa=Vy.undiscriminatedUnion([Vy.string(),QMa]);var GMa=Vy.objectWithoutOptionalProperties({http:Vy.string(),args:Vy.record(Vy.string(),JMa).optional(),returns:X5r.optional()}).extend(k9t);var $Ma=Vy.objectWithoutOptionalProperties({name:Vy.string().optional(),package:Vy.string().optional(),basePath:Vy.property("base-path",Vy.string().optional()),endpoints:Vy.record(Vy.string(),GMa).optional()}).extend(k9t);var wGf=Vy.objectWithoutOptionalProperties({types:WMa.optional(),services:Vy.record(CMa,$Ma).optional()});var Uxu={};kc(Uxu,{ConjureArgument:()=>JMa,ConjureArgumentWithParamType:()=>QMa,ConjureEndpoint:()=>GMa,ConjureParamType:()=>HMa,ConjureService:()=>$Ma});var Vxu={};kc(Vxu,{ConjureAliasDeclaration:()=>IMa,ConjureDefinitions:()=>VMa,ConjureEnumDeclaration:()=>LMa,ConjureEnumVariant:()=>FMa,ConjureEnumWithDocs:()=>RMa,ConjureObjectDeclaration:()=>zMa,ConjurePrimitive:()=>qMa,ConjureType:()=>Y5r,ConjureTypeDeclaration:()=>UMa,ConjureTypeReference:()=>X5r,ConjureTypeWithDocs:()=>BMa,ConjureTypes:()=>WMa,ConjureUnionDeclaration:()=>NMa});var jGf=require("fs/promises");async function DGf(e,t){let r=[];for(let n of await tTe(e,t))r.push(await jDw({relativeFilepath:jq(e,n),absoluteFilepath:n}));return r}async function jDw({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,jGf.readFile)(t)).toString().replaceAll(": rid",": string").replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:KMa.DefinitionFile.parseOrThrow(d0.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}var qOi=class extends AOi{fernDefinitionBuilder=new Fin(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:n,globalHeaderOverrides:i}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(n!=null){for(let[a,u]of Object.entries(n.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});n["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(n["default-environment"]),n["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(n["default-url"])}return await SGf(t,(a,u,f)=>{for(let[o,l]of Object.entries(f.services??{})){let g=gXi({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Ms.of(`${g}/__package__.yml`);return}let c=TZo(u)?.split(".")[0];c!=null&&(this.conjureFilepathToFernFilepath[u]=Ms.of(`${c}/__package__.yml`))}),await SGf(t,(a,u,f)=>{if(f.services==null||Object.keys(f.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[c,o]of Object.entries(f.types?.conjureImports??{})){let l=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ms.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Ms.of(l),alias:c})}this.importAllTypes({conjureFile:f,fernFilePath:d});return}for(let[d,c]of Object.entries(f.services)){let o=gXi({value:d,suffix:"Service"}),l=Ms.of(`${o}/__package__.yml`),g={};c.basePath!=null&&(g["base-path"]=c.basePath),c.docs!=null&&(g.docs=c.docs),this.fernDefinitionBuilder.setServiceInfo(l,g),this.importAllTypes({conjureFile:f,fernFilePath:l});for(let[O,P]of Object.entries(f.types?.conjureImports??{})){let j=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ms.of(P)});this.fernDefinitionBuilder.addImport({file:l,fileToImport:Ms.of(j),alias:O})}for(let[O,P]of Object.entries(c.endpoints??{})){let j=NKo(P.http);if(j.type==="failure"){this.context?.logger.error(`Failed to parse ${P.http}. Skipping.`);continue}let M={auth:!0,path:j.path,method:j.method,response:P.returns==="binary"?"file":P.returns};P.docs!=null&&(M.docs=P.docs);let q={};if(P.args!=null)for(let B of j.pathParameters){let I=P.args[B];if(I==null)throw new Error(`Failed to find path parameter ${B} in ${P.http}`);q[B]=typeof I=="string"?I:{type:I.type}}Object.entries(q).length>0&&(M["path-parameters"]=q);for(let[B,I]of Object.entries(P.args??{}))if(q[B]==null)if(typeof I=="string")M.request={body:I==="binary"?"bytes":I};else switch(I.paramType){case"body":M.request={body:I.type==="binary"?"bytes":I.type};break;case"query":M.request==null?M.request={"query-parameters":{[B]:I.type}}:typeof M.request!="string"&&M.request?.["query-parameters"]==null?M.request["query-parameters"]={[B]:I.type}:typeof M.request!="string"&&M.request?.["query-parameters"]!=null&&(M.request["query-parameters"][B]=I.type)}M.request!=null&&typeof M.request!="string"&&M.request?.["query-parameters"]!=null&&(M.request.name=`${O}Request`),this.fernDefinitionBuilder.addEndpoint(l,{name:O,schema:M,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[n,i]of Object.entries(t.types?.definitions?.objects??{}))YJf(i,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:n,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,f])=>[u,{type:typeof f=="string"?f:f.type,docs:typeof f=="string"?void 0:f.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:n}){let i=yf(cb(t),Ms.of(r)),a=w3r(n,i),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function SGf(e,t){for(let r of await DGf(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}var YMa=class extends jIt{absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=yf(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let n=await this.getDefinition({context:t},r);return new DIt({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let i=await new qOi(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:y_.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:i.rootApiFile["default-url"],contents:i.rootApiFile,rawContents:d0.dump(i.rootApiFile)},namedDefinitionFiles:{...EMa(i.definitionFiles,a=>({absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(a),contents:a})),[Ms.of($A)]:{absoluteFilepath:y_.of("/DUMMY_PATH"),rawContents:d0.dump(i.packageMarkerFile),contents:i.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function Wxu(e,t){for(let[r,n]of b8(e.failures))DDw({relativeFilepath:r,failure:n,logger:t})}function DDw({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case Dj.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case Dj.FILE_READ:r.error("Failed to open file: "+e);break;case Dj.FILE_MISSING:r.error("Missing file: "+e);break;case Dj.FILE_PARSE:t.error instanceof $pi?r.error(c6t({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case Dj.STRUCTURE_VALIDATION:for(let n of t.error.issues)for(let{title:i,subtitle:a}of SDw(n))r.error(c6t({title:i,subtitle:a,breadcrumbs:[e,...n.path]}));break;case Dj.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case Dj.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${tZi}: `+t.dependencyName);break;case Dj.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case Dj.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case Dj.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(c6t({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(n=>n!=="")]}));break;default:xc(t)}}function SDw(e){switch(e.code){case r_.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${nl.underline(e.expected)} but received ${nl.underline(e.received)}`}];case r_.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${nl.underline(t)}`}));case r_.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>nl.underline(t)).join(", ")}`}];case r_.invalid_union:case r_.invalid_arguments:case r_.invalid_return_type:case r_.invalid_date:case r_.invalid_string:case r_.too_small:case r_.too_big:case r_.invalid_intersection_types:case r_.not_multiple_of:case r_.custom:default:return[{title:e.message}]}}var EGf=require("fs/promises");async function AGf(e,t){let r=[];for(let n of await tTe(e,t))r.push(await EDw({relativeFilepath:jq(e,n),absoluteFilepath:n}));return r}async function EDw({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,EGf.readFile)(t)).toString()}}async function MGf({absolutePathToWorkspace:e}){let t=yf(e,Ms.of(ael));if(!await Wh(t))return;let n=await AGf(t,"{md,mdx}");return{files:await Promise.all(n.map(i=>({absoluteFilepath:i.absoluteFilepath,contents:i.fileContents})))}}async function Hxu({absolutePathToWorkspace:e,namespace:t,definitions:r}){let n=[];for(let i of r){let a=i.overrides!=null?yf(e,Ms.of(i.overrides)):void 0;if(i.schema.type==="protobuf"){let f=yf(e,Ms.of(i.schema.root));if(!await Wh(f))return{didSucceed:!1,failures:{[Ms.of(i.schema.root)]:{type:Dj.FILE_MISSING}}};let d=yf(e,Ms.of(i.schema.target));if(!await Wh(d))return{didSucceed:!1,failures:{[Ms.of(i.schema.target)]:{type:Dj.FILE_MISSING}}};n.push({type:"protobuf",absoluteFilepathToProtobufRoot:f,absoluteFilepathToProtobufTarget:d,absoluteFilepathToOverrides:a,generateLocally:i.schema.localGeneration,settings:{audiences:i.audiences??[],shouldUseTitleAsName:i.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:i.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,optionalAdditionalProperties:i.settings?.shouldUseOptionalAdditionalProperties??!0,cooerceEnumsToLiterals:i.settings?.coerceEnumsToLiterals??!0}});continue}let u=yf(e,Ms.of(i.schema.path));if(!await Wh(u))return{didSucceed:!1,failures:{[Ms.of(i.schema.path)]:{type:Dj.FILE_MISSING}}};if(i.overrides!=null&&a!=null&&!await Wh(a))return{didSucceed:!1,failures:{[Ms.of(i.overrides)]:{type:Dj.FILE_MISSING}}};n.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:i.audiences??[],shouldUseTitleAsName:i.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:i.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,asyncApiNaming:i.settings?.asyncApiMessageNaming,optionalAdditionalProperties:i.settings?.shouldUseOptionalAdditionalProperties??!0,cooerceEnumsToLiterals:i.settings?.coerceEnumsToLiterals??!0},source:{type:"openapi",file:u},namespace:t})}return n}async function IOi({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:n}){let i=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:e,context:t}),a;try{a=await MGf({absolutePathToWorkspace:e})}catch{}if(i?.api!=null&&i?.api.type==="conjure")return{didSucceed:!0,workspace:new YMa({workspaceName:n,absoluteFilePath:e,generatorsConfiguration:i,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:Ms.of(i.api.pathToConjureDefinition)})};if(i?.api!=null&&(i.api.type==="singleNamespace"&&i.api.definitions.length>0||i.api.type==="multiNamespace")){let u=[];if(i.api.type==="singleNamespace"){let f=await Hxu({absolutePathToWorkspace:e,namespace:void 0,definitions:i.api.definitions});if(!Array.isArray(f))return f;u.push(...f)}else{for(let[f,d]of Object.entries(i.api.definitions)){let c=await Hxu({absolutePathToWorkspace:e,namespace:f,definitions:d});if(!Array.isArray(c))return c;u.push(...c)}if(i.api.rootDefinitions!=null){let f=await Hxu({absolutePathToWorkspace:e,namespace:void 0,definitions:i.api.rootDefinitions});if(!Array.isArray(f))return f;u.push(...f)}}return{didSucceed:!0,workspace:new N2e({specs:u,workspaceName:n,absoluteFilePath:e,generatorsConfiguration:i,changelog:a,cliVersion:r})}}return await Wh(yf(e,Ms.of(QL)))?{didSucceed:!0,workspace:new U7n({absoluteFilePath:e,generatorsConfiguration:i,workspaceName:n,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:IOi})}:{didSucceed:!1,failures:{[Ms.of(qkr)]:{type:Dj.MISCONFIGURED_DIRECTORY}}}}var xGf=require("fs/promises");var TGf=Xo(require("path"),1);async function Qxu({fernDirectory:e,context:t}){let r=yf(e,Ms.of(LSr));if(!await Wh(r))return;let n=await ADw({absolutePathToDocsDefinition:e,context:t});if(n!=null)return{type:"docs",absoluteFilePath:e,config:n,workspaceName:void 0,absoluteFilepathToDocsConfig:yf(e,Ms.of(LSr))}}async function ADw({absolutePathToDocsDefinition:e,context:t}){if(!await Wh(e))return;let r=yf(e,Ms.of(LSr));return await MDw({absolutePathOfConfiguration:r,context:t})}async function MDw({absolutePathOfConfiguration:e,context:t}){let r=await(0,xGf.readFile)(e),n=d0.load(r.toString());return await xDw({value:n,context:t,filepathBeingParsed:e})}async function xDw({value:e,context:t,filepathBeingParsed:r}){let n=await gTe.RawSchemas.Serializer.DocsConfiguration.parse(e);if(n.ok)return n.value;let i=n.errors.map(u=>{let f=u.path.length>0?`${u.message} at "${u.path.join(" -> ")}"`:u.message;return DZ({content:f,prefix:" - "})}),a=[`Failed to parse file: ${TGf.default.relative(process.cwd(),r)}`,...i].join(`
|
|
1958
1958
|
`);return t.failAndThrow(a)}var CGf=require("fs/promises");async function Jxu({context:e,nameOverride:t,...r}){let n=await UNr(t);return n==null?e.failAndThrow(`Directory "${t??t6t}" not found.`):await qGf({absolutePathToFernDirectory:n,context:e,nameOverride:t,...r})}async function qGf({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:i,context:a}){let u=[];return(await Wh(yf(e,Ms.of(v3r)))||await Wh(yf(e,Ms.of(QL)))||await Wh(yf(e,Ms.of(m8)))||await Wh(yf(e,Ms.of(qkr)))||await Wh(yf(e,Ms.of(oel))))&&(u=await IGf({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:i})),{config:await dzt.loadProjectConfig({directory:e,context:a}),apiWorkspaces:u,docsWorkspaces:await Qxu({fernDirectory:e,context:a}),loadAPIWorkspace:f=>f==null?u[0]:u.find(d=>d.workspaceName===f)}}async function IGf({cliName:e,fernDirectory:t,context:r,cliVersion:n,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:a}){let u=yf(t,Ms.of(v3r));if(await Wh(u)){let o=(await(0,CGf.readdir)(u,{withFileTypes:!0})).reduce((O,P)=>(P.isDirectory()&&O.push(P.name),O),[]);if(i!=null){if(!o.includes(i))return r.failAndThrow("API does not exist: "+i)}else{if(o.length===0)return r.failAndThrow("No APIs found.");if(o.length>1&&!a){let O=`There are multiple workspaces. You must specify one with --api:
|
|
1959
1959
|
`,P=Math.max(...o.map(j=>j.length));return O+=o.map(j=>{let M=`${e} ${process.argv.slice(2).join(" ")} --api ${j}`;return` \u203A ${nl.bold(j.padEnd(P))} ${nl.dim(M)}`}).join(`
|
|
1960
1960
|
`),r.failAndThrow(O)}}let l=[],g=i!=null?o.filter(O=>O===i):o;return await Promise.all(g.map(async O=>{let P=await IOi({absolutePathToWorkspace:yf(u,Ms.of(O)),context:r,cliVersion:n,workspaceName:O});P.didSucceed?l.push(P.workspace):(Wxu(P,r.logger),r.failAndThrow())})),l}let d=await IOi({absolutePathToWorkspace:t,context:r,cliVersion:n,workspaceName:void 0});return d.didSucceed?[d.workspace]:(Wxu(d,r.logger),[])}async function Tq(e,t,r=!1){let n=e.addTask().start(),i=await Jxu({...t,cliName:e.environment.cliName,cliVersion:e.environment.packageVersion,context:n});return n.finish(),r&&i.docsWorkspaces!=null?e.registerWorkspaces([...i.apiWorkspaces,i.docsWorkspaces]):e.registerWorkspaces(i.apiWorkspaces),e.registerProject(i),i}var VGf=Xo(shi(),1);var NGf=require("fs/promises");var k8n={GitHub:"github",Local:"local-file-system",PackageRegistry:"publish"};async function zGf({cliContext:e,generatorFilter:t,groupFilter:r,apiFilter:n,apiKeyFallback:i="FERN_DEFAULT",project:{apiWorkspaces:a},outputLocation:u,excludedModes:f,includedModes:d}){let c={};await Promise.all(a.map(async l=>{await e.runTaskForWorkspace(l,async g=>{if(n!=null&&(l.workspaceName==null||!n.has(l.workspaceName)))return;let O=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:l.absoluteFilePath,context:g});if(O==null||O.groups==null)return;let P=l.workspaceName??i;c[P]={};for(let j of O.groups)r!=null&&!r.has(j.groupName)||(c[P][j.groupName]=j.generators.filter(M=>{let q=!0;return d!=null&&(q=BGf(M,d)),f!=null&&(q=!BGf(M,f)),q}).filter(M=>t==null||t.has(M.name)).map(M=>M.name))})}));let o=d0.dump(c);if(u==null){process.stdout.write(o);return}try{await(0,NGf.writeFile)(u,o)}catch(l){e.failAndThrow(`Could not write file to the specified location: ${u}`,l)}}function BGf(e,t){let r,n=e.outputMode.type;switch(n){case"downloadFiles":r=k8n.Local;break;case"github":case"githubV2":r=k8n.GitHub;break;case"publish":case"publishV2":r=k8n.PackageRegistry;break;default:xc(n)}return t.has(r)}async function RGf({cliContext:e,generatorFilter:t,groupFilter:r,apiFilter:n,project:{apiWorkspaces:i}}){let a;return await Promise.all(i.map(async u=>{await e.runTaskForWorkspace(u,async f=>{if(n!=null&&(u.workspaceName==null||n!==u.workspaceName))return;let d=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:u.absoluteFilePath,context:f});if(!(d==null||d.groups==null)){for(let c of d.groups)if(r===c.groupName)for(let o of c.generators)t===o.name&&(a=o)}})})),a}var FGf=require("fs/promises");async function LGf({project:e,outputLocation:t,context:r}){let n=e.config.organization;if(t==null){process.stdout.write(n);return}try{await(0,FGf.writeFile)(t,n)}catch(i){r.failAndThrow(`Could not write file to the specified location: ${t}`,i)}}var XMa=require("fs/promises"),BOi=Xo(require("path"),1),ezn=Xo(Pk(),1);async function TDw({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:n,includeMajor:i,channel:a,cliVersion:u}){let f=nP.getPathToGeneratorsConfiguration({absolutePathToWorkspace:e});if(!await Wh(f)){t.logger.debug("Generators configuration file was not found, no generators to upgrade.");return}let d=await(0,XMa.readFile)(f);t.logger.debug(`Found generators: ${d.toString()}`);let c=ezn.default.parseDocument(d.toString()),o=c.get("groups");if(o==null){t.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}if(!ezn.default.isMap(o)){t.failAndThrow(`Expected 'groups' to be a map in ${BOi.default.relative(process.cwd(),f)}`);return}t.logger.debug(`Groups found: ${o.toString()}`);for(let l of o.items){let g=l.key.value,O=l.value;if(!ezn.default.isMap(O)){t.failAndThrow(`Expected group ${g} to be a map in ${BOi.default.relative(process.cwd(),f)}`);continue}if(n!=null&&n!==g){t.logger.debug(`Skipping group ${g} as it does not match the filter: ${n}`);continue}let P=O.get("generators");if(!ezn.default.isSeq(P)){t.failAndThrow(`Expected group ${g} to have a 'generators' key in ${BOi.default.relative(process.cwd(),f)}`);continue}t.logger.debug(`Generators found: ${P.toString()}`);for(let j of P.items){ezn.default.isMap(j)||t.failAndThrow(`Expected generator in group ${g} to be a map in ${BOi.default.relative(process.cwd(),f)}`);let M=j.get("name");if(r!=null&&M!==r){t.logger.debug(`Skipping generator ${M} as it does not match the filter: ${r}`);continue}let q=nP.getGeneratorNameOrThrow(M,t),B=j.get("version"),I=await nP.getLatestGeneratorVersion({generatorName:q,cliVersion:u,currentGeneratorVersion:B,channel:a,includeMajor:i,context:t});I!=null&&(t.logger.debug(nl.green(`Upgrading ${M} from ${B} to ${I}`)),j.set("version",I))}}return c.toString()}async function UGf({cliContext:e,generator:t,group:r,project:{apiWorkspaces:n},includeMajor:i,channel:a}){await Promise.all(n.map(async u=>{await e.runTaskForWorkspace(u,async f=>{let d=await nP.loadRawGeneratorsConfiguration({absolutePathToWorkspace:u.absoluteFilePath,context:f})??{};if(d==null||d.groups==null){f.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}u.workspaceName==null?f.logger.info("Upgrading generators."):f.logger.info(`Upgrading generators in workspace: ${u.workspaceName}.`);let c=await TDw({absolutePathToWorkspace:u.absoluteFilePath,context:f,generatorFilter:t,groupFilter:r,includeMajor:i,channel:a,cliVersion:e.environment.packageVersion});c!=null&&await(0,XMa.writeFile)(u.generatorsConfiguration?.absolutePathToConfiguration??nP.getPathToGeneratorsConfiguration({absolutePathToWorkspace:u.absoluteFilePath}),c)})}))}var WGf=require("fs/promises");function HGf(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await LGf({project:await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function QGf(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,n=>n.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values(k8n),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(k8n),type:"array",description:"The generator output modes to exclude within the outputted list."}),async n=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:n.output}}),await zGf({project:await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:n.generators?new Set(n.generators):void 0,groupFilter:n.groups?new Set(n.groups):void 0,apiFilter:n.apis?new Set(n.apis):void 0,apiKeyFallback:n.apiFallback,cliContext:t,outputLocation:n.output,includedModes:n["include-mode"]?new Set(n["include-mode"]):void 0,excludedModes:n["exclude-mode"]?new Set(n["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${m8} to the latest stable version.`,n=>n.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(VGf.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async n=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:n.generator,version:n.version,api:n.api,group:n.group,includeMajor:n.includeMajor,rc:n.rc}});let i=await Tq(t,{commandLineApiWorkspace:n.api,defaultToAllApiWorkspaces:!0});if(n.list){t.suppressUpgradeMessage();let a=await HOa({cliContext:t,project:i,generatorFilter:n.generator,groupFilter:n.group,includeMajor:n.includeMajor,channel:n.channel}),u=await bmu({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
@@ -1987,7 +1987,7 @@ ${g}
|
|
|
1987
1987
|
`+Object.keys(t.union).map(B=>` - ${B}`).join(`
|
|
1988
1988
|
`)}];if(t["base-properties"]!=null){let B=Object.fromEntries(Object.entries(o).filter(([C])=>t["base-properties"]?.[C]!=null)),I=Ian({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:B,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f});if(I.length>0)return I}let g=typeof l=="string"?l:l.type;if(typeof g!="string")return ird(o);let O=n.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&mA(O.declaration)){let B=Object.fromEntries(Object.entries(o).filter(([I])=>t["base-properties"]?.[I]==null));return Ian({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:B,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f})}let P=typeof l!="string"&&typeof l.key=="string"?l.key:void 0;if(P==null)return[];let{[P]:j,...M}=o,q=[];return j==null?q.push({message:`Missing property "${P}"`}):q.push(...nQ({rawTypeReference:g,example:j,typeResolver:n,exampleResolver:i,file:a,workspace:u,breadcrumbs:f})),q.push(...ird(M)),q}function ird(e){return Object.keys(e).map(t=>({severity:"error",message:`Unexpected property "${t}"`}))}function ATa({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}){return I8(t,{alias:d=>Xtd({rawAlias:d,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}),enum:d=>Ztd({rawEnum:d,example:a,breadcrumbs:f}),object:d=>Ian({typeName:e,typeNameForBreadcrumb:e,rawObject:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),discriminatedUnion:d=>ard({typeName:e,rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),undiscriminatedUnion:d=>ktd({rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f})})}var _rd=/^([+-]?\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)?)?)?)?$/,Fqw=/^[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}$/,Lqw=/^\d{4}-\d{2}-\d{2}$/;function nQ({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}){if(typeof t=="string"&&t.startsWith(oFt)){let f=r.resolveType({type:e,file:i});if(f==null)return[];let d=n.parseExampleReference(t);if(d==null)return[];let c=r.resolveNamedType({referenceToNamedType:d.rawTypeReference,file:i});return c==null?[]:APi({expected:f,actual:c})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return Dtn({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>Uqw({primitiveType:f,example:t}),named:f=>{let d=r.getDeclarationOfNamedType({referenceToNamedType:f,file:i});return d==null?[]:ATa({typeName:d.typeName,typeDeclaration:d.declaration,file:d.file,example:t,typeResolver:r,exampleResolver:n,workspace:a,breadcrumbs:u})},map:({keyType:f,valueType:d})=>lS(t)?Object.entries(t).flatMap(([c,o])=>[...nQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]}),...nQ({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]})]):L2e(t,"a map"),list:f=>Array.isArray(t)?t.flatMap((d,c)=>nQ({rawTypeReference:f,example:d,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${c}`]})):L2e(t,"a list"),set:f=>{if(!Array.isArray(t))return L2e(t,"a list");let d=dKo(t);return d.length>0?[{severity:"error",message:`Set has duplicate elements:
|
|
1989
1989
|
`+d.map(c=>` - ${JSON.stringify(c)}`).join(`
|
|
1990
|
-
`)}]:t.flatMap((c,o)=>nQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:nQ({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return UDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return UDe(d=>d===f.string,`"${f.string}"`)(t);default:xc(f)}}}})}function Uqw({primitiveType:e,example:t}){return e.v2!=null?kA._visit(e.v2,{integer:r=>Vqw({example:t,rules:r.validation}),long:()=>crd(t),uint:()=>ord(t),uint64:()=>urd(t),double:r=>Wqw({example:t,rules:r.validation}),float:()=>srd(t),boolean:()=>lrd(t),string:r=>Hqw({example:t,rules:r.validation}),uuid:()=>frd(t),date:()=>prd(t),dateTime:()=>drd(t),base64:()=>jzn(t),bigInteger:()=>jzn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>hrd(t),long:()=>crd(t),uint:()=>ord(t),uint64:()=>urd(t),double:()=>yrd(t),float:()=>srd(t),boolean:()=>lrd(t),string:()=>jzn(t),uuid:()=>frd(t),dateTime:()=>drd(t),date:()=>prd(t),base64:()=>jzn(t),bigInteger:()=>jzn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function Vqw({example:e,rules:t}){let r=hrd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function Wqw({example:e,rules:t}){let r=yrd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function Hqw({example:e,rules:t}){let r=jzn(e);if(r.length>0||t==null)return r;let n=e;return t.minLength!=null&&n.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${n.length}.`}]:t.maxLength!=null&&n.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${n.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(n)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var jzn=UDe(e=>typeof e=="string","a string"),hrd=UDe(e=>Number.isInteger(e),"an integer"),ord=UDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),urd=UDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),srd=UDe(e=>typeof e=="number","a float"),yrd=UDe(e=>typeof e=="number","a double"),crd=UDe(e=>Number.isInteger(e),"an integer"),lrd=UDe(e=>typeof e=="boolean","a boolean"),frd=UDe(e=>typeof e=="string"&&Fqw.test(e),"a UUID"),drd=UDe(e=>typeof e=="string"&&_rd.test(e),"an ISO 8601 timestamp"),prd=UDe(e=>typeof e=="string"&&Lqw.test(e)&&_rd.test(e),"a date");function UDe(e,t){return r=>e(r)?[]:L2e(r,t)}function APi({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&&APi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return APi({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&&APi({expected:e.container.keyType,actual:t.container.keyType})&&APi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:Qqw({expected:e.container.literal,actual:t.container.literal});default:xc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;xc(e)}function Qqw({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:xc(e)}}async function MTa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await X$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:Dzn(i).name,opts:{casingOverrides:typeof i!="string"?i.casing:void 0}})}))),n;if(e.default!=null&&(n=r.find(i=>i.name.wireValue===e.default),n==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:n,values:r}}function vrd(e,t){let r=t.enum.find(n=>typeof n=="string"?!1:n.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function Dzn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function xqu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return I8(t,{alias:d=>dS.alias({value:lT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>brd({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=Ban(d);if(!lS(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=d.union[o];if(l==null)throw new Error(`${o} is not one of the specified discriminant values.`);let g=typeof l=="string"?l:typeof l.type=="string"?l.type:void 0;return dS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:sRr(d).name,wireValue:c}),singleUnionType:Gqw({rawValueType:g,rawSingleUnionType:l,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,example:r,discriminant:c,discriminantValueForExample:o,workspace:f})})},enum:d=>{if(typeof r!="string")throw new Error("Enum example is not a string");return dS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:vrd(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(nQ({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return dS.undiscriminatedUnion({index:c,singleUnionType:lT({example:r,rawTypeBeingExemplified:typeof o=="string"?o:o.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})});throw new Error("Example doesn't match any of the undiscriminated unions")}})}function lT({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}){let{resolvedExample:f,file:d}=a.resolveExampleOrThrow({example:e,file:t}),c=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:Dtn({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>Jqw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!lS(f))throw new Error("Example is not an object");return dO.container(gA.map({map:Object.entries(f).map(([O,P])=>({key:lT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:lT({example:P,fileContainingExample:d,rawTypeBeingExemplified:g,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})})),keyType:n.parseTypeReference(l),valueType:n.parseTypeReference(g)}))},list:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.list({list:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},set:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.set({set:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(gA.optional({optional:f!=null?lT({example:f,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}):void 0,valueType:n.parseTypeReference(l)})),literal:l=>{switch(l.type){case"boolean":return dO.container(gA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(gA.literal({literal:Pv.string({original:l.string})}));default:xc(l)}},named:l=>{let g=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:n}),O=n.parseTypeReference(l);if(O.type!=="named")throw new Error("Type reference is not to a named type.");let P={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:P,shape:xqu({typeName:P,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function Jqw({example:e,typeBeingExemplified:t}){return vP._visit(t,{string:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.date(e))},base64:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.integer(e))},float:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.float(e))},double:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.double(e))},long:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error("Example is not a boolean");return dO.primitive(Pv.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function brd({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!lS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return dS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=grd({typeName:e,wirePropertyKey:c,rawObject:t,typeResolver:a,file:n});if(l==null)throw new Error("Could not find original type declaration for property: "+c);let g=lT({example:o,fileContainingExample:i,rawTypeBeingExemplified:typeof l.rawPropertyType=="string"?l.rawPropertyType:l.rawPropertyType.type,fileContainingRawTypeReference:l.file,typeResolver:a,exampleResolver:u,workspace:f});return d.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function grd({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:MPi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function MPi({wirePropertyKey:e,extends_:t,typeResolver:r,file:n}){if(t!=null){let i=typeof t=="string"?[t]:t;for(let a of i){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:n});if(u._type!=="named"||!mA(u.declaration))throw new Error("Extension is not of a named object");let f=grd({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function Gqw({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:n,typeResolver:i,exampleResolver:a,example:u,discriminant:f,discriminantValueForExample:d,workspace:c}){let o=n.casingsGenerator.generateNameAndWireValue({name:wzn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:C8.noProperties()};let l=Mqu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!lS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:C8.singleProperty(lT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!lS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,P=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!mA(P.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:C8.samePropertiesAsObject({typeId:o1.generateTypeId(j),object:brd({rawObject:P.declaration,example:O,fileContainingType:P.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:xc(l)}}async function xTa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=pMr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await X$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function pMr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function $qw(e){let t=JSON.stringify(e);return mrd.default.createHash("sha256").update(t).digest("hex")}function Ord({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=Yqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??$qw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:t6w({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...Xqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,l])=>{let g=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(g==null)throw new Error(`Query parameter ${o} does not exist`);return{name:f.casingsGenerator.generateNameAndWireValue({name:pMr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:lT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:Kqw({queryParameter:g})}}):[],request:Zqw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:kqw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function Kqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function Yqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,variableResolver:a,file:u,workspace:f}){let d=[],c=[],o=[],l=({name:g,pathParameterDeclaration:O,examplePathParameter:P})=>{let j=xPi({parameter:O,variableResolver:a,file:u});return{name:g,value:lT({example:P,rawTypeBeingExemplified:j.rawType,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:j.file,fileContainingExample:u,workspace:f})}};if(r["path-parameters"]!=null)for(let[g,O]of Object.entries(r["path-parameters"])){let P=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(P!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else if(M!=null)o.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:M,examplePathParameter:O}));else if(j!=null)c.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:j,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:c}}function Xqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:u}){let f=[],d=[];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,g=e.headers?.[c];if(l!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:c,header:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(g!=null)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:c,header:g}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${c} does not exist`)}return{endpointHeaders:d,serviceHeaders:f}}function Zqw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&nyi(u)!=null)return;if(!y6(u))return v$.reference(lT({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!t.request)return;if(!lS(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let f=[];for(let[d,c]of Object.entries(t.request)){let o=u.properties?.[d],l=typeof o=="string"?o:o?.type;if(!(l!=null&&MCe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:d,property:o}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let g=MPi({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:i});if(g==null)throw new Error("Could not find original type declaration for property: "+d);f.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof g.rawPropertyType=="string"?g.rawPropertyType:g.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:g.typeName})}}return v$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function kqw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?T4.ok(cN.body(void 0)):Etn(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return T4.error({error:oRr({errorName:f.error,file:a}),body:d.declaration.type!=null?lT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return T4.ok(cN.body(e6w({endpoint:e,example:f,typeResolver:r,exampleResolver:i,file:a,workspace:u})))},stream:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.stream(f.stream.map(c=>{if(d!=null)return lT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter($M)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=lT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter($M)))}})}function e6w({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return lT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function t6w({file:e,service:t,endpoint:r,example:n,pathParams:i}){let a=k1(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(n["path-parameters"]!=null)for(let u of[...i.endpointPathParameters,...i.servicePathParameters,...i.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}async function Prd({endpoint:e,file:t,typeResolver:r}){return{body:await r6w({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function r6w({endpoint:e,file:t,typeResolver:r}){let n=await n6w({endpoint:e,file:t,typeResolver:r}),i=await i6w({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Lie.fileDownload({...n});break}case"json":{a=Lie.json({...n.value});break}case"text":{a=Lie.text({...n});break}default:xc(n)}return A3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return A3.streaming(i)}}async function n6w({endpoint:e,file:t,typeResolver:r}){let{response:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type;return MCe(a)!=null?A3.fileDownload({docs:i}):iyi(a)!=null?A3.text({docs:i}):await a6w(n,i,t,r)}}async function i6w({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type,u=typeof n=="string"?"json":n.format??"json";return Y6n(a)?Uie.text({docs:i}):typeof n!="string"&&u==="sse"?Uie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Uie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function a6w(e,t,r,n){let i=r.parseTypeReference(e),a=n.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?A3.json(N6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await DPi({typeResolver:n,file:r,resolvedType:a,property:u})})):A3.json(N6t.response({docs:t,responseBodyType:i}))}async function wrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return wCe.cursor({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.cursor}),next:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.next_cursor}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}async function jrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return wCe.offset({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.offset}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results}),step:i.step!=null?await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.step}):void 0,hasNextPage:i.hasNextPage!=null?await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.hasNextPage}):void 0})}function Drd(e){return o6w(e)?{type:"offset",offset:WIt(e.offset),results:fMr(e.results),step:e.step!=null?WIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?fMr(e["has-next-page"]):void 0}:{type:"cursor",cursor:WIt(e.cursor),next_cursor:fMr(e.next_cursor),results:fMr(e.results)}}function o6w(e){return e.offset!=null&&e.results!=null}async function Srd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=Drd(i);switch(a.type){case"cursor":return await wrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return jrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:xc(a)}}function Erd({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=oRr({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function TTa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Ard({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:TTa({source:e}),name:uRr.generateName(r)}}async function Mrd({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return mCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return mCe.http();let i=Ard({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return mCe.grpc({service:i})}async function xrd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:n,errorResolver:i,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:d,sourceResolver:c,globalErrors:o,workspace:l}){let g=await Szn({pathParameters:r["path-parameters"],location:OCe.Service,file:n,variableResolver:d}),O=await Mrd({file:n,serviceDeclaration:r,sourceResolver:c}),P={fernFilepath:n.fernFilepath};return{availability:Sae(r.availability),name:P,displayName:r["display-name"]??void 0,basePath:F2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>U2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:l6w(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await Szn({pathParameters:q["path-parameters"],location:OCe.Endpoint,file:n,variableResolver:d}),I={...await X$(q),id:"",name:n.casingsGenerator.generateName(M),displayName:q["display-name"],auth:q.auth??r.auth,idempotent:q.idempotent??r.idempotent??!1,baseUrl:q.url??r.url??e,method:q.method!=null?c6w(q.method):Rie.Post,basePath:q["base-path"]!=null?F2e(q["base-path"]):void 0,path:F2e(q.path),fullPath:F2e(q["base-path"]!=null?k1(q["base-path"],q.path):n.rootApiFile["base-path"]!=null?k1(n.rootApiFile["base-path"],r["base-path"],q.path):k1(r["base-path"],q.path)),pathParameters:B,allPathParameters:q["base-path"]!=null?B:[...t,...g,...B],queryParameters:typeof q.request!="string"&&q.request?.["query-parameters"]!=null?await Promise.all(Object.entries(q.request["query-parameters"]).map(async([C,F])=>await xTa({file:n,queryParameterKey:C,queryParameter:F}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,F])=>U2e({headerKey:C,header:F,file:n}))):[],requestBody:Wtd({request:q.request,file:n}),sdkRequest:await $td({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await Prd({endpoint:q,file:n,typeResolver:a}),errors:[...Erd({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:Ord({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(F=>Ytd({codeSample:F,file:n}))})):[],autogeneratedExamples:[],pagination:await Srd({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=o1.generateEndpointId(P,I),I}))}}async function Szn({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>u6w({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function u6w({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await X$(t),name:n.casingsGenerator.generateName(e),valueType:s6w({parameter:t,variableResolver:i,file:n}),location:r,variable:NIn(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function s6w({parameter:e,variableResolver:t,file:r}){let n=xPi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function xPi({parameter:e,variableResolver:t,file:r}){let n=CTa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function CTa({parameter:e,variableResolver:t,file:r}){if(NIn(e)){let n=typeof e=="string"?e:e.variable,i=t.getDeclaration(n,r);return i==null?void 0:{rawType:typeof i.declaration=="string"?i.declaration:i.declaration.type,file:i.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function c6w(e){switch(e){case"GET":return Rie.Get;case"POST":return Rie.Post;case"PUT":return Rie.Put;case"PATCH":return Rie.Patch;case"DELETE":return Rie.Delete;default:xc(e)}}async function U2e({headerKey:e,header:t,file:r}){let{name:n}=uLt({headerKey:e,header:t});return{...await X$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function uLt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function l6w(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:xc(e)}}var Z$={};kc(Z$,{validateObjectExample:()=>Ian,validateTypeExample:()=>ATa,validateTypeReferenceExample:()=>nQ});function Trd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function qTa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function Crd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:o1.generateEndpointIdFromResolvedEndpoint(i),serviceId:o1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:qTa({fernFilePath:i.file.fernFilepath})?void 0:o1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{refreshToken:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.refresh_token})},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function qrd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:o1.generateEndpointIdFromResolvedEndpoint(i),serviceId:o1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:qTa({fernFilePath:i.file.fernFilepath})?void 0:o1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{clientId:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_id}),clientSecret:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_secret}),scopes:n.requestProperties.scopes!=null?await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.scopes}):void 0},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Ird({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await qrd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:i});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?await Crd({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:n["client-id-env"],clientSecretEnvVar:n["client-secret-env"],tokenPrefix:n["token-prefix"],scopes:n.scopes,tokenEndpoint:u,refreshEndpoint:f}}var TPi={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}},Tqu={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 Brd(e){return{endpoint:e["get-token"].endpoint,requestProperties:f6w({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:d6w({responseProperties:e["get-token"]?.["response-properties"]})}}function Nrd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:p6w({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:_6w({responseProperties:e["refresh-token"]?.["response-properties"]})}}function f6w({requestProperties:e}){if(e==null)return TPi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?WIt(t):TPi.requestProperties.client_id,client_secret:r!=null?WIt(r):TPi.requestProperties.client_secret,scopes:n!=null?WIt(n):TPi.requestProperties.scopes}}function d6w({responseProperties:e}){return zrd({responseProperties:e,defaultValue:TPi.responseProperties})}function p6w({requestProperties:e}){if(e==null)return Tqu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?WIt(t):Tqu.requestProperties.refresh_token}}function _6w({responseProperties:e}){return zrd({responseProperties:e,defaultValue:Tqu.responseProperties})}function zrd({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],n=e["expires-in"],i=e["refresh-token"];return{type:"access_token",access_token:r!=null?fMr(r):t.access_token,expires_in:n!=null?fMr(n):t.expires_in,refresh_token:i!=null?fMr(i):t.refresh_token}}async function Vrd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:DNr.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return ayi(e.auth,{single:async a=>{let u=await Rrd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:DNr.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:DNr.Any,schemes:await Promise.all(a.map(async u=>await Rrd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function Rrd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:n,endpointResolver:i}){let a=(f,d)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return bsu(c,{header:async o=>EH.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:async o=>Lrd({file:r,docs:d,rawScheme:o}),bearer:async o=>Frd({file:r,docs:d,rawScheme:o}),oauth:async o=>await Urd({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Frd({file:r,docs:void 0,rawScheme:void 0});case"basic":return Lrd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await Urd({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Frd({file:e,docs:t,rawScheme:r}){return EH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Lrd({file:e,docs:t,rawScheme:r}){return EH.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})}async function Urd({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return EH.oauth({docs:t,configuration:SNr.clientCredentials(await Ird({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:Brd(r),refreshTokenEndpoint:Nrd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function Wrd({file:e,rawApiFileSchema:t}){if(t.version!=null)return ANr.header({header:await h6w({file:e,header:t.version.header}),value:await y6w({file:e,versionDeclaration:t.version})})}async function h6w({file:e,header:t}){return typeof t=="string"?await U2e({file:e,headerKey:t,header:{type:"string"}}):await U2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function y6w({file:e,versionDeclaration:t}){return await MTa({_enum:{default:t.default,enum:t.values},file:e})}async function Hrd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a}){let u=[];for(let[f,d]of Object.entries(e.messages??{}))u.push({type:f,availability:Sae(d.availability),docs:d.docs,origin:d.origin,body:g6w({body:d.body,file:i}),displayName:d["display-name"]});return{availability:Sae(e.availability),path:F2e(e.path),auth:e.auth,name:i.fernFilepath.file??i.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?await Promise.all(Object.entries(e.headers).map(([f,d])=>U2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await Szn({pathParameters:e["path-parameters"],location:OCe.Endpoint,file:i,variableResolver:n}):[],queryParameters:e["query-parameters"]!=null?await Promise.all(Object.entries(e["query-parameters"]).map(async([f,d])=>{let{name:c}=pMr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await X$(d),name:i.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}})):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let d=O6w({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a});return{name:f.name!=null?i.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:w6w({channel:e,example:f,pathParams:d}),...d,...P6w({channel:e,example:f,typeResolver:t,exampleResolver:r,file:i,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:i.casingsGenerator.generateNameAndWireValue({name:pMr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:v6w({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:b6w({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function v6w({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function b6w({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!j6w(e.body))return F6t.reference(lT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!lS(t))throw new Error("Example must be an object");let u=[];for(let[f,d]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:f,property:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let o=MPi({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:i});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:o.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:o.typeName})}}return F6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function g6w({body:e,file:t}){return typeof e=="string"?DCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):m6w(e)?DCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):DCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:VIt(e.extends??[]).map(r=>CU({typeName:r,file:t})),properties:[]})}function m6w(e){return e.type!=null}function O6w({channel:e,example:t,typeResolver:r,exampleResolver:n,variableResolver:i,file:a,workspace:u}){let f=[],d=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let g=xPi({parameter:o,variableResolver:i,file:a});return{name:c,value:lT({example:l,rawTypeBeingExemplified:g.rawType,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null)for(let[c,o]of Object.entries(t["path-parameters"])){let l=e["path-parameters"]?.[c];if(l!=null)f.push(d({name:a.casingsGenerator.generateName(c),pathParameterDeclaration:l,examplePathParameter:o}));else throw new Error(`Path parameter ${c} does not exist`)}return{pathParameters:f}}function P6w({channel:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=[];if(t.headers!=null)for(let[f,d]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:f,header:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function w6w({channel:e,example:t,pathParams:r}){let n=e.path;if(t["path-parameters"]!=null)for(let i of[...r.pathParameters])n=n.replaceAll(`{${i.name.originalName}}`,`${i.value.jsonExample}`);return n}function j6w(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function Cqu({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{defaultEnvironment:e??void 0,environments:NEr(n,{singleBaseUrl:()=>q6t.singleBaseUrl(D6w({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q6t.multipleBaseUrls(S6w({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function D6w({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>NEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:Qrd(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function S6w({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>NEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>Qrd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function Qrd(e){return e.endsWith("/")?e.slice(0,-1):e}function Jrd({errorName:e,errorDeclaration:t,file:r,typeResolver:n,exampleResolver:i,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:i.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:lT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:oRr({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 Grd="content";function $rd(e,t){if(e==null||e.strategy==="status-code")return z6t.statusCode();switch(e.strategy){case"property":return z6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Grd,wireValue:Grd})});default:xc(e)}}function Krd({readme:e,services:t}){let r=new qqu(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(([n,i])=>[n,i.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var qqu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=A6w({endpoint:t}),n=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[n]}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 n of Object.values(t))for(let i of n.endpoints)r[this.getEndpointKeyForHttpEndpoint(i)]=i;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:E6w(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function E6w(e){let t="";e.fullPath.head.length>0&&(t=k1(t,e.fullPath.head));for(let r of e.fullPath.parts)t=k1(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=k1(t,r.tail));return t.startsWith("/")?t:`/${t}`}function A6w({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}async function Yrd({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:o1.generateWebhookId(t.fernFilepath,u),availability:Sae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?await Promise.all(Object.entries(f.headers).map(([d,c])=>U2e({headerKey:d,header:c,file:t}))):[],payload:M6w({payload:f.payload,file:t}),examples:f.examples!=null?T6w({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function M6w({payload:e,file:t}){return typeof e=="string"?Qie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):ITa(e)?Qie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Qie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:VIt(e.extends).map(r=>CU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>x6w({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?Sae(n.availability):void 0,file:t})):[]})}function x6w({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:rQ({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function T6w({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:ITa(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:lT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!lS(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:lT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function ITa(e){return e.type!=null}function Ezn(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Xrd({name:e,source:t}){return wD.userDefined({file:TTa({source:t}),name:uRr.generateName(e)})}function Zrd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=C6w({type:e.proto.type});if(t!=null)return t}}function C6w({type:e}){switch(e){case"google.protobuf.Any":return wD.wellKnown(uh.any());case"google.protobuf.Api":return wD.wellKnown(uh.api());case"google.protobuf.BoolValue":return wD.wellKnown(uh.boolValue());case"google.protobuf.BytesValue":return wD.wellKnown(uh.bytesValue());case"google.protobuf.DoubleValue":return wD.wellKnown(uh.doubleValue());case"google.protobuf.Duration":return wD.wellKnown(uh.duration());case"google.protobuf.Empty":return wD.wellKnown(uh.empty());case"google.protobuf.Enum":return wD.wellKnown(uh.enum());case"google.protobuf.EnumValue":return wD.wellKnown(uh.enumValue());case"google.protobuf.Field":return wD.wellKnown(uh.field());case"google.protobuf.FieldCardinality":return wD.wellKnown(uh.fieldCardinality());case"google.protobuf.FieldKind":return wD.wellKnown(uh.fieldKind());case"google.protobuf.FieldMask":return wD.wellKnown(uh.fieldMask());case"google.protobuf.FloatVlaue":return wD.wellKnown(uh.floatValue());case"google.protobuf.Int32Value":return wD.wellKnown(uh.int32Value());case"google.protobuf.Int64Value":return wD.wellKnown(uh.int64Value());case"google.protobuf.ListValue":return wD.wellKnown(uh.listValue());case"google.protobuf.Method":return wD.wellKnown(uh.method());case"google.protobuf.Mixin":return wD.wellKnown(uh.mixin());case"google.protobuf.NullValue":return wD.wellKnown(uh.nullValue());case"google.protobuf.Option":return wD.wellKnown(uh.option());case"google.protobuf.SourceContext":return wD.wellKnown(uh.sourceContext());case"google.protobuf.StringValue":return wD.wellKnown(uh.stringValue());case"google.protobuf.Struct":return wD.wellKnown(uh.struct());case"google.protobuf.Syntax":return wD.wellKnown(uh.syntax());case"google.protobuf.Timestamp":return wD.wellKnown(uh.timestamp());case"google.protobuf.Type":return wD.wellKnown(uh.type());case"google.protobuf.Uint32Value":return wD.wellKnown(uh.uint32Value());case"google.protobuf.Uint64Value":return wD.wellKnown(uh.uint64Value());case"google.protobuf.Value":return wD.wellKnown(uh.value())}}async function krd({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=E3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&mA(a.declaration)){let u=E3(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([d,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=i.arguments?.[u.indexOf(c)]??c),[d,o]});return Sq.object({extends:VIt(a.declaration.extends).map(d=>CU({typeName:d,file:t})),properties:await jPi({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${n}`)}async function end({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return gCe(n)?await krd({generic:n,file:t,typeResolver:r}):Sq.alias({aliasOf:t.parseTypeReference(e),resolvedType:q6w({aliasOf:n,file:t,typeResolver:r})})}function q6w({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return AH.primitive(n.originalTypeReference.primitive);case"container":return AH.container(n.originalTypeReference.container);case"unknown":return AH.unknown();case"named":{let i=mA(n.declaration)?R6t.Object:LNr(n.declaration)?R6t.Union:V6t(n.declaration)?R6t.Enum:RIn(n.declaration)?R6t.UndiscriminatedUnion:xc(n.declaration);return AH.named({name:n.name,shape:i})}}}function tnd({union:e,file:t}){return Sq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function rnd(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 Bqu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new Iqu}){let i=I8(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=E3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=E3(o.typeName)?.arguments;if(mA(o.declaration)){let g=rnd(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>rnd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),f.push(...Object.values(u.union).reduce((d,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&d.push(o),d},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,d)=>{let c=typeof d=="string"?d:d.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of i){let f=O$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:c})=>[...d,...c],list:d=>d,optional:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of f){let c=CU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(gCe(o.typeName))continue;a.push(...Bqu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var Iqu=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}};async function nnd({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await X$(t),d=CU({typeName:e,file:r}),c=Bqu({typeDeclaration:t,file:r,typeResolver:n}),o={};mA(t)&&(o=Ezn(t.properties??{}));let l=await B6w({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await I6w({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:N6w({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(g=>({name:g.name!=null?r.casingsGenerator.generateName(g.name):void 0,docs:g.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:g.value,file:r}).resolvedExample,shape:xqu({typeName:d,example:g.value,typeResolver:n,exampleResolver:i,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(g=>g.fernFilepath))}}async function I6w({typeDeclaration:e,file:t,typeResolver:r}){return await I8(e,{alias:n=>end({alias:n,file:t,typeResolver:r}),object:n=>Utd({object:n,file:t}),discriminatedUnion:n=>nrd({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>tnd({union:n,file:t}),enum:async n=>Sq.enum(await MTa({_enum:n,file:t}))})}async function B6w({file:e,typeDeclaration:t,typeName:r,sourceResolver:n}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Zrd({encoding:t.encoding});if(a!=null)return IEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return IEr.proto(Xrd({source:i,name:r}))}function N6w({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?z6w(e.encoding):R6w(t)}function z6w(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function R6w(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function ind(e,t){let r=t[e];if(r==null)throw new JSr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function and(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,L6w({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>F6w({endpoint:n,ir:e}))}]))}}function F6w({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>ond(r,t))}}}function L6w({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>ond(r,t))}}}return e}function ond(e,t){let r=Nqu(e.typeId,t);return und({objectTypeDeclaration:r,ir:t})}function Nqu(e,t){let r=ind(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Nqu(r.shape.resolvedType.name.typeId,t)}throw new JSr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function und({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=Nqu(n.typeId,t);return und({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var BTa=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:a,endpoints:u,webhooks:f,subpackages:d,queryParameters:c,requestProperties:o,webhookPayloadProperties:l}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=c}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=o1.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=o1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=o1.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 n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var NTa=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=U6w(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=o1.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=o1.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){return this.typesReferencedByService}addError(t){let r=o1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&Q5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=o1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])Q5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])Q5(c.valueType,u,d);for(let c of r.queryParameters)Q5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=Ezn(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&M5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)zqu(o,u,d);for(let o of c.properties)Q5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&y6(n.request.body)){let o=Ezn(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{Q5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)Fie._visit(o,{file:ll,bodyProperty:({valueType:l})=>{Q5(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&A3._visit(r.response.body,{fileDownload:ll,json:c=>{Q5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>Q5(o.payload,u,d),json:o=>Q5(o.payload,u,d),text:ll,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>Q5(o.payload,u,d),json:o=>Q5(o.payload,u,d),text:ll,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&Q5(c.nonStreamResponse.value.responseBodyType,u,d)},text:ll,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(o1.generateErrorId(c.error)),d.add(c.error.fernFilepath)});for(let c of u)this.markTypeForService(c,i);this.endpoints[a]={endpointId:a,referencedTypes:u,referencedErrors:f,referencedSubpackages:d}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=o1.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,n){let i=r.id;if(i==null)return;let a=new Set,u=new Set;r.payload!=null&&Qie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)zqu(d,a,u);for(let d of f.properties)Q5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!ITa(n.payload)){let d=Ezn(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{Q5(f,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let f of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(f);for(let c of d.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(f);this.addReferencedTypes(t,d.referencedTypes)}let n={},i={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,d]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}c.size>0&&(n[f]=c),n[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}i[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(g=>{c.add(g)})}a[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}u[f]=c.size>0?c:void 0}}return new BTa({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t];n==null?this.typesReferencedByService[t]=new Set(r):n.add(r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=i.descendantsByAudience[a];if(u!=null)u.forEach(f=>{t.add(f)});else{i.allDescendants.forEach(f=>{t.add(f)});break}}else i.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}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:xc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(o1.generateSubpackageId(n))}}};function U6w(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:xc(e)}}function Q5(e,t,r){uT._visit(e,{container:n=>{V6w(n,t,r)},named:n=>{zqu(n,t,r)},primitive:ll,unknown:ll,_other:ll})}function zqu(e,t,r){t.add(o1.generateTypeId(e)),r.add(e.fernFilepath)}function V6w(e,t,r){Eq._visit(e,{list:n=>{Q5(n,t,r)},map:n=>{Q5(n.keyType,t,r),Q5(n.valueType,t,r)},optional:n=>{Q5(n,t,r)},set:n=>{Q5(n,t,r)},literal:ll,_other:ll})}function cnd({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?C8.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?C8.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function ON({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(gA.list({...n,list:n.list.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(gA.set({...n,set:n.set.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?ON({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(gA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(gA.map({...n,map:n.map.map(i=>{let a=ON({filteredIr:e,exampleTypeReference:i.key}),u=ON({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:dS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:dS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=cnd({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Rqu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function W6w({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function snd({filteredIr:e,headers:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function H6w({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?v$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function Q6w({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>T4.ok(cN.body(n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>T4.ok(cN.stream(n.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter($M))),sse:n=>T4.ok(cN.sse(n.map(({event:i,data:a})=>{let u=ON({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter($M))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>T4.error({error:r,body:n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Fqu({filteredIr:e,example:t}){return{...t,rootPathParameters:Rqu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Rqu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Rqu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:snd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:snd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:W6w({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?H6w({filteredIr:e,requestBody:t.request}):void 0,response:Q6w({filteredIr:e,response:t.response})}}function lnd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:ON({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=cnd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var zTa=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 n=this.getPackageForFernFilepath(t);if(n.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");n.navigationConfig={pointsTo:o1.generateSubpackageId(r)}}addDocs(t,r){let n=this.getPackageForFernFilepath(t);if(n.docs!=null)throw new Error("Found duplicate docs for package");n.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 n=this.getPackageForFernFilepath(r.name.fernFilepath);if(n.service!=null)throw new Error("Found duplicate service for "+t);n.service=t}addWebhookGroup(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.webhooks=t}addWebSocketChannel(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([n,i])=>{t.hasSubpackageId(n)?this.subpackages[n]={...i,types:i.types.filter(a=>t.hasTypeId(a)),errors:i.errors.filter(a=>t.hasErrorId(a)),service:i.service!=null&&t.hasServiceId(i.service)?i.service:void 0,subpackages:i.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[n]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(n=>t.hasTypeId(n)),errors:this.rootPackage.errors.filter(n=>t.hasErrorId(n)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(n=>t.hasSubpackageId(n)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:by(this.subpackages,(n,i)=>({...n,hasEndpointsInTree:r.has(i)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!fnd(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let n=this.subpackages[t];if(n==null)throw new Error("Subpackage does not exist: "+t);if(!fnd(n.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");n.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let n=this.getAllChildrenWithEndpoints(r);return(n.length>0||r.service!=null)&&n.push(t),n}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,n=this.rootPackage){let i=t.allParts[r];if(i==null)return n;let a=n.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},d=a.find(c=>c.name.originalName===i.originalName);if(d==null){let c=o1.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:i,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,n.subpackages.push(c),d=o}return this.getPackageForFernFilepath(t,u,d)}};function fnd(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let n of t)if(!r.has(n))return!1;return!0}function dnd({reference:e,referencedIn:t,imports:r}){let[n,i,...a]=e.split(".");if(n==null||a.length>0)return;if(i==null)return{endpointName:n,relativeFilepath:t};let f=r[n];if(f!=null)return{endpointName:i,relativeFilepath:aRr({referencedIn:t,importPath:f})}}var Nan=class{workspace;constructor(t){this.workspace=t}async resolveEndpointOrThrow({endpoint:t,file:r}){let n=await this.resolveEndpoint({endpoint:t,file:r});if(n==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return n}async resolveEndpointByMethodAndPath({method:t,path:r}){let n;return await W8(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:uRr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(n={endpointId:d,endpoint:c,file:f})}),await Enn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:uRr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(n={endpointId:f,endpoint:d,file:u})}),n}async resolveEndpoint({endpoint:t,file:r}){let i=new oyi().tryParse(t);if(i!=null)return await this.resolveEndpointByMethodAndPath(i);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 n=dnd({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(!(i==null||i.service?.endpoints?.[n.endpointName]==null))return{endpointName:n.endpointName,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var zan=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Error does not exist: "+t);return n}getDeclaration(t,r){let n=LDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.errors?.[n.typeName];if(a!=null)return{declaration:a,file:qO({definitionFile:i,relativeFilepath:n.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var VDe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let n=this.resolveExample({example:t,file:r});return n==null||typeof n.resolvedExample=="string"?n:this.resolveAllReferencesInExample({example:n.resolvedExample,file:n.file})}else if(lS(t)){let n={};for(let[i,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;n[i]=u.resolvedExample}return{resolvedExample:n}}else if(Array.isArray(t)){let n=[];for(let i of t){let a=this.resolveAllReferencesInExample({example:i,file:r});if(a==null)return;n.push(a.resolvedExample)}return{resolvedExample:n}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let n=this.resolveAllReferencesInExample({example:t,file:r});if(n==null)throw new Error("Failed to resolve examples");return n}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${oFt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(oFt))return{resolvedExample:t,file:r};let n=this.parseExampleReference(t);if(n==null)return;let i=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:n.rawTypeReference,file:r});if(i==null||typeof i.declaration=="string"||i.declaration.examples==null)return;let a=i.declaration.examples.find(u=>u.name===n.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:i.file})}resolveExampleOrThrow({example:t,file:r}){let n=this.resolveExample({example:t,file:r});if(n==null)throw new Error("Cannot resolve example: "+t);return n}parseExampleReference(t){let[r,n,i,...a]=t.split(".");if(!(r==null||n==null||a.length>0))return i==null?{rawTypeReference:r.slice(oFt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(oFt.length),exampleName:i}}};var RTa=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}async resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveRequestProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(i.endpoint.request==null)return;if(typeof i.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:i.file,requestType:i.endpoint.request,propertyComponents:n});let a=await this.resolveObjectProperty({file:i.file,typeName:i.endpoint.request,propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:Vie.body(a)}}async resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveResponseProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=await this.resolveObjectProperty({file:i.file,typeName:(typeof i.endpoint.response!="string"?i.endpoint.response?.type:i.endpoint.response)??"",propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:a}}async resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(i.length===1){let a=i[0]??"",u=typeof n["query-parameters"]!=null?n["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Vie.query(await xTa({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i})}async resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(n.body==null)return;if(typeof n.body=="string"){let u=await this.resolveObjectProperty({file:r,typeName:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(u)}}if(y6(n.body)){let u=await Equ({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(u)}}let a=await this.resolveObjectProperty({file:r,typeName:n.body.type,propertyComponents:i});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await Squ({typeResolver:this.typeResolver,file:SPi(i)??t,resolvedType:i,propertyComponents:n})}async propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(n=>r.casingsGenerator.generateName(n))}};var pnd=require("fs/promises"),FTa=class{async parse({absoluteFilePath:t}){let r=await(0,pnd.readFile)(t,"utf-8"),n=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),i=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:n?.[1],packageName:i?.[1],serviceName:a?.[1]}}};var LTa=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}async resolveSourceOrThrow({source:t,file:r}){let n=await this.resolveSource({source:t,file:r});if(n==null){if(hca(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r.relativeFilepath}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r.relativeFilepath}`)}return n}async resolveSource({source:t,file:r}){return hca(t)?await this.resolveProtobufSource({source:t,file:r}):await this.resolveOpenAPISource({source:t,file:r})}async resolveProtobufSource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.proto));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let a=await new FTa().parse({absoluteFilePath:n}),u={type:"protobuf",absoluteFilePath:n,relativeFilePath:Ms.of(t.proto),csharpNamespace:a.csharpNamespace,packageName:a.packageName,serviceName:a.serviceName};return this.sourceCache.set(n,u),u}async resolveOpenAPISource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.openapi));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let i={type:"openapi",absoluteFilePath:n,relativeFilePath:Ms.of(t.openapi)};return this.sourceCache.set(n,i),i}};var eM=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let n=this.resolveType({type:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let n=LDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=E3(n.typeName);if(u!=null){for(let f of Object.keys(i.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let d=i.types?.[f];return d!=null?{typeName:f,declaration:d,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:n.typeName,declaration:a,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:n=[]}){return O$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:uT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:uT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:uT.container(Eq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:uT.container(Eq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:uT.container(Eq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:uT.container(Eq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:uT.container(Eq.literal(i))}),named:i=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:i,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:i};if(!n.some(f=>f.file===u.file&&f.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:i,referencedIn:r,rawDeclaration:a,objectPath:[...n,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.resolveNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t);return n}resolveNamedType({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n,objectPath:i=[]}){let{declaration:a,file:u}=n;if(zIn(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=ETa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||lae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:n.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:i,originalTypeReference:f,file:u}}};var QIt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Variable does not exist: "+t);return n}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let n=r.rootApiFile.variables?.[t.substring(1)];if(n!=null)return{declaration:n,file:dMr({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 UTa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function _nd({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":{let r=e??aD.STRING;return{type:"success",example:Pv.string({original:r}),jsonExample:r}}case"BASE_64":return{type:"success",example:Pv.base64(aD.BASE64),jsonExample:aD.BASE64};case"BOOLEAN":return{type:"success",example:Pv.boolean(aD.BOOLEAN),jsonExample:aD.BOOLEAN};case"DATE":return{type:"success",example:Pv.date(aD.DATE),jsonExample:aD.DATE};case"DATE_TIME":return{type:"success",example:Pv.datetime({datetime:new Date(aD.DATE_TIME),raw:aD.DATE_TIME}),jsonExample:aD.DATE_TIME};case"DOUBLE":return{type:"success",example:Pv.double(aD.DOUBLE),jsonExample:aD.DOUBLE};case"FLOAT":return{type:"success",example:Pv.float(aD.FLOAT),jsonExample:aD.FLOAT};case"INTEGER":return{type:"success",example:Pv.integer(aD.INT),jsonExample:aD.INT};case"UINT_64":return{type:"success",example:Pv.uint64(aD.INT64),jsonExample:aD.INT64};case"UINT":return{type:"success",example:Pv.uint(aD.UINT),jsonExample:aD.UINT};case"BIG_INTEGER":return{type:"success",example:Pv.bigInteger(aD.INT64.toString()),jsonExample:`${aD.INT64}`};case"LONG":return{type:"success",example:Pv.long(aD.INT64),jsonExample:aD.INT64};case"UUID":return{type:"success",example:Pv.uuid(aD.UUID),jsonExample:aD.UUID};default:xc(t.v1)}}function hnd({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return cRr({containerType:t});switch(t.type){case"list":{let u=YF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gA.literal({literal:t.literal._visit({boolean:u=>Pv.boolean(u),string:u=>Pv.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 cRr({containerType:t});let u=YF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=YF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=YF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=YF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:xc(t)}}function cRr({containerType:e}){switch(e.type){case"list":return{type:"success",example:gA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gA.literal({literal:e.literal._visit({boolean:t=>Pv.boolean(t),string:t=>Pv.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:gA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:gA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:xc(e)}}function Azn({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 vnd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=YF({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.alias({value:f}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=ynd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=YF({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:c,jsonExample:o}=d;return{type:"success",example:dS.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let d=f.shape._visit({noProperties:()=>({type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.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=ynd({currentDepth:i,maxDepth:n,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:g,jsonExample:O}=l;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=YF({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:g}=o;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:g}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function ynd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:u}){let f={},d=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=YF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!Azn({typeDeclarations:n,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:g}=o;d.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=g}return{type:"success",example:dS.object({properties:d}),jsonExample:f}}function YF({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)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=vnd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:d,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:dO.named({shape:d,typeName:u.name})},jsonExample:c}}case"container":{let u=hnd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=cRr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:dO.container(c)},jsonExample:o}}let{example:f,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:dO.container(f)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:f}=_nd({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:dO.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:dO.unknown(u)},jsonExample:u}}}}var bnd=Xo(y1u(),1);function CPi({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:T4.ok(cN.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=YF({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}for(let c of t.queryParameters){if(i&&Azn({typeDeclarations:n,typeReference:c.valueType}))continue;let o=YF({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:c.valueType,skipOptionalProperties:i});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?NF.exploded():NF.single(),value:l})}let d=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of d)for(let o of c.params){if(i&&Azn({typeDeclarations:n,typeReference:o.valueType}))continue;let l=YF({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}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 g=YF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!Azn({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${g.message}`};if(g.type==="failure")continue;let{example:O,jsonExample:P}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=P}u.request=v$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=v$.reference(o);break}default:xc(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=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=T4.ok(cN.body({...o,jsonExample:l}));break}case"streamParameter":return{type:"failure",message:"Stream parameter unsupported"};case"streaming":return{type:"failure",message:"Streaming unsupported"};case"text":return{type:"failure",message:"Text unsupported"};default:xc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=T4.error({body:void 0,error:a.declaration.name});else{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=T4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,bnd.default)(u),url:J6w(t,u),...u},jsonExample:void 0}}function J6w(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=u});let n=e.fullPath.head+e.fullPath.parts.map(i=>r[i.pathParameter]+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}async function iQ({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,includeOptionalRequestPropertyExamples:u,audiences:f,readme:d,packageName:c,version:o,context:l}){let g=aLt({generationLanguage:r,keywords:n,smartCasing:i}),O=new NTa(f),P=dMr({casingsGenerator:g,rootApiFile:t.definition.rootApiFile.contents}),j=(t.definition.rootApiFile.contents.errors??[]).map(Gt=>({error:oRr({errorName:Gt,file:P}),docs:void 0})),M=new eM(t),q=new Nan(t),B=new RTa(M,q),I=new zan(t),C=new VDe(M),F=new QIt,K=new LTa(l,t),ee={fdrApiDefinitionId:e,apiVersion:await Wrd({file:P,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:g.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await wTa(t.definition.rootApiFile.contents.docs),auth:await Vrd({rawApiFileSchema:t.definition.rootApiFile.contents,file:P,propertyResolver:B,endpointResolver:q}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Gt,ln])=>U2e({headerKey:Gt,header:ln,file:P}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Gt,ln])=>U2e({headerKey:Gt,header:ln,file:P}))):[],types:{},errors:{},services:{},constants:Trd(g),environments:Cqu({casingsGenerator:g,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:$rd(t.definition.rootApiFile.contents["error-discrimination"],P),basePath:t.definition.rootApiFile.contents["base-path"]!=null?F2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await Szn({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:P,location:OCe.Root,variableResolver:F}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Gt,ln])=>({docs:typeof ln!="string"?ln.docs:void 0,id:Gt,name:P.casingsGenerator.generateName(Gt),type:P.parseTypeReference(ln)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},J=new zTa,G=async Gt=>{J.addSubpackage(Gt.fernFilepath),await VP(Gt.definitionFile,{imports:ll,docs:ln=>{ln!=null&&J.addDocs(Gt.fernFilepath,ln)},types:async ln=>{if(ln!=null)for(let[En,Ht]of Object.entries(ln)){if(gCe(En))continue;let tr=await nnd({typeName:En,typeDeclaration:Ht,file:Gt,typeResolver:M,exampleResolver:C,sourceResolver:K,workspace:t}),on=tr.typeDeclaration;a&&(on.userProvidedExamples=[],on.autogeneratedExamples=[]);let dn=tr.descendantFilepaths,wi=o1.generateTypeId(on.name);ee.types[wi]=on,J.addType(wi,on),O.addType({declaredTypeName:on.name,descendantTypeIds:on.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:tr.propertiesByAudience,descendantFilepaths:dn}),O.markTypeForAudiences(on.name,Ltd(Ht))}},errors:ln=>{if(ln==null)return;if(t.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[Ht,tr]of Object.entries(ln)){let on=Jrd({errorName:Ht,errorDeclaration:tr,file:Gt,typeResolver:M,exampleResolver:C,workspace:t}),dn=o1.generateErrorId(on.name);ee.errors[dn]=on,J.addError(dn,on),O.addError(on)}},service:async ln=>{if(ln==null)return;let En=await xrd({rootDefaultUrl:Gt.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:ee.pathParameters,serviceDefinition:ln,file:Gt,errorResolver:I,typeResolver:M,propertyResolver:B,exampleResolver:C,sourceResolver:K,globalErrors:j,variableResolver:F,workspace:t}),Ht=o1.generateServiceId(En.name);ee.services[Ht]=En,J.addService(Ht,En);let tr={};En.endpoints.forEach(on=>{a&&(on.autogeneratedExamples=[],on.userSpecifiedExamples=[]);let dn=ln.endpoints[on.name.originalName];O.addEndpoint(En,on,dn),tr[on.name.originalName]=on}),ln.audiences!=null&&O.markEndpointForAudience(En.name,En.endpoints,ln.audiences),Object.entries(ln.endpoints).map(([on,dn])=>{let wi=tr[on];wi!=null&&dn.audiences!=null&&O.markEndpointForAudience(En.name,[wi],dn.audiences)})},webhooks:async ln=>{if(ln==null)return;let En=o1.generateWebhookGroupId(Gt.fernFilepath),Ht=await Yrd({webhooks:ln,file:Gt,typeResolver:M,exampleResolver:C,workspace:t}),tr={};for(let on of Ht)tr[on.name.originalName]=on;Object.entries(ln).forEach(([on,dn])=>{let wi=tr[on];wi!=null&&(O.addWebhook(Gt,wi,dn),dn.audiences!=null&&O.markWebhookForAudiences(Gt,wi,dn.audiences))}),ee.webhookGroups[En]=Ht,J.addWebhookGroup(En,Gt.fernFilepath)},channel:async ln=>{if(ln==null)return;let En=o1.generateWebSocketChannelId(Gt.fernFilepath),Ht=await Hrd({channel:ln,file:Gt,variableResolver:F,typeResolver:M,exampleResolver:C,workspace:t});ee.websocketChannels!=null&&(ee.websocketChannels[En]=Ht,J.addWebSocketChannel(En,Gt.fernFilepath))}})};await W8(t,async(Gt,ln,En)=>{await G(qO({relativeFilepath:Gt,definitionFile:ln,casingsGenerator:g,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:En.defaultUrl}))}),await Enn(t,async(Gt,ln)=>{if(ln.navigation!=null)if(typeof ln.navigation=="string")J.addPackageRedirection({from:Dae({relativeFilepath:Gt,casingsGenerator:g}),to:Dae({relativeFilepath:yf(cb(Gt),Ms.of(ln.navigation)),casingsGenerator:g})});else{let En=ln.navigation.map(Ht=>o1.generateSubpackageId(Dae({relativeFilepath:yf(cb(Gt),Ms.of(Ht)),casingsGenerator:g})));Gt===$A?J.sortRootPackage(En):J.sortSubpackage(o1.generateSubpackageId(Dae({relativeFilepath:Gt,casingsGenerator:g})),En)}}),ee.serviceTypeReferenceInfo=$6w(O);let te=a?ee:G6w(ee,l,!u),Ye=t.definition.rootApiFile.contents,Re=Cqu({casingsGenerator:g,rawApiFileSchema:Ye}),wt=Re?.environments._visit({singleBaseUrl:Gt=>Gt.environments.filter(ln=>UTa(ln.id,Ye.environments)!=null).length===0,multipleBaseUrls:Gt=>Gt.environments.filter(ln=>UTa(ln.id,Ye.environments)!=null).length===0,_other:()=>!1});Re?.environments.environments.forEach(Gt=>{O.markEnvironmentForAudiences(Gt,UTa(Gt.id,Ye.environments)??[],wt)});let Ct=O.hasNoAudiences()?void 0:O.build(),Wt=K6w(te,Ct),Bt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Wt.services).every(Gt=>Gt.endpoints.every(ln=>ln.auth)),or=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.response?.body?.type==="streaming")),jr=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.pagination!=null)),Vr=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.response?.body?.type==="fileDownload")),It=d!=null?Krd({readme:d,services:ee.services}):void 0,{types:cr,services:fn}=and(Wt);return{...Wt,...J.build(Ct),types:cr,services:fn,sdkConfig:{isAuthMandatory:Bt,hasStreamingEndpoints:or,hasPaginatedEndpoints:jr,hasFileDownloadEndpoints:Vr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:o!=null&&c!=null?{header:"User-Agent",value:`${c}/${o}`}:void 0}},readmeConfig:It}}function G6w(e,t,r){for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=CPi({ir:e,service:i,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 $6w(e){let t={},r=[],n=e.getTypesReferencedByService();for(let[i,a]of Object.entries(n)){if(a.size===1){let u=a.values().next().value;t[u]===void 0&&(t[u]=[]),t[u]?.push(i);continue}r.push(i)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function K6w(e,t){if(t==null)return e;let r=Pkr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>lnd({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)&&d.push(c);return[u,{...f,shape:Sq.object({...f.shape,properties:d})}]}return[u,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let d=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,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:n,errors:Pkr(e.errors,u=>t.hasError(u)),services:by(Pkr(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(d=>({...d,example:Fqu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?Fqu({filteredIr:t,example:d.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(d=>t.hasQueryParameter(f.id,d.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(d=>t.hasRequestProperty(f.id,d.name.wireValue))}}:f))})),webhookGroups:i,serviceTypeReferenceInfo:Y6w(e.serviceTypeReferenceInfo,t)}}function Y6w(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}var And=Xo(vTa(),1),Mnd=Xo(bTa(),1),HTa=require("fs/promises"),xnd=Xo(cxa(),1);function sLt(e){return typeof e.subpackageId=="string"}function WDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Ran(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Lqu="__package__",lRr=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#n=new Map;#i=new Map;#r=new Map;#a=new Map;#o=new Map;#f=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return sLt(t)?t.subpackageId:Lqu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=KF.SubpackageId(t);return r===Lqu?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(n=>{let i=KF.SubpackageId(e.getSubpackageId(n)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(i,a),n.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,i);this.#e.set(f,u);let d=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{d.push(`${o} ${WDe(u.path.parts)}`),d.push(`${o} ${Ran(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,WDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ran(u.path.parts))}`);let g=gnd(l);g!=null&&(d.push(`${o} ${k1(g,WDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ran(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#f.set(o,u)})}),n.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,i);this.#t.set(f,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${WDe(u.path.parts)}`),d.push(`${o} ${Ran(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,WDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ran(u.path.parts))}`);let g=gnd(l);g!=null&&(d.push(`${o} ${k1(g,WDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ran(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.set(o,u)})}),n.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#n.set(e.createWebhookId(u,i),u)})}),this.#e.forEach((n,i)=>{this.#i.set(n,i)}),this.#t.forEach((n,i)=>{this.#r.set(n,i)}),this.#n.forEach((n,i)=>{this.#a.set(n,i)}),this.#p(t.rootPackage,[])}#p(t,r){if(t==null)return;let n=sLt(t)?[...r,t.name]:r,i=n.length===0?[Lqu]:n;if([i.join("."),i.join("/"),`${i.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#p(this.api.subpackages[t.pointsTo],n);t.endpoints.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#f.set(c,u)})}),t.websockets.forEach(u=>{let f=[...n,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=[...n,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.#p(this.api.subpackages[u],n)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#n}get endpointsByLocator(){return this.#f}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#r.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return Zc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Zc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Zc.WebhookId(`${r}.${t.id}`)}};function gnd(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 Mzn=Xo(vTa(),1),Ond=Xo(bTa(),1);function mnd(e){let t=e.split(".")[0];if(t==null)return;let n=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(n!=null)try{return new Date(n)}catch{}}Mzn.default.extend(Ond.default);var X6w="Changelog",Z6w=["summary","index","overview"],Fan=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}convert(t){if(this.changelogFiles==null||this.changelogFiles.length===0)return;let r=t.title??X6w;this.idgen=this.idgen.append("changelog");let n=[],i;for(let c of this.changelogFiles){let o=DKo(c.split("/"));if(o==null)continue;let l=mnd(o);if(l==null){let O=o.split(".")[0]?.toLowerCase();O!=null&&Z6w.includes(O)&&(i=c);continue}let g=this.toRelativeFilepath(c);n.push({date:l,pageId:Zc.PageId(g),absoluteFilepath:c})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??OF(r)}),u=n.map(c=>{let o=Mzn.default.utc(c.date);return{id:this.idgen.append(o.format("YYYY-M-D")).get(),type:"changelogEntry",title:o.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(c.absoluteFilepath)?.split("/"),urlSlug:o.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:c.date.toISOString(),pageId:c.pageId,noindex:void 0}}),f=Uqu(u,c=>c.date,"desc"),d=this.groupByYear(f,a);return{id:this.idgen.get(),type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:d,overviewPageId:i!=null?Zc.PageId(this.toRelativeFilepath(i)):void 0,noindex:void 0}}groupByYear(t,r){let n=new Map;for(let i of t){let a=Mzn.default.utc(i.date).year(),u=n.get(a)??[];u.push(i),n.set(a,u)}return Uqu(Array.from(n.entries()).map(([i,a])=>{let u=r.append(i.toString()).get();return{id:this.idgen.append(i.toString()).get(),type:"changelogYear",title:i.toString(),year:i,slug:u,icon:void 0,hidden:void 0,children:this.groupByMonth(a,r)}}),"year","desc")}groupByMonth(t,r){let n=new Map;for(let i of t){let a=Mzn.default.utc(i.date).month()+1,u=n.get(a)??[];u.push(i),n.set(a,u)}return Uqu(Array.from(n.entries()).map(([i,a])=>{let u=(0,Mzn.default)(new Date(0,i-1));return{id:this.idgen.append(u.format("YYYY-M")).get(),type:"changelogMonth",title:u.format("MMMM YYYY"),month:i,slug:r.append(i.toString()).get(),icon:void 0,hidden:void 0,children:a}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Uqu(e,t,r="asc"){return e.concat().sort((n,i)=>{let a=typeof t=="function"?t(n):n[t],u=typeof t=="function"?t(i):i[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}var fRr=class e{id;ids;static init(t){return new e(t,new Set([t]))}constructor(t,r){this.id=t,this.ids=r}get(){return Zc.V1.NodeId(this.id)}append(t){let r=`${this.id}.${t}`;if(this.ids.has(r)){let n=1;for(;this.ids.has(`${r}-${n}`);)n++;r=`${r}-${n}`}return this.ids.add(r),new e(r,this.ids)}};var VTa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#n=new Set;#i=new Set;#r=new Set;#a=new Map;#o=[];#f;#c;disableEndpointPairs;constructor(t,r,n,i,a,u,f){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Zc.V1.ApiDefinitionId(r.id),this.#e=lRr.create(r,u);let d=fRr.init(this.apiDefinitionId);this.#f=this.apiSection.overviewAbsolutePath!=null?Zc.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=n.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??OF(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,d)),this.#o=this.#d(this.#o.map(o=>this.#O(o)),this.#y(this.#e.api.rootPackage,this.#c))}get(){let t=Zc.V1.followRedirects(this.#o),r=fRr.init(this.apiDefinitionId);return{id:r.get(),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,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:new Fan(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,r).convert({parentSlug:this.#c}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#m(this.apiSection.playground)}}#s(t,r,n,i){r=this.#e.resolveSubpackage(r);let a=r!=null?lRr.getSubpackageId(r):void 0;return t.map(u=>Zxa(u)._visit({link:f=>({id:i.append(`link:${f.url}`).get(),type:"link",title:f.text,icon:f.icon,url:Zc.Url(f.url)}),page:f=>{let d=Zc.V1.PageId(this.toRelativeFilepath(f.absolutePath)),c=n.apply({fullSlug:this.markdownFilesToFullSlugs.get(f.absolutePath)?.split("/"),urlSlug:f.slug??OF(f.title)});return{id:i.append(`page:${d}`).get(),type:"page",pageId:d,title:f.title,slug:c.get(),icon:f.icon,hidden:f.hidden,noindex:f.noindex}},package:f=>this.#u(f,n,i),section:f=>this.#p(f,n,i),item:({value:f})=>this.#v(f,a,n,i),endpoint:f=>this.#_(f,a,n,i)})).filter($M)}#u(t,r,n){let i=t.overviewAbsolutePath!=null?Zc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,u=this.#e.getSubpackageByIdOrLocator(t.package);if(u!=null){let f=lRr.getSubpackageId(u),d=n.append(f);this.#r.has(f)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${f}`),this.#r.add(f),this.#a.set(d.get(),[f]);let c=t.slug??(sLt(u)?u.urlSlug:this.apiSection.slug??OF(this.apiSection.title)),o=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),l=this.#s(t.contents,u,o,d);return{id:d.get(),type:"apiPackage",children:l,title:t.title??(sLt(u)?u.displayName??wan(u.name):this.apiSection.title),slug:o.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#m(t.playground)}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let f=t.slug??OF(t.package),d=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#s(t.contents,void 0,d,n);return{id:n.append(OF(t.package)).get(),type:"apiPackage",children:c,title:t.title??t.package,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#m(t.playground)}}}#p(t,r,n){let i=t.overviewAbsolutePath!=null?Zc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,u=n.append(`section:${OF(t.title)}`),f=t.referencedSubpackages.map(l=>{let g=this.#e.getSubpackageByIdOrLocator(l);return g!=null?lRr.getSubpackageId(g):void 0}).filter(l=>(l==null&&this.taskContext.logger.error(`Subpackage ${l} not found in ${this.apiDefinitionId}`),l!=null)).filter($M);this.#a.set(u.get(),f),f.forEach(l=>{this.#r.has(l)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${l}`),this.#r.add(l)});let d=t.slug??OF(t.title),c=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,c,n);return{id:u.get(),type:"apiPackage",children:o,title:t.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.#m(t.playground)}}#v(t,r,n,i){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t);if(a!=null){let u=lRr.getSubpackageId(a),f=i.append(u);this.#r.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#r.add(u),this.#a.set(f.get(),[u]);let d=sLt(a)?a.urlSlug:"",c=n.apply({urlSlug:d});return{id:f.get(),type:"apiPackage",children:[],title:sLt(a)?a.displayName??wan(a.name):this.apiSection.title,slug:c.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}}return this.#_({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0},r,n,i)}#_(t,r,n,i){let a=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.endpoints.get(KF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let d=this.#e.getEndpointId(a);if(d==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);this.#t.has(d)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${d}`),this.#t.add(d);let c=t.slug!=null?n.append(t.slug):n.apply(a);return{id:i.append(a.id).get(),type:"endpoint",method:a.method,endpointId:d,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(a.availability),isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??WDe(a.path.parts),slug:c.get(),icon:t.icon,hidden:t.hidden,playground:this.#m(t.playground)}}let u=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webSockets.get(KF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(u!=null){let d=this.#e.getWebSocketId(u);if(d==null)throw new Error(`Expected WebSocket ID for ${u.id}. Got undefined.`);return this.#n.has(d)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${d}`),this.#n.add(d),{id:i.append(u.id).get(),type:"webSocket",webSocketId:d,title:t.title??u.name??WDe(u.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(u.availability),playground:this.#m(t.playground)}}let f=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webhooks.get(KF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Zc.V1.WebhookId(t.endpoint));if(f!=null){let d=this.#e.getWebhookId(f);if(d==null)throw new Error(`Expected Webhook ID for ${f.id}. Got undefined.`);return this.#i.has(d)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${d}`),this.#i.add(d),{id:i.append(f.id).get(),type:"webhook",webhookId:d,method:f.method,title:t.title??f.name??k1("/",...f.path),slug:(t.slug!=null?n.append(t.slug):n.apply(f)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#d(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#O(t){if(t.type==="apiPackage"){let r=Zc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#b(f,r)),a=t.children.map(f=>this.#O(f)),u=this.#d(a,i);return{...t,children:u,pointsTo:Zc.V1.followRedirects(u)}}return t}#y(t,r){let n=[];return t.endpoints.forEach(i=>{let a=this.#e.getEndpointId(i);if(a==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(i);n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??WDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0})}),t.websockets.forEach(i=>{let a=this.#e.getWebSocketId(i);if(a==null)throw new Error(`Expected WebSocket ID for ${i.id}. Got undefined.`);this.#n.has(a)||n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??WDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(i.availability),playground:void 0})}),t.webhooks.forEach(i=>{let a=this.#e.getWebhookId(i);if(a==null)throw new Error(`Expected Webhook ID for ${i.id}. Got undefined.`);this.#i.has(a)||n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??wan(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0})}),t.subpackages.forEach(i=>{if(this.#r.has(i))return;let a=this.#e.getSubpackageByIdOrLocator(i);if(a==null){this.taskContext.logger.error(`Subpackage ${i} not found in ${this.apiDefinitionId}`);return}let u=sLt(a)?r.apply(a):r,f=this.#b(i,u);f.length>0&&n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:sLt(a)?a.displayName??wan(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:Zc.V1.followRedirects(f),noindex:void 0,playground:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((i,a)=>{let u=i.type==="endpointPair"?i.nonStream.title:i.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),n}#b(t,r){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#y(n,r)}#m(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Zc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Zc.V1.Url(t.button.href)}:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],n=new Map;return t.forEach(i=>{if(i.type!=="endpoint"){r.push(i);return}let a=this.#e.endpoints.get(i.endpointId);if(a==null)throw new Error(`Endpoint ${i.endpointId} not found`);let u=`${a.method} ${WDe(a.path.parts)}`,f=n.get(u);if(n.set(u,i),f==null||f.isResponseStream===i.isResponseStream){r.push(i);return}let d=r.indexOf(f),c=i.isResponseStream?i:f,o=i.isResponseStream?f:i,l={id:Zc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Pnd(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 WTa=Xo(O6t(),1);var DD=Xo(O6t(),1);var dRr=Xo(O6t(),1);function wnd(e){return e._visit({alias:t=>({type:"alias",value:Ex(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:J5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dRr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dRr.FernRegistry.PropertyKey(r.name.wireValue),valueType:Ex(r.valueType),availability:J5(r.availability)})),extraProperties:rIw(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:dRr.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:J5(n.availability),description:n.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?J5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[dRr.FernRegistry.TypeId(i.typeId)],properties:r}),singleProperty:i=>({extends:[],properties:[{key:dRr.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.type),description:void 0,availability:void 0},...r]}),noProperties:()=>({extends:[],properties:r}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.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:Ex(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function Ex(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:Ex(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:Ex(r),valueType:Ex(n)}),optional:r=>({type:"optional",itemType:Ex(r),defaultValue:void 0}),set:r=>({type:"set",itemType:Ex(r)}),literal:r=>lp.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:dRr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>eIw(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>tIw(t.v2),string:()=>k6w(t.v2),long:()=>({type:"long",default:0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:!1}),dateTime:()=>({type:"datetime",default:new Date(0).toISOString()}),date:()=>({type:"date",default:new Date(0).toISOString()}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",default:"0"}),bigInteger:()=>({type:"bigInteger",default:BigInt(0).toString()}),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 k6w(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.minLength,default:e!=null&&e.type==="string"?e.default:void 0}}function eIw(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 tIw(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 rIw(e){return typeof e=="boolean"?uT.unknown():typeof e=="string"?{type:"id",value:dRr.FernRegistry.TypeId(e),default:void 0}:Ex(e)}function Wqu(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?iIw(r,t):[],webhooks:n!=null?nIw(n):[],websockets:i!=null?[aIw(i,t)]:[],types:e.types.map(a=>DD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>DD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?DD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function nIw(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Rdi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:J5(r.availability)})),payload:pIw(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function iIw(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.userSpecifiedExamples.length>0&&i!=null)a.push(...n.userSpecifiedExamples.map(f=>Vqu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(Vqu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=CPi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...Vqu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:J5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:cIw(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?oIw({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Rdi(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...xzn(n.basePath),...xzn(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...t.basePath!=null?xzn(t.basePath):[],...xzn(e.basePath),...xzn(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:J5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:J5(f.availability)})),request:n.requestBody!=null?lIw(n.requestBody):void 0,response:n.response!=null?fIw(n.response):void 0,errors:void 0,errorsV2:dIw(n.errors,t),examples:a};r.push(u)}return r}function aIw(e,t){return{auth:e.auth,availability:J5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?uIw({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Rdi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:Ex(r.valueType),availability:void 0})),parts:xzn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:Ex(r.valueType),description:r.docs,availability:J5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:J5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:_Iw(r.body),description:r.docs,availability:J5(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((n,i)=>(n[DD.FernRegistry.PropertyKey(i.name.originalName)]=i.value.jsonExample,n),{}),queryParameters:r.queryParameters.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),headers:r.headers.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),messages:r.messages.map(n=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}))}}function J5(e){if(e!=null)switch(e.status){case"DEPRECATED":return DD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return DD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return DD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return DD.FernRegistry.Availability.Beta;default:xc(e.status)}}function oIw({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:i.url}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Expected environment ${i.id} to contain url for ${n}`);return{id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:xc(r)}}function uIw({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:DD.FernRegistry.EnvironmentId(n.id),baseUrl:sIw(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:xc(r)}}function sIw(e,t){return e.replace(/^[^:]+/,t)}function cIw(e){return lp.http.HttpMethod._visit(e,{get:()=>DD.FernRegistry.HttpMethod.Get,post:()=>DD.FernRegistry.HttpMethod.Post,put:()=>DD.FernRegistry.HttpMethod.Put,patch:()=>DD.FernRegistry.HttpMethod.Patch,delete:()=>DD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function xzn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:DD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function lIw(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>DD.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:DD.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:J5(n.availability)}))},description:r.docs??void 0}),reference:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"reference",value:Ex(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(n=>n._visit({file:i=>{let a=i._visit({file:u=>({type:"file",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:DD.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:i=>({type:"bodyProperty",key:DD.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.valueType),contentType:i.contentType,description:i.docs,availability:J5(i.availability)}),_other:()=>{}})).filter($M)},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 fIw(e){if(e.body==null)return;let t,r=lp.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:Ex(n.responseBodyType)}),text:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function dIw(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:Ex(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.name.name.originalName,availability:void 0,examples:i.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0}];i.type!=null&&a.push({key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:Ex(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.name.name.originalName,examples:i.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Vqu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(f=>{let d=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(d!=null)return{name:f.name,value:{jsonExample:d,shape:lp.ExampleTypeReferenceShape.primitive(lp.ExamplePrimitive.string({original:d}))}}}).filter($M),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,d)=>(f[DD.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((f,d)=>(f[d.name.wireValue]=d.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 d={};if(lS(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let g=c[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof g=="string"?g:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(g)?g:[g]).filter(P=>typeof P=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:$qt})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:lp.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let d=n.errors[f.errorId];if(d==null)throw new Error("Cannot find error "+f.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(c=>c.jsonExample)}),sse:d=>({type:"sse",value:d.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=>oDe._visit(f,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter($M)}}function pIw(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:J5(t.availability)}))},description:void 0};case"reference":return{type:{type:"reference",value:Ex(e.payloadType)},description:e.docs};default:xc(e)}}function _Iw(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:J5(t.availability)}))};case"reference":return{type:"reference",value:Ex(e.bodyType)};default:xc(e)}}var Hqu=Xo(O6t(),1);function jnd(e,t,r){let n=e.schemes[0];if(e.schemes.length===1&&n!=null)switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix};case"oauth":{let i=n.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:Hqu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Hqu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:xc(n)}}function HDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:Wqu(e.rootPackage,e),auth:jnd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:J5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:Ex(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[WTa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:wnd(a.shape),availability:J5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[WTa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:WTa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Wqu(a,e)}}return n}var Qqu=Xo(O6t(),1);async function Jqu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await iQ({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r}),d=Ttn({token:n.value}),c=HDe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await d.api.v1.register.registerApiDefinition({orgId:Qqu.FernRegistry.OrgId(e),apiId:Qqu.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 hIw=new San({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Dnd(e,t,r){return uPi(iPi(HDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),KF.ApiDefinitionId(t),hIw))}function Snd(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 _Mr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}And.default.extend(Mnd.default);var yIw=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),End=0,vIw=async({ir:e})=>(End++,`${e.apiName.snakeCase.unsafeName}-${End}`),hMr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=yIw,f=vIw){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}_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 gTe.parseDocsConfiguration({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(d=>{d.changelog?.files.forEach(c=>{let o=jq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await VTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await WTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=Snd(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=kOi(c,{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ms.of(d)]=l;for(let g of o)t.add(g)}let r=Array.from(t).map(d=>({absoluteFilePath:d,relativeFilePath:this.toRelativeFilepath(d)}));(await this.uploadFiles(r)).forEach(d=>{this.collectedFileIds.set(d.absoluteFilePath,d.fileId)});let i=this.getDocsBasePath();for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=UTu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,k1(i,l)])),{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([d,c])=>{let o=bIw(this.editThisPage,d);a[Ak.PageId(d)]={markdown:c,editThisPageUrl:o?Ak.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let d=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=rT(this.docsWorkspace.absoluteFilePath,c);(await(0,HTa.stat)(o)).isDirectory()?(await tTe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{d.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&d.add(o)})),f=Object.fromEntries(await Promise.all([...d].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,HTa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return rT(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,xnd.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(_Mr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.convertNavigationConfig();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?Ak.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:Ak.Url(n.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(n=>({...n,value:Ak.Url(n.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,playground: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(n=>n.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async convertNavigationConfig(){let t=Zc.V1.SlugGenerator.init(Zc.slugjoin(this.getDocsBasePath()));switch(this.parsedDocsConfig.navigation.type){case"versioned":return{versions:await Promise.all(this.parsedDocsConfig.navigation.versions.map(async n=>{let i=t.setVersionSlug(n.slug??OF(n.version)),a=await this.convertUnversionedNavigationConfig({landingPage:n.landingPage,navigationConfig:n.navigation,parentSlug:i});return{version:Zc.VersionId(n.version),config:a,availability:n.availability!=null?gIw(n.availability):void 0,urlSlugOverride:n.slug}}))};case"untabbed":case"tabbed":return this.convertUnversionedNavigationConfig({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:this.parsedDocsConfig.navigation,parentSlug:t});default:xc(this.parsedDocsConfig.navigation)}}async convertNavigationItem(t,r){switch(t.type){case"page":return{type:"page",title:t.title,icon:t.icon,id:Zc.PageId(this.toRelativeFilepath(t.absolutePath)),urlSlugOverride:t.slug,fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),hidden:t.hidden};case"section":{let n=r.apply({fullSlug:void 0,skipUrlSlug:t.skipUrlSlug,urlSlug:t.slug??OF(t.title)}),i=await Promise.all(t.contents.map(u=>this.convertNavigationItem(u,n))),a=this.toRelativeFilepath(t.overviewAbsolutePath);return{type:"section",title:t.title,items:i,urlSlugOverride:t.slug,collapsed:t.collapsed,icon:t.icon,hidden:t.hidden,skipUrlSlug:t.skipUrlSlug,overviewPageId:a?Zc.PageId(a):void 0,fullSlug:void 0}}case"apiSection":{let n=this.getFernWorkspaceForApiSection(t),i=Pnd(t.snippetsConfiguration),a=await iQ({workspace:n,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}),u=await this.registerApi({ir:a,snippetsConfig:i,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=Dnd(a,u,{oauth:t.playground?.oauth});return{type:"apiV2",node:new VTa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs).get()}}case"link":return{type:"link",icon:t.icon,title:t.text,url:ePi.Url(t.url)};case"changelog":{let n=t.slug??OF(t.title),i=fRr.init(r.get()).append(n),a=new Fan(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,i).convert({parentSlug:r,title:t.title,hidden:t.hidden,slug:t.slug,icon:t.icon}),u=this.toRelativeFilepath(t.changelog[0]);return{type:"changelogV3",node:a??{id:i.append("changelog").get(),type:"changelog",title:t.title,slug:r.append(n).get(),children:[],icon:t.icon,hidden:t.hidden,overviewPageId:u?Zc.PageId(u):void 0,noindex:!1}}}default:xc(t)}}async convertUnversionedNavigationConfig({landingPage:t,navigationConfig:r,parentSlug:n}){let i=t!=null?{id:Zc.PageId(this.toRelativeFilepath(t.absolutePath)),urlSlugOverride:t.slug,fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),hidden:t.hidden,title:t.title,icon:t.icon}:void 0;switch(r.type){case"untabbed":{let a=await Promise.all(r.items.map(u=>this.convertNavigationItem(u,n)));return{landingPage:i,items:a}}case"tabbed":return{landingPage:i,tabs:void 0,tabsV2:await this.convertTabbedNavigation(r.items,n)};default:xc(r)}}async convertTabbedNavigation(t,r){return Promise.all(t.map(async n=>{if(n.child.type==="link")return{type:"link",title:n.title,icon:n.icon,url:ePi.Url(n.child.href)};if(n.child.type==="changelog"){let i=fRr.init(r.get()),a=new Fan(this.markdownFilesToFullSlugs,n.child.changelog,this.docsWorkspace,i).convert({parentSlug:r,title:n.title,icon:n.icon,hidden:n.hidden,slug:n.slug}),u=this.toRelativeFilepath(n.child.changelog[0]);return{type:"changelogV3",node:a??{id:i.append("changelog").get(),type:"changelog",title:n.title,slug:r.append(n.slug??OF(n.title)).get(),children:[],icon:n.icon,hidden:n.hidden,overviewPageId:u?Zc.PageId(u):void 0,noindex:!1}}}if(n.child.type==="layout"){let i=r.apply({skipUrlSlug:n.skipUrlSlug,urlSlug:n.slug??OF(n.title)}),a=await Promise.all(n.child.layout.map(u=>this.convertNavigationItem(u,i)));return{type:"group",title:n.title,icon:n.icon,items:a,urlSlugOverride:n.slug,skipUrlSlug:n.skipUrlSlug,hidden:n.hidden,fullSlug:void 0}}xc(n.child)}))}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):Ak.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:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),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 n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.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($M),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:Ak.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return hKo(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:Ak.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function bIw(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${_Mr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function gIw(e){switch(e){case"beta":return Ak.Availability.Beta;case"deprecated":return Ak.Availability.Deprecated;case"ga":return Ak.Availability.GenerallyAvailable;case"stable":return Ak.Availability.Stable;default:xc(e)}}var B0d=Xo(Nnd(),1),y3u=Xo(H6u(),1),N0d=Xo(require("http"),1),Kqa=Xo(require("path"),1);var usd=require("events"),DCa=Xo(require("fs"),1),$an=Xo(require("path"),1);var Wud=Xo(require("os"),1),Hud=300,bRr=20,e1i=1e7,Qud=Wud.default.platform();var r5w=Qud==="darwin",Q6u=Qud==="win32",gRr=r5w||Q6u,Jud=3e3,Gud=2e4,J6u=1250;var dLt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(dLt||(dLt={}));var Gan;(function(e){e.CHANGE="change",e.RENAME="rename"})(Gan||(Gan={}));var t1i;(function(e){e.CHANGE="change",e.ERROR="error"})(t1i||(t1i={}));var Lm;(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"})(Lm||(Lm={}));var Tk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Tk||(Tk={}));var n5w=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,d=0,c=0,o=()=>{let C=Date.now(),F=C-d,K=C-c,ee=F>=t||K>=a;return[C,ee]},l=C=>{if(c=C,!u)return;let F=u;u=void 0,e.apply(void 0,F)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},P=C=>{if(c=C,n)return l(C)},j=C=>{if(i&&u)return l(C);u=void 0},M=()=>{f=void 0;let[C,F]=o();return F?j(C):q(C)},q=C=>{let F=C-d,K=C-c,ee=t-F,J=a-K,G=Math.min(ee,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[F,K]=o(),ee=!!f;if(u=C,d=F,(K||!f)&&B(t),K)return ee?l(F):P(F)};return I.cancel=g,I.flush=O,I},OCa=n5w;var X6u=Xo(require("fs"),1),wCa=Xo(require("path"),1);var Ax=Xo(require("fs"),1),aQ=require("util");var yMr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},pLt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var G6u=Xo(require("process"),1),$ud=G6u.default.getuid?!G6u.default.getuid():!1,Kud=1e4,Mae=()=>{};var r1i={isChangeErrorOk:e=>{if(!r1i.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!$ud&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!r1i.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(!r1i.isNodeError(e))throw e;if(!r1i.isChangeErrorOk(e))throw e}},K8=r1i;var $6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Kud,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(n),n=()=>t(r);this.add(n)}),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()}}}}},Yud=new $6u;var vMr=(e,t)=>function(n){return function i(...a){return Yud.schedule().then(u=>{let f=c=>(u(),c),d=c=>{if(u(),Date.now()>=n)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(g=>setTimeout(g,o)).then(()=>i.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,d)})}},bMr=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>n)throw u;if(t(u))return i.apply(void 0,a);throw u}}};var i5w={attempt:{chmod:yMr((0,aQ.promisify)(Ax.default.chmod),K8.onChangeError),chown:yMr((0,aQ.promisify)(Ax.default.chown),K8.onChangeError),close:yMr((0,aQ.promisify)(Ax.default.close),Mae),fsync:yMr((0,aQ.promisify)(Ax.default.fsync),Mae),mkdir:yMr((0,aQ.promisify)(Ax.default.mkdir),Mae),realpath:yMr((0,aQ.promisify)(Ax.default.realpath),Mae),stat:yMr((0,aQ.promisify)(Ax.default.stat),Mae),unlink:yMr((0,aQ.promisify)(Ax.default.unlink),Mae),chmodSync:pLt(Ax.default.chmodSync,K8.onChangeError),chownSync:pLt(Ax.default.chownSync,K8.onChangeError),closeSync:pLt(Ax.default.closeSync,Mae),existsSync:pLt(Ax.default.existsSync,Mae),fsyncSync:pLt(Ax.default.fsync,Mae),mkdirSync:pLt(Ax.default.mkdirSync,Mae),realpathSync:pLt(Ax.default.realpathSync,Mae),statSync:pLt(Ax.default.statSync,Mae),unlinkSync:pLt(Ax.default.unlinkSync,Mae)},retry:{close:vMr((0,aQ.promisify)(Ax.default.close),K8.isRetriableError),fsync:vMr((0,aQ.promisify)(Ax.default.fsync),K8.isRetriableError),open:vMr((0,aQ.promisify)(Ax.default.open),K8.isRetriableError),readFile:vMr((0,aQ.promisify)(Ax.default.readFile),K8.isRetriableError),rename:vMr((0,aQ.promisify)(Ax.default.rename),K8.isRetriableError),stat:vMr((0,aQ.promisify)(Ax.default.stat),K8.isRetriableError),write:vMr((0,aQ.promisify)(Ax.default.write),K8.isRetriableError),writeFile:vMr((0,aQ.promisify)(Ax.default.writeFile),K8.isRetriableError),closeSync:bMr(Ax.default.closeSync,K8.isRetriableError),fsyncSync:bMr(Ax.default.fsyncSync,K8.isRetriableError),openSync:bMr(Ax.default.openSync,K8.isRetriableError),readFileSync:bMr(Ax.default.readFileSync,K8.isRetriableError),renameSync:bMr(Ax.default.renameSync,K8.isRetriableError),statSync:bMr(Ax.default.statSync,K8.isRetriableError),writeSync:bMr(Ax.default.writeSync,K8.isRetriableError),writeFileSync:bMr(Ax.default.writeFileSync,K8.isRetriableError)}},Xud=i5w;var PCa=Xo(require("fs"),1),n1i=Xo(require("path"),1);var Zud={then:e=>{e()}};var K6u=()=>{};var Y6u=()=>{let e=K6u,t=K6u,r=!1,n=!1;return{promise:new Promise((d,c)=>{e=o=>(r=!0,d(o)),t=o=>(n=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}};Y6u.wrap=async e=>{let t=Y6u();return await e(t),t.promise};var kud=Y6u;var esd=e=>Array.isArray(e)?e:[e],tsd=e=>typeof e=="function",rsd=()=>{let{promise:e,resolve:t}=kud(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var a5w=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=esd(a).map(It=>tsd(It)?It:cr=>It.test(cr)),f=It=>u.some(cr=>cr(It)),d=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,g={},O=[],P=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,F={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},K={directories:o,directoriesNames:l,directoriesNamesToPaths:g,files:O,filesNames:P,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:ee,increment:J,decrement:G}=rsd(),te=0,Ye=(It,cr,fn,Gt)=>{C.has(cr)||te>=i||(te+=1,It.directories.push(cr),It.directoriesNames.add(fn),o.push(cr),l.add(fn),g.propertyIsEnumerable(fn)||(g[fn]=[]),g[fn].push(cr),C.add(cr),!(Gt>=n)&&(te>=i||or(cr,Gt+1)))},Re=(It,cr,fn)=>{C.has(cr)||te>=i||(te+=1,It.files.push(cr),It.filesNames.add(fn),O.push(cr),P.add(fn),j.propertyIsEnumerable(fn)||(j[fn]=[]),j[fn].push(cr),C.add(cr))},wt=(It,cr,fn,Gt)=>{C.has(cr)||te>=i||(te+=1,It.symlinks.push(cr),It.symlinksNames.add(fn),M.push(cr),q.add(fn),B.propertyIsEnumerable(fn)||(B[fn]=[]),B[fn].push(cr),C.add(cr),r&&(Gt>=n||te>=i||jr(cr,Gt+1)))},Ct=(It,cr,fn,Gt,ln)=>{d.aborted||f(cr)||(Gt.isDirectory()?Ye(It,cr,fn,ln):Gt.isFile()?Re(It,cr,fn):Gt.isSymbolicLink()&&wt(It,cr,fn,ln))},Wt=(It,cr,fn,Gt)=>{if(d.aborted)return;let ln=cr===n1i.default.sep?"":n1i.default.sep,En=fn.name,Ht=`${cr}${ln}${En}`;f(Ht)||(fn.isDirectory()?Ye(It,Ht,En,Gt):fn.isFile()?Re(It,Ht,En):fn.isSymbolicLink()&&wt(It,Ht,En,Gt))},Bt=(It,cr,fn,Gt)=>{for(let ln=0,En=fn.length;ln<En;ln++)Wt(It,cr,fn[ln],Gt)},or=(It,cr)=>{d.aborted||cr>n||te>=i||(J(),PCa.default.readdir(It,{withFileTypes:!0},(fn,Gt)=>{if(fn||d.aborted||!Gt.length)return G();(c(Gt)||Zud).then(()=>{let En=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(En,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),PCa.default.realpath(It,(fn,Gt)=>{if(fn||d.aborted)return G();PCa.default.stat(Gt,async(ln,En)=>{if(ln||d.aborted)return G();let Ht=n1i.default.basename(Gt),tr=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(tr,Gt,Ht,En,cr),G()})})};return(async(It,cr=1)=>(It=n1i.default.normalize(It),C.add(It),or(It,cr),await ee,d.aborted?F:K))(e)},nsd=a5w;var _Lt={lang:{debounce:OCa,attempt:e=>{try{return e()}catch(t){return _Lt.lang.castError(t)}},castArray:e=>_Lt.lang.isArray(e)?e:[e],castError:e=>_Lt.lang.isError(e)?e:_Lt.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(_Lt.lang.isNaN(e))return _Lt.lang.isNaN(t);if(_Lt.lang.isPrimitive(e)||_Lt.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(wCa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?X6u.default.realpathSync.native(e):X6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===wCa.default.sep&&t.length-e.length>wCa.default.sep.length,poll:(e,t=Gud)=>Xud.retry.stat(t)(e,{bigint:!0}).catch(_Lt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await nsd(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=_Lt;var jCa=Xo(require("path"),1);var Z6u=class{constructor(t,r,n){this.base=n,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||yw.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Hud){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,a=async(f,d)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=yw.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(f,d="",c=!1)=>{c?await this.eventsPopulate([d],n,!0):i.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,u]=i,f=r[u];return a===f||a===Lm.CHANGE&&f===Lm.ADD||(r[u]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,i]),u===Lm.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):u===Lm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),u=this.options.limit??e1i,[f,d]=await yw.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...d];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())yw.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Lm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!gRr&&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(Lm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Lm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(jCa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Lm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(jCa.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(Lm.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Lm.ADD?this.onTargetAdd(n):r===Lm.ADD_DIR?this.onTargetAddDir(n):r===Lm.CHANGE?this.onTargetChange(n):r===Lm.UNLINK?this.onTargetUnlink(n):r===Lm.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=Gan.CHANGE,r){if(this.watcher.isClosed())return;let n=jCa.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){Q6u&&t.code==="EPERM"?this.onWatcherChange(Gan.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(t1i.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(t1i.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Gan.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&gRr&&this.options.native!==!1?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),n=this.options.limit??e1i,[i,a]=await yw.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...i,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(Gan.CHANGE,f,t)}))}}},isd=Z6u;var Ck={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ck.intervalId||(Ck.intervalId=setInterval(Ck.resolve,Ck.interval))},reset:()=>{Ck.intervalId&&(clearInterval(Ck.intervalId),delete Ck.intervalId)},add:(e,t)=>{Ck.fns.set(e,Date.now()+t),Ck.init()},remove:e=>{Ck.fns.delete(e)},resolve:()=>{if(!Ck.fns.size)return Ck.reset();let e=Date.now();for(let[t,r]of Ck.fns)r>=e||(Ck.remove(t),t())}},i1i=Ck;var a1i=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=J6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(n||-1,g=>g!==i);if(l&&l!==i){if(yw.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return f();let d=()=>{u.add.delete(n),i1i.remove(c)},c=()=>{d(),f()};i1i.add(c,r);let o=()=>{let l=u.unlink.get(n);if(!l)return;d();let g=l();i===g?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,g,i)};u.add.set(n,o),o()}getLockUnlink(t,r=J6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,i)};if(!n)return f();let d=()=>{u.unlink.delete(n),i1i.remove(c)},c=()=>{d(),f()};i1i.add(c,r);let o=()=>(d(),i);u.unlink.set(n,o),u.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD,dLt.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD_DIR,dLt.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Lm.UNLINK,dLt.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Lm.UNLINK_DIR,dLt.DIR);return this.getLockUnlink({ino:n,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}}};a1i.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};a1i.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var asd=a1i;var k6u=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yw.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(yw.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(yw.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(yw.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return yw.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);yw.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},eIu=k6u;var tIu=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}},osd=tIu;var rIu=class{constructor(){this.inos={},this.paths=new eIu,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await yw.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new osd(n)}reset(){this.inos={},this.paths=new eIu,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Lm.ADD,i),[Lm.ADD];if(i.isDirectory())return this.updateIno(t,Lm.ADD_DIR,i),[Lm.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Lm.UNLINK,n),[Lm.UNLINK];if(n.isDirectory())return this.updateIno(t,Lm.UNLINK_DIR,n),[Lm.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Lm.CHANGE,i),[Lm.CHANGE]);if(i.isDirectory())return this.updateIno(t,Lm.UNLINK,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK,Lm.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD,i),[Lm.UNLINK_DIR,Lm.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK_DIR,Lm.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?dLt.FILE:dLt.DIR;i[t]=[n.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},nIu=rIu;var iIu=class e extends usd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Tk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(Tk.CLOSE,i)),this._readyWait=new Promise(i=>this.on(Tk.READY,i)),this._locker=new asd(this),this._roots=new Set,this._poller=new nIu,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(yw.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(Tk.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(Tk.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(Tk.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Tk.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)yw.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let i in this._watchers)this.watchersClose(i,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,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let a=new isd(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 n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yw.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(f=>f.handler===n&&(!f.filePath||f.filePath===i)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=$an.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??bRr))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&gRr&&o.options.native!==!1)))return!0;if(!gRr)break;let c=$an.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=yw.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,n,i))try{let d=!r.recursive||gRr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:DCa.default.watch(f,d),handler:n,options:r,folderPath:f,filePath:i},l=u=await this.watcherAdd(o,a);if(this._roots.has(i||f)){let O={...r,ignoreInitial:!0,recursive:!1},P=$an.default.dirname(f),j=f;await this.watchDirectories([P],O,n,j,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||gRr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??bRr,f=r.limit??e1i,[d]=await yw.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,a);if(d.length){let o=yw.fs.getDepth(t);for(let l of d){let g=yw.fs.getDepth(l),O=Math.max(0,u-(g-o)),P={...r,depth:O};await this.watchDirectories([l],P,n,i,a||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(c,o)=>{o===t&&(d(),n())},u=new e(a),f=()=>{this._subwatchers.add(i),this.on(Tk.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(Tk.CLOSE,d),u.close()};return f()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=$an.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new nIu,u=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,u(),n())})}async watchPolling(t,r,n){if(this.isClosed())return yw.lang.noop;if(this.pollerExists(t,r))return yw.lang.noop;let i={...r,interval:r.pollingInterval??Jud},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(Tk.CLOSE,f),DCa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(Tk.CLOSE,f),DCa.default.unwatchFile(t,n)};return yw.lang.attempt(u),()=>yw.lang.attempt(f)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=yw.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,d)=>d===u||!yw.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=$an.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await yw.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let a=$an.default.dirname(t);return(await yw.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=yw.lang.noop){if(yw.lang.isFunction(t))return this.watch([],{},t);if(yw.lang.isUndefined(t))return this.watch([],r,n);if(yw.lang.isFunction(r))return this.watch(t,{},r);if(yw.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=yw.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==yw.lang.noop&&this.on(Tk.ALL,n),r.readdirMap=void 0,this.ready())}},ssd=iIu;var hRw=Xo(dsd(),1),yRw=Xo(hIu(),1),vRw=Xo(vIu(),1),bRw=Xo(jIu(),1),SIu=Xo(ccd(),1);var x0d=Xo(O2a(),1),TLt=require("fs/promises"),Gqa=require("os"),f3u=Xo(require("path"),1),T0d=Xo(zne(),1),C0d=Xo(Bpd(),1),d3u=Xo(l3u(),1),lGw="etag",p3u="preview",fGw="bundle",_3u=".fern";function dGw(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u))}function $qa(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u),Ms.of(fGw))}function pGw(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u),Ms.of(lGw))}async function q0d({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let n=await(0,d3u.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let i=n.body,u=await new C0d.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=pGw();if(r){let B=await Wh(c),I;if(B&&(t.debug("Reading existing ETag"),I=(await(0,TLt.readFile)(c)).toString()),I!=null&&I===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 T0d.default.dir({prefix:"fern"}),l=y_.of(o.path);t.debug(`Downloading docs preview bundle from ${f3u.default.join(e,d)}`);let g=await(0,d3u.fetcher)({url:`${f3u.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=yf(l,Ms.of("output.zip")),P=g.body;if(P==null)return{type:"failure"};let j=Buffer.from(P);await(0,TLt.writeFile)(O,j),t.debug(`Wrote output.zip to ${O}`);let M=dGw();await Wh(M)&&await(0,TLt.rm)(M,{recursive:!0}),await(0,TLt.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let q=$qa();return await(0,TLt.mkdir)(q,{recursive:!0}),await(0,x0d.default)(O,q),await(0,TLt.writeFile)(c,f),t.debug(`Downloaded bundle to ${q}`),{type:"success"}}async function I0d({domain:e,project:t,context:r}){let n=t.docsWorkspaces,i=t.apiWorkspaces;if(n==null)throw new Error("No docs workspace found in project");let a=await Promise.all(i.map(async g=>await g.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),u=new h3u(r),f={},c=await new hMr(e,n,a,r,void 0,async g=>g.map(O=>{let P=izr();return f[P]={type:"url",url:Zc.Url(`/_local${OXo(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:P}}),async g=>u.addReferencedAPI(g)).resolve(),o=U2u({writeShape:c,files:{}}),l=W2u({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 h3u=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=izr(),a=iPi(HDe({ir:t,snippetsConfig:r,playgroundConfig:n}),MU.ApiDefinitionId(i),new San({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=uPi(a);return this.apis[i]=u,i}catch(i){let a=i;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),i}}getAPIsForDefinition(){return this.apis}};var _Gw={pages:{},apis:{},files:{},filesV2:{},config:{navigation:{landingPage:void 0,items:[]},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,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function v3u({initialProject:e,reloadProject:t,validateProject:r,context:n,port:i,bundlePath:a}){if(a!=null)n.logger.info(`Using bundle from path: ${a}`);else try{let I="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(I==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await q0d({bucketUrl:I,logger:n.logger,preferCached:!0})}catch(I){let C=$qa();if(I instanceof Error&&n.logger.debug(`Failed to download latest docs bundle: ${I.message}`),await Wh(C))n.logger.warn("Falling back to cached bundle...");else{n.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,y3u.default)(),d=N0d.default.createServer(f),c=new SIu.default({server:d}),o=new Set;function l(I){for(let C of o)C.send(JSON.stringify(I))}c.on("connection",function(C){o.add(C),C.on("close",function(){o.delete(C)})}),f.use((0,B0d.default)());let g=new URL(_Mr(e.docsWorkspaces?.config.instances[0]?.url??`localhost:${i}`)),O=e,P,j=async()=>{n.logger.info("Reloading docs...");let I=Date.now();try{O=await t(),n.logger.info("Validating docs..."),await r(O);let C=await I0d({domain:`${g.host}${g.pathname}`,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return P==null?n.logger.error("Failed to read docs configuration. Rendering blank page."):n.logger.error("Failed to read docs configuration. Rendering last successful configuration."),C instanceof Error&&C instanceof Error&&C.stack&&n.logger.debug(`${C.message}
|
|
1990
|
+
`)}]:t.flatMap((c,o)=>nQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:nQ({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return UDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return UDe(d=>d===f.string,`"${f.string}"`)(t);default:xc(f)}}}})}function Uqw({primitiveType:e,example:t}){return e.v2!=null?kA._visit(e.v2,{integer:r=>Vqw({example:t,rules:r.validation}),long:()=>crd(t),uint:()=>ord(t),uint64:()=>urd(t),double:r=>Wqw({example:t,rules:r.validation}),float:()=>srd(t),boolean:()=>lrd(t),string:r=>Hqw({example:t,rules:r.validation}),uuid:()=>frd(t),date:()=>prd(t),dateTime:()=>drd(t),base64:()=>jzn(t),bigInteger:()=>jzn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>hrd(t),long:()=>crd(t),uint:()=>ord(t),uint64:()=>urd(t),double:()=>yrd(t),float:()=>srd(t),boolean:()=>lrd(t),string:()=>jzn(t),uuid:()=>frd(t),dateTime:()=>drd(t),date:()=>prd(t),base64:()=>jzn(t),bigInteger:()=>jzn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function Vqw({example:e,rules:t}){let r=hrd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function Wqw({example:e,rules:t}){let r=yrd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function Hqw({example:e,rules:t}){let r=jzn(e);if(r.length>0||t==null)return r;let n=e;return t.minLength!=null&&n.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${n.length}.`}]:t.maxLength!=null&&n.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${n.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(n)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var jzn=UDe(e=>typeof e=="string","a string"),hrd=UDe(e=>Number.isInteger(e),"an integer"),ord=UDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),urd=UDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),srd=UDe(e=>typeof e=="number","a float"),yrd=UDe(e=>typeof e=="number","a double"),crd=UDe(e=>Number.isInteger(e),"an integer"),lrd=UDe(e=>typeof e=="boolean","a boolean"),frd=UDe(e=>typeof e=="string"&&Fqw.test(e),"a UUID"),drd=UDe(e=>typeof e=="string"&&_rd.test(e),"an ISO 8601 timestamp"),prd=UDe(e=>typeof e=="string"&&Lqw.test(e)&&_rd.test(e),"a date");function UDe(e,t){return r=>e(r)?[]:L2e(r,t)}function APi({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&&APi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return APi({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&&APi({expected:e.container.keyType,actual:t.container.keyType})&&APi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:Qqw({expected:e.container.literal,actual:t.container.literal});default:xc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;xc(e)}function Qqw({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:xc(e)}}async function MTa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await X$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:Dzn(i).name,opts:{casingOverrides:typeof i!="string"?i.casing:void 0}})}))),n;if(e.default!=null&&(n=r.find(i=>i.name.wireValue===e.default),n==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:n,values:r}}function vrd(e,t){let r=t.enum.find(n=>typeof n=="string"?!1:n.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function Dzn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function xqu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return I8(t,{alias:d=>dS.alias({value:lT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>brd({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=Ban(d);if(!lS(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=d.union[o];if(l==null)throw new Error(`${o} is not one of the specified discriminant values.`);let g=typeof l=="string"?l:typeof l.type=="string"?l.type:void 0;return dS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:sRr(d).name,wireValue:c}),singleUnionType:Gqw({rawValueType:g,rawSingleUnionType:l,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,example:r,discriminant:c,discriminantValueForExample:o,workspace:f})})},enum:d=>{if(typeof r!="string")throw new Error("Enum example is not a string");return dS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:vrd(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(nQ({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return dS.undiscriminatedUnion({index:c,singleUnionType:lT({example:r,rawTypeBeingExemplified:typeof o=="string"?o:o.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})});throw new Error("Example doesn't match any of the undiscriminated unions")}})}function lT({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}){let{resolvedExample:f,file:d}=a.resolveExampleOrThrow({example:e,file:t}),c=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:Dtn({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>Jqw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!lS(f))throw new Error("Example is not an object");return dO.container(gA.map({map:Object.entries(f).map(([O,P])=>({key:lT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:lT({example:P,fileContainingExample:d,rawTypeBeingExemplified:g,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})})),keyType:n.parseTypeReference(l),valueType:n.parseTypeReference(g)}))},list:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.list({list:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},set:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.set({set:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(gA.optional({optional:f!=null?lT({example:f,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}):void 0,valueType:n.parseTypeReference(l)})),literal:l=>{switch(l.type){case"boolean":return dO.container(gA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(gA.literal({literal:Pv.string({original:l.string})}));default:xc(l)}},named:l=>{let g=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:n}),O=n.parseTypeReference(l);if(O.type!=="named")throw new Error("Type reference is not to a named type.");let P={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:P,shape:xqu({typeName:P,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function Jqw({example:e,typeBeingExemplified:t}){return vP._visit(t,{string:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.date(e))},base64:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.integer(e))},float:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.float(e))},double:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.double(e))},long:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error("Example is not a boolean");return dO.primitive(Pv.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function brd({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!lS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return dS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=grd({typeName:e,wirePropertyKey:c,rawObject:t,typeResolver:a,file:n});if(l==null)return d;let g=lT({example:o,fileContainingExample:i,rawTypeBeingExemplified:typeof l.rawPropertyType=="string"?l.rawPropertyType:l.rawPropertyType.type,fileContainingRawTypeReference:l.file,typeResolver:a,exampleResolver:u,workspace:f});return d.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function grd({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:MPi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function MPi({wirePropertyKey:e,extends_:t,typeResolver:r,file:n}){if(t!=null){let i=typeof t=="string"?[t]:t;for(let a of i){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:n});if(u._type!=="named"||!mA(u.declaration))throw new Error("Extension is not of a named object");let f=grd({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function Gqw({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:n,typeResolver:i,exampleResolver:a,example:u,discriminant:f,discriminantValueForExample:d,workspace:c}){let o=n.casingsGenerator.generateNameAndWireValue({name:wzn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:C8.noProperties()};let l=Mqu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!lS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:C8.singleProperty(lT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!lS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,P=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!mA(P.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:C8.samePropertiesAsObject({typeId:o1.generateTypeId(j),object:brd({rawObject:P.declaration,example:O,fileContainingType:P.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:xc(l)}}async function xTa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=pMr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await X$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function pMr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function $qw(e){let t=JSON.stringify(e);return mrd.default.createHash("sha256").update(t).digest("hex")}function Ord({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=Yqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??$qw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:t6w({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...Xqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,l])=>{let g=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(g==null)throw new Error(`Query parameter ${o} does not exist`);return{name:f.casingsGenerator.generateNameAndWireValue({name:pMr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:lT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:Kqw({queryParameter:g})}}):[],request:Zqw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:kqw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function Kqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function Yqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,variableResolver:a,file:u,workspace:f}){let d=[],c=[],o=[],l=({name:g,pathParameterDeclaration:O,examplePathParameter:P})=>{let j=xPi({parameter:O,variableResolver:a,file:u});return{name:g,value:lT({example:P,rawTypeBeingExemplified:j.rawType,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:j.file,fileContainingExample:u,workspace:f})}};if(r["path-parameters"]!=null)for(let[g,O]of Object.entries(r["path-parameters"])){let P=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(P!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else if(M!=null)o.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:M,examplePathParameter:O}));else if(j!=null)c.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:j,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:c}}function Xqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:u}){let f=[],d=[];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,g=e.headers?.[c];if(l!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:c,header:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(g!=null)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:c,header:g}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${c} does not exist`)}return{endpointHeaders:d,serviceHeaders:f}}function Zqw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&nyi(u)!=null)return;if(!y6(u))return v$.reference(lT({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!t.request)return;if(!lS(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let f=[];for(let[d,c]of Object.entries(t.request)){let o=u.properties?.[d],l=typeof o=="string"?o:o?.type;if(!(l!=null&&MCe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:d,property:o}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let g=MPi({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:i});if(g==null)throw new Error("Could not find original type declaration for property: "+d);f.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof g.rawPropertyType=="string"?g.rawPropertyType:g.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:g.typeName})}}return v$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function kqw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?T4.ok(cN.body(void 0)):Etn(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return T4.error({error:oRr({errorName:f.error,file:a}),body:d.declaration.type!=null?lT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return T4.ok(cN.body(e6w({endpoint:e,example:f,typeResolver:r,exampleResolver:i,file:a,workspace:u})))},stream:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.stream(f.stream.map(c=>{if(d!=null)return lT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter($M)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=lT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter($M)))}})}function e6w({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return lT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function t6w({file:e,service:t,endpoint:r,example:n,pathParams:i}){let a=k1(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(n["path-parameters"]!=null)for(let u of[...i.endpointPathParameters,...i.servicePathParameters,...i.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}async function Prd({endpoint:e,file:t,typeResolver:r}){return{body:await r6w({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function r6w({endpoint:e,file:t,typeResolver:r}){let n=await n6w({endpoint:e,file:t,typeResolver:r}),i=await i6w({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Lie.fileDownload({...n});break}case"json":{a=Lie.json({...n.value});break}case"text":{a=Lie.text({...n});break}default:xc(n)}return A3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return A3.streaming(i)}}async function n6w({endpoint:e,file:t,typeResolver:r}){let{response:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type;return MCe(a)!=null?A3.fileDownload({docs:i}):iyi(a)!=null?A3.text({docs:i}):await a6w(n,i,t,r)}}async function i6w({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type,u=typeof n=="string"?"json":n.format??"json";return Y6n(a)?Uie.text({docs:i}):typeof n!="string"&&u==="sse"?Uie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Uie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function a6w(e,t,r,n){let i=r.parseTypeReference(e),a=n.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?A3.json(N6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await DPi({typeResolver:n,file:r,resolvedType:a,property:u})})):A3.json(N6t.response({docs:t,responseBodyType:i}))}async function wrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return wCe.cursor({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.cursor}),next:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.next_cursor}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}async function jrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return wCe.offset({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.offset}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results}),step:i.step!=null?await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.step}):void 0,hasNextPage:i.hasNextPage!=null?await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.hasNextPage}):void 0})}function Drd(e){return o6w(e)?{type:"offset",offset:WIt(e.offset),results:fMr(e.results),step:e.step!=null?WIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?fMr(e["has-next-page"]):void 0}:{type:"cursor",cursor:WIt(e.cursor),next_cursor:fMr(e.next_cursor),results:fMr(e.results)}}function o6w(e){return e.offset!=null&&e.results!=null}async function Srd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=Drd(i);switch(a.type){case"cursor":return await wrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return jrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:xc(a)}}function Erd({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=oRr({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function TTa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Ard({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:TTa({source:e}),name:uRr.generateName(r)}}async function Mrd({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return mCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return mCe.http();let i=Ard({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return mCe.grpc({service:i})}async function xrd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:n,errorResolver:i,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:d,sourceResolver:c,globalErrors:o,workspace:l}){let g=await Szn({pathParameters:r["path-parameters"],location:OCe.Service,file:n,variableResolver:d}),O=await Mrd({file:n,serviceDeclaration:r,sourceResolver:c}),P={fernFilepath:n.fernFilepath};return{availability:Sae(r.availability),name:P,displayName:r["display-name"]??void 0,basePath:F2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>U2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:l6w(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await Szn({pathParameters:q["path-parameters"],location:OCe.Endpoint,file:n,variableResolver:d}),I={...await X$(q),id:"",name:n.casingsGenerator.generateName(M),displayName:q["display-name"],auth:q.auth??r.auth,idempotent:q.idempotent??r.idempotent??!1,baseUrl:q.url??r.url??e,method:q.method!=null?c6w(q.method):Rie.Post,basePath:q["base-path"]!=null?F2e(q["base-path"]):void 0,path:F2e(q.path),fullPath:F2e(q["base-path"]!=null?k1(q["base-path"],q.path):n.rootApiFile["base-path"]!=null?k1(n.rootApiFile["base-path"],r["base-path"],q.path):k1(r["base-path"],q.path)),pathParameters:B,allPathParameters:q["base-path"]!=null?B:[...t,...g,...B],queryParameters:typeof q.request!="string"&&q.request?.["query-parameters"]!=null?await Promise.all(Object.entries(q.request["query-parameters"]).map(async([C,F])=>await xTa({file:n,queryParameterKey:C,queryParameter:F}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,F])=>U2e({headerKey:C,header:F,file:n}))):[],requestBody:Wtd({request:q.request,file:n}),sdkRequest:await $td({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await Prd({endpoint:q,file:n,typeResolver:a}),errors:[...Erd({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:Ord({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(F=>Ytd({codeSample:F,file:n}))})):[],autogeneratedExamples:[],pagination:await Srd({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=o1.generateEndpointId(P,I),I}))}}async function Szn({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>u6w({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function u6w({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await X$(t),name:n.casingsGenerator.generateName(e),valueType:s6w({parameter:t,variableResolver:i,file:n}),location:r,variable:NIn(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function s6w({parameter:e,variableResolver:t,file:r}){let n=xPi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function xPi({parameter:e,variableResolver:t,file:r}){let n=CTa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function CTa({parameter:e,variableResolver:t,file:r}){if(NIn(e)){let n=typeof e=="string"?e:e.variable,i=t.getDeclaration(n,r);return i==null?void 0:{rawType:typeof i.declaration=="string"?i.declaration:i.declaration.type,file:i.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function c6w(e){switch(e){case"GET":return Rie.Get;case"POST":return Rie.Post;case"PUT":return Rie.Put;case"PATCH":return Rie.Patch;case"DELETE":return Rie.Delete;default:xc(e)}}async function U2e({headerKey:e,header:t,file:r}){let{name:n}=uLt({headerKey:e,header:t});return{...await X$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function uLt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function l6w(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:xc(e)}}var Z$={};kc(Z$,{validateObjectExample:()=>Ian,validateTypeExample:()=>ATa,validateTypeReferenceExample:()=>nQ});function Trd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function qTa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function Crd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:o1.generateEndpointIdFromResolvedEndpoint(i),serviceId:o1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:qTa({fernFilePath:i.file.fernFilepath})?void 0:o1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{refreshToken:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.refresh_token})},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function qrd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:o1.generateEndpointIdFromResolvedEndpoint(i),serviceId:o1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:qTa({fernFilePath:i.file.fernFilepath})?void 0:o1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{clientId:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_id}),clientSecret:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_secret}),scopes:n.requestProperties.scopes!=null?await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.scopes}):void 0},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Ird({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await qrd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:i});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?await Crd({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:n["client-id-env"],clientSecretEnvVar:n["client-secret-env"],tokenPrefix:n["token-prefix"],scopes:n.scopes,tokenEndpoint:u,refreshEndpoint:f}}var TPi={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}},Tqu={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 Brd(e){return{endpoint:e["get-token"].endpoint,requestProperties:f6w({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:d6w({responseProperties:e["get-token"]?.["response-properties"]})}}function Nrd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:p6w({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:_6w({responseProperties:e["refresh-token"]?.["response-properties"]})}}function f6w({requestProperties:e}){if(e==null)return TPi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?WIt(t):TPi.requestProperties.client_id,client_secret:r!=null?WIt(r):TPi.requestProperties.client_secret,scopes:n!=null?WIt(n):TPi.requestProperties.scopes}}function d6w({responseProperties:e}){return zrd({responseProperties:e,defaultValue:TPi.responseProperties})}function p6w({requestProperties:e}){if(e==null)return Tqu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?WIt(t):Tqu.requestProperties.refresh_token}}function _6w({responseProperties:e}){return zrd({responseProperties:e,defaultValue:Tqu.responseProperties})}function zrd({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],n=e["expires-in"],i=e["refresh-token"];return{type:"access_token",access_token:r!=null?fMr(r):t.access_token,expires_in:n!=null?fMr(n):t.expires_in,refresh_token:i!=null?fMr(i):t.refresh_token}}async function Vrd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:DNr.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return ayi(e.auth,{single:async a=>{let u=await Rrd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:DNr.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:DNr.Any,schemes:await Promise.all(a.map(async u=>await Rrd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function Rrd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:n,endpointResolver:i}){let a=(f,d)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return bsu(c,{header:async o=>EH.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:async o=>Lrd({file:r,docs:d,rawScheme:o}),bearer:async o=>Frd({file:r,docs:d,rawScheme:o}),oauth:async o=>await Urd({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Frd({file:r,docs:void 0,rawScheme:void 0});case"basic":return Lrd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await Urd({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Frd({file:e,docs:t,rawScheme:r}){return EH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Lrd({file:e,docs:t,rawScheme:r}){return EH.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})}async function Urd({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return EH.oauth({docs:t,configuration:SNr.clientCredentials(await Ird({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:Brd(r),refreshTokenEndpoint:Nrd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function Wrd({file:e,rawApiFileSchema:t}){if(t.version!=null)return ANr.header({header:await h6w({file:e,header:t.version.header}),value:await y6w({file:e,versionDeclaration:t.version})})}async function h6w({file:e,header:t}){return typeof t=="string"?await U2e({file:e,headerKey:t,header:{type:"string"}}):await U2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function y6w({file:e,versionDeclaration:t}){return await MTa({_enum:{default:t.default,enum:t.values},file:e})}async function Hrd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a}){let u=[];for(let[f,d]of Object.entries(e.messages??{}))u.push({type:f,availability:Sae(d.availability),docs:d.docs,origin:d.origin,body:g6w({body:d.body,file:i}),displayName:d["display-name"]});return{availability:Sae(e.availability),path:F2e(e.path),auth:e.auth,name:i.fernFilepath.file??i.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?await Promise.all(Object.entries(e.headers).map(([f,d])=>U2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await Szn({pathParameters:e["path-parameters"],location:OCe.Endpoint,file:i,variableResolver:n}):[],queryParameters:e["query-parameters"]!=null?await Promise.all(Object.entries(e["query-parameters"]).map(async([f,d])=>{let{name:c}=pMr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await X$(d),name:i.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}})):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let d=O6w({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a});return{name:f.name!=null?i.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:w6w({channel:e,example:f,pathParams:d}),...d,...P6w({channel:e,example:f,typeResolver:t,exampleResolver:r,file:i,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:i.casingsGenerator.generateNameAndWireValue({name:pMr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:v6w({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:b6w({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function v6w({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function b6w({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!j6w(e.body))return F6t.reference(lT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!lS(t))throw new Error("Example must be an object");let u=[];for(let[f,d]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:f,property:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let o=MPi({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:i});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:i.casingsGenerator.generateNameAndWireValue({name:rQ({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:o.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:o.typeName})}}return F6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function g6w({body:e,file:t}){return typeof e=="string"?DCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):m6w(e)?DCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):DCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:VIt(e.extends??[]).map(r=>CU({typeName:r,file:t})),properties:[]})}function m6w(e){return e.type!=null}function O6w({channel:e,example:t,typeResolver:r,exampleResolver:n,variableResolver:i,file:a,workspace:u}){let f=[],d=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let g=xPi({parameter:o,variableResolver:i,file:a});return{name:c,value:lT({example:l,rawTypeBeingExemplified:g.rawType,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null)for(let[c,o]of Object.entries(t["path-parameters"])){let l=e["path-parameters"]?.[c];if(l!=null)f.push(d({name:a.casingsGenerator.generateName(c),pathParameterDeclaration:l,examplePathParameter:o}));else throw new Error(`Path parameter ${c} does not exist`)}return{pathParameters:f}}function P6w({channel:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=[];if(t.headers!=null)for(let[f,d]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:uLt({headerKey:f,header:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function w6w({channel:e,example:t,pathParams:r}){let n=e.path;if(t["path-parameters"]!=null)for(let i of[...r.pathParameters])n=n.replaceAll(`{${i.name.originalName}}`,`${i.value.jsonExample}`);return n}function j6w(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function Cqu({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{defaultEnvironment:e??void 0,environments:NEr(n,{singleBaseUrl:()=>q6t.singleBaseUrl(D6w({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q6t.multipleBaseUrls(S6w({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function D6w({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>NEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:Qrd(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function S6w({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>NEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>Qrd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function Qrd(e){return e.endsWith("/")?e.slice(0,-1):e}function Jrd({errorName:e,errorDeclaration:t,file:r,typeResolver:n,exampleResolver:i,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:i.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:lT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:oRr({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 Grd="content";function $rd(e,t){if(e==null||e.strategy==="status-code")return z6t.statusCode();switch(e.strategy){case"property":return z6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Grd,wireValue:Grd})});default:xc(e)}}function Krd({readme:e,services:t}){let r=new qqu(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(([n,i])=>[n,i.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var qqu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=A6w({endpoint:t}),n=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[n]}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 n of Object.values(t))for(let i of n.endpoints)r[this.getEndpointKeyForHttpEndpoint(i)]=i;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:E6w(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function E6w(e){let t="";e.fullPath.head.length>0&&(t=k1(t,e.fullPath.head));for(let r of e.fullPath.parts)t=k1(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=k1(t,r.tail));return t.startsWith("/")?t:`/${t}`}function A6w({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}async function Yrd({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:o1.generateWebhookId(t.fernFilepath,u),availability:Sae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?await Promise.all(Object.entries(f.headers).map(([d,c])=>U2e({headerKey:d,header:c,file:t}))):[],payload:M6w({payload:f.payload,file:t}),examples:f.examples!=null?T6w({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function M6w({payload:e,file:t}){return typeof e=="string"?Qie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):ITa(e)?Qie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Qie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:VIt(e.extends).map(r=>CU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>x6w({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?Sae(n.availability):void 0,file:t})):[]})}function x6w({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:rQ({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function T6w({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:ITa(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:lT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!lS(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:lT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function ITa(e){return e.type!=null}function Ezn(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Xrd({name:e,source:t}){return wD.userDefined({file:TTa({source:t}),name:uRr.generateName(e)})}function Zrd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=C6w({type:e.proto.type});if(t!=null)return t}}function C6w({type:e}){switch(e){case"google.protobuf.Any":return wD.wellKnown(uh.any());case"google.protobuf.Api":return wD.wellKnown(uh.api());case"google.protobuf.BoolValue":return wD.wellKnown(uh.boolValue());case"google.protobuf.BytesValue":return wD.wellKnown(uh.bytesValue());case"google.protobuf.DoubleValue":return wD.wellKnown(uh.doubleValue());case"google.protobuf.Duration":return wD.wellKnown(uh.duration());case"google.protobuf.Empty":return wD.wellKnown(uh.empty());case"google.protobuf.Enum":return wD.wellKnown(uh.enum());case"google.protobuf.EnumValue":return wD.wellKnown(uh.enumValue());case"google.protobuf.Field":return wD.wellKnown(uh.field());case"google.protobuf.FieldCardinality":return wD.wellKnown(uh.fieldCardinality());case"google.protobuf.FieldKind":return wD.wellKnown(uh.fieldKind());case"google.protobuf.FieldMask":return wD.wellKnown(uh.fieldMask());case"google.protobuf.FloatVlaue":return wD.wellKnown(uh.floatValue());case"google.protobuf.Int32Value":return wD.wellKnown(uh.int32Value());case"google.protobuf.Int64Value":return wD.wellKnown(uh.int64Value());case"google.protobuf.ListValue":return wD.wellKnown(uh.listValue());case"google.protobuf.Method":return wD.wellKnown(uh.method());case"google.protobuf.Mixin":return wD.wellKnown(uh.mixin());case"google.protobuf.NullValue":return wD.wellKnown(uh.nullValue());case"google.protobuf.Option":return wD.wellKnown(uh.option());case"google.protobuf.SourceContext":return wD.wellKnown(uh.sourceContext());case"google.protobuf.StringValue":return wD.wellKnown(uh.stringValue());case"google.protobuf.Struct":return wD.wellKnown(uh.struct());case"google.protobuf.Syntax":return wD.wellKnown(uh.syntax());case"google.protobuf.Timestamp":return wD.wellKnown(uh.timestamp());case"google.protobuf.Type":return wD.wellKnown(uh.type());case"google.protobuf.Uint32Value":return wD.wellKnown(uh.uint32Value());case"google.protobuf.Uint64Value":return wD.wellKnown(uh.uint64Value());case"google.protobuf.Value":return wD.wellKnown(uh.value())}}async function krd({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=E3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&mA(a.declaration)){let u=E3(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([d,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=i.arguments?.[u.indexOf(c)]??c),[d,o]});return Sq.object({extends:VIt(a.declaration.extends).map(d=>CU({typeName:d,file:t})),properties:await jPi({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${n}`)}async function end({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return gCe(n)?await krd({generic:n,file:t,typeResolver:r}):Sq.alias({aliasOf:t.parseTypeReference(e),resolvedType:q6w({aliasOf:n,file:t,typeResolver:r})})}function q6w({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return AH.primitive(n.originalTypeReference.primitive);case"container":return AH.container(n.originalTypeReference.container);case"unknown":return AH.unknown();case"named":{let i=mA(n.declaration)?R6t.Object:LNr(n.declaration)?R6t.Union:V6t(n.declaration)?R6t.Enum:RIn(n.declaration)?R6t.UndiscriminatedUnion:xc(n.declaration);return AH.named({name:n.name,shape:i})}}}function tnd({union:e,file:t}){return Sq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function rnd(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 Bqu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new Iqu}){let i=I8(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=E3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=E3(o.typeName)?.arguments;if(mA(o.declaration)){let g=rnd(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>rnd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),f.push(...Object.values(u.union).reduce((d,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&d.push(o),d},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,d)=>{let c=typeof d=="string"?d:d.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of i){let f=O$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:c})=>[...d,...c],list:d=>d,optional:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of f){let c=CU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(gCe(o.typeName))continue;a.push(...Bqu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var Iqu=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}};async function nnd({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await X$(t),d=CU({typeName:e,file:r}),c=Bqu({typeDeclaration:t,file:r,typeResolver:n}),o={};mA(t)&&(o=Ezn(t.properties??{}));let l=await B6w({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await I6w({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:N6w({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(g=>({name:g.name!=null?r.casingsGenerator.generateName(g.name):void 0,docs:g.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:g.value,file:r}).resolvedExample,shape:xqu({typeName:d,example:g.value,typeResolver:n,exampleResolver:i,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(g=>g.fernFilepath))}}async function I6w({typeDeclaration:e,file:t,typeResolver:r}){return await I8(e,{alias:n=>end({alias:n,file:t,typeResolver:r}),object:n=>Utd({object:n,file:t}),discriminatedUnion:n=>nrd({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>tnd({union:n,file:t}),enum:async n=>Sq.enum(await MTa({_enum:n,file:t}))})}async function B6w({file:e,typeDeclaration:t,typeName:r,sourceResolver:n}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Zrd({encoding:t.encoding});if(a!=null)return IEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return IEr.proto(Xrd({source:i,name:r}))}function N6w({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?z6w(e.encoding):R6w(t)}function z6w(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function R6w(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function ind(e,t){let r=t[e];if(r==null)throw new JSr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function and(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,L6w({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>F6w({endpoint:n,ir:e}))}]))}}function F6w({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>ond(r,t))}}}function L6w({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>ond(r,t))}}}return e}function ond(e,t){let r=Nqu(e.typeId,t);return und({objectTypeDeclaration:r,ir:t})}function Nqu(e,t){let r=ind(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Nqu(r.shape.resolvedType.name.typeId,t)}throw new JSr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function und({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=Nqu(n.typeId,t);return und({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var BTa=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:a,endpoints:u,webhooks:f,subpackages:d,queryParameters:c,requestProperties:o,webhookPayloadProperties:l}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=c}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=o1.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=o1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=o1.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 n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var NTa=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=U6w(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=o1.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=o1.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){return this.typesReferencedByService}addError(t){let r=o1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&Q5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=o1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])Q5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])Q5(c.valueType,u,d);for(let c of r.queryParameters)Q5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=Ezn(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&M5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)zqu(o,u,d);for(let o of c.properties)Q5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&y6(n.request.body)){let o=Ezn(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{Q5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)Fie._visit(o,{file:ll,bodyProperty:({valueType:l})=>{Q5(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&A3._visit(r.response.body,{fileDownload:ll,json:c=>{Q5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>Q5(o.payload,u,d),json:o=>Q5(o.payload,u,d),text:ll,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>Q5(o.payload,u,d),json:o=>Q5(o.payload,u,d),text:ll,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&Q5(c.nonStreamResponse.value.responseBodyType,u,d)},text:ll,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(o1.generateErrorId(c.error)),d.add(c.error.fernFilepath)});for(let c of u)this.markTypeForService(c,i);this.endpoints[a]={endpointId:a,referencedTypes:u,referencedErrors:f,referencedSubpackages:d}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=o1.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,n){let i=r.id;if(i==null)return;let a=new Set,u=new Set;r.payload!=null&&Qie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)zqu(d,a,u);for(let d of f.properties)Q5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!ITa(n.payload)){let d=Ezn(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{Q5(f,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let f of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(f);for(let c of d.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(f);this.addReferencedTypes(t,d.referencedTypes)}let n={},i={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,d]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}c.size>0&&(n[f]=c),n[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}i[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(g=>{c.add(g)})}a[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}u[f]=c.size>0?c:void 0}}return new BTa({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t];n==null?this.typesReferencedByService[t]=new Set(r):n.add(r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=i.descendantsByAudience[a];if(u!=null)u.forEach(f=>{t.add(f)});else{i.allDescendants.forEach(f=>{t.add(f)});break}}else i.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}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:xc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(o1.generateSubpackageId(n))}}};function U6w(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:xc(e)}}function Q5(e,t,r){uT._visit(e,{container:n=>{V6w(n,t,r)},named:n=>{zqu(n,t,r)},primitive:ll,unknown:ll,_other:ll})}function zqu(e,t,r){t.add(o1.generateTypeId(e)),r.add(e.fernFilepath)}function V6w(e,t,r){Eq._visit(e,{list:n=>{Q5(n,t,r)},map:n=>{Q5(n.keyType,t,r),Q5(n.valueType,t,r)},optional:n=>{Q5(n,t,r)},set:n=>{Q5(n,t,r)},literal:ll,_other:ll})}function cnd({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?C8.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?C8.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function ON({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(gA.list({...n,list:n.list.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(gA.set({...n,set:n.set.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?ON({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(gA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(gA.map({...n,map:n.map.map(i=>{let a=ON({filteredIr:e,exampleTypeReference:i.key}),u=ON({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:dS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:dS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=cnd({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Rqu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function W6w({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function snd({filteredIr:e,headers:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function H6w({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?v$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function Q6w({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>T4.ok(cN.body(n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>T4.ok(cN.stream(n.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter($M))),sse:n=>T4.ok(cN.sse(n.map(({event:i,data:a})=>{let u=ON({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter($M))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>T4.error({error:r,body:n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Fqu({filteredIr:e,example:t}){return{...t,rootPathParameters:Rqu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Rqu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Rqu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:snd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:snd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:W6w({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?H6w({filteredIr:e,requestBody:t.request}):void 0,response:Q6w({filteredIr:e,response:t.response})}}function lnd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:ON({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=cnd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var zTa=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 n=this.getPackageForFernFilepath(t);if(n.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");n.navigationConfig={pointsTo:o1.generateSubpackageId(r)}}addDocs(t,r){let n=this.getPackageForFernFilepath(t);if(n.docs!=null)throw new Error("Found duplicate docs for package");n.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 n=this.getPackageForFernFilepath(r.name.fernFilepath);if(n.service!=null)throw new Error("Found duplicate service for "+t);n.service=t}addWebhookGroup(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.webhooks=t}addWebSocketChannel(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([n,i])=>{t.hasSubpackageId(n)?this.subpackages[n]={...i,types:i.types.filter(a=>t.hasTypeId(a)),errors:i.errors.filter(a=>t.hasErrorId(a)),service:i.service!=null&&t.hasServiceId(i.service)?i.service:void 0,subpackages:i.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[n]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(n=>t.hasTypeId(n)),errors:this.rootPackage.errors.filter(n=>t.hasErrorId(n)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(n=>t.hasSubpackageId(n)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:by(this.subpackages,(n,i)=>({...n,hasEndpointsInTree:r.has(i)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!fnd(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let n=this.subpackages[t];if(n==null)throw new Error("Subpackage does not exist: "+t);if(!fnd(n.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");n.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let n=this.getAllChildrenWithEndpoints(r);return(n.length>0||r.service!=null)&&n.push(t),n}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,n=this.rootPackage){let i=t.allParts[r];if(i==null)return n;let a=n.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},d=a.find(c=>c.name.originalName===i.originalName);if(d==null){let c=o1.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:i,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,n.subpackages.push(c),d=o}return this.getPackageForFernFilepath(t,u,d)}};function fnd(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let n of t)if(!r.has(n))return!1;return!0}function dnd({reference:e,referencedIn:t,imports:r}){let[n,i,...a]=e.split(".");if(n==null||a.length>0)return;if(i==null)return{endpointName:n,relativeFilepath:t};let f=r[n];if(f!=null)return{endpointName:i,relativeFilepath:aRr({referencedIn:t,importPath:f})}}var Nan=class{workspace;constructor(t){this.workspace=t}async resolveEndpointOrThrow({endpoint:t,file:r}){let n=await this.resolveEndpoint({endpoint:t,file:r});if(n==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return n}async resolveEndpointByMethodAndPath({method:t,path:r}){let n;return await W8(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:uRr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(n={endpointId:d,endpoint:c,file:f})}),await Enn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:uRr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(n={endpointId:f,endpoint:d,file:u})}),n}async resolveEndpoint({endpoint:t,file:r}){let i=new oyi().tryParse(t);if(i!=null)return await this.resolveEndpointByMethodAndPath(i);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 n=dnd({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(!(i==null||i.service?.endpoints?.[n.endpointName]==null))return{endpointName:n.endpointName,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var zan=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Error does not exist: "+t);return n}getDeclaration(t,r){let n=LDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.errors?.[n.typeName];if(a!=null)return{declaration:a,file:qO({definitionFile:i,relativeFilepath:n.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var VDe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let n=this.resolveExample({example:t,file:r});return n==null||typeof n.resolvedExample=="string"?n:this.resolveAllReferencesInExample({example:n.resolvedExample,file:n.file})}else if(lS(t)){let n={};for(let[i,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;n[i]=u.resolvedExample}return{resolvedExample:n}}else if(Array.isArray(t)){let n=[];for(let i of t){let a=this.resolveAllReferencesInExample({example:i,file:r});if(a==null)return;n.push(a.resolvedExample)}return{resolvedExample:n}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let n=this.resolveAllReferencesInExample({example:t,file:r});if(n==null)throw new Error("Failed to resolve examples");return n}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${oFt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(oFt))return{resolvedExample:t,file:r};let n=this.parseExampleReference(t);if(n==null)return;let i=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:n.rawTypeReference,file:r});if(i==null||typeof i.declaration=="string"||i.declaration.examples==null)return;let a=i.declaration.examples.find(u=>u.name===n.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:i.file})}resolveExampleOrThrow({example:t,file:r}){let n=this.resolveExample({example:t,file:r});if(n==null)throw new Error("Cannot resolve example: "+t);return n}parseExampleReference(t){let[r,n,i,...a]=t.split(".");if(!(r==null||n==null||a.length>0))return i==null?{rawTypeReference:r.slice(oFt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(oFt.length),exampleName:i}}};var RTa=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}async resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveRequestProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(i.endpoint.request==null)return;if(typeof i.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:i.file,requestType:i.endpoint.request,propertyComponents:n});let a=await this.resolveObjectProperty({file:i.file,typeName:i.endpoint.request,propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:Vie.body(a)}}async resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveResponseProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=await this.resolveObjectProperty({file:i.file,typeName:(typeof i.endpoint.response!="string"?i.endpoint.response?.type:i.endpoint.response)??"",propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:a}}async resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(i.length===1){let a=i[0]??"",u=typeof n["query-parameters"]!=null?n["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Vie.query(await xTa({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i})}async resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(n.body==null)return;if(typeof n.body=="string"){let u=await this.resolveObjectProperty({file:r,typeName:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(u)}}if(y6(n.body)){let u=await Equ({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(u)}}let a=await this.resolveObjectProperty({file:r,typeName:n.body.type,propertyComponents:i});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Vie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await Squ({typeResolver:this.typeResolver,file:SPi(i)??t,resolvedType:i,propertyComponents:n})}async propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(n=>r.casingsGenerator.generateName(n))}};var pnd=require("fs/promises"),FTa=class{async parse({absoluteFilePath:t}){let r=await(0,pnd.readFile)(t,"utf-8"),n=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),i=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:n?.[1],packageName:i?.[1],serviceName:a?.[1]}}};var LTa=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}async resolveSourceOrThrow({source:t,file:r}){let n=await this.resolveSource({source:t,file:r});if(n==null){if(hca(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r.relativeFilepath}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r.relativeFilepath}`)}return n}async resolveSource({source:t,file:r}){return hca(t)?await this.resolveProtobufSource({source:t,file:r}):await this.resolveOpenAPISource({source:t,file:r})}async resolveProtobufSource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.proto));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let a=await new FTa().parse({absoluteFilePath:n}),u={type:"protobuf",absoluteFilePath:n,relativeFilePath:Ms.of(t.proto),csharpNamespace:a.csharpNamespace,packageName:a.packageName,serviceName:a.serviceName};return this.sourceCache.set(n,u),u}async resolveOpenAPISource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.openapi));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let i={type:"openapi",absoluteFilePath:n,relativeFilePath:Ms.of(t.openapi)};return this.sourceCache.set(n,i),i}};var eM=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let n=this.resolveType({type:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let n=LDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=lae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=E3(n.typeName);if(u!=null){for(let f of Object.keys(i.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let d=i.types?.[f];return d!=null?{typeName:f,declaration:d,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:n.typeName,declaration:a,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:n=[]}){return O$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:uT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:uT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:uT.container(Eq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:uT.container(Eq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:uT.container(Eq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:uT.container(Eq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:uT.container(Eq.literal(i))}),named:i=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:i,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:i};if(!n.some(f=>f.file===u.file&&f.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:i,referencedIn:r,rawDeclaration:a,objectPath:[...n,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.resolveNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t);return n}resolveNamedType({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n,objectPath:i=[]}){let{declaration:a,file:u}=n;if(zIn(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=ETa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||lae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:n.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:i,originalTypeReference:f,file:u}}};var QIt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Variable does not exist: "+t);return n}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let n=r.rootApiFile.variables?.[t.substring(1)];if(n!=null)return{declaration:n,file:dMr({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 UTa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function _nd({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":{let r=e??aD.STRING;return{type:"success",example:Pv.string({original:r}),jsonExample:r}}case"BASE_64":return{type:"success",example:Pv.base64(aD.BASE64),jsonExample:aD.BASE64};case"BOOLEAN":return{type:"success",example:Pv.boolean(aD.BOOLEAN),jsonExample:aD.BOOLEAN};case"DATE":return{type:"success",example:Pv.date(aD.DATE),jsonExample:aD.DATE};case"DATE_TIME":return{type:"success",example:Pv.datetime({datetime:new Date(aD.DATE_TIME),raw:aD.DATE_TIME}),jsonExample:aD.DATE_TIME};case"DOUBLE":return{type:"success",example:Pv.double(aD.DOUBLE),jsonExample:aD.DOUBLE};case"FLOAT":return{type:"success",example:Pv.float(aD.FLOAT),jsonExample:aD.FLOAT};case"INTEGER":return{type:"success",example:Pv.integer(aD.INT),jsonExample:aD.INT};case"UINT_64":return{type:"success",example:Pv.uint64(aD.INT64),jsonExample:aD.INT64};case"UINT":return{type:"success",example:Pv.uint(aD.UINT),jsonExample:aD.UINT};case"BIG_INTEGER":return{type:"success",example:Pv.bigInteger(aD.INT64.toString()),jsonExample:`${aD.INT64}`};case"LONG":return{type:"success",example:Pv.long(aD.INT64),jsonExample:aD.INT64};case"UUID":return{type:"success",example:Pv.uuid(aD.UUID),jsonExample:aD.UUID};default:xc(t.v1)}}function hnd({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return cRr({containerType:t});switch(t.type){case"list":{let u=YF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gA.literal({literal:t.literal._visit({boolean:u=>Pv.boolean(u),string:u=>Pv.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 cRr({containerType:t});let u=YF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=YF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=YF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=YF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?cRr({containerType:t}):{type:"success",example:gA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:xc(t)}}function cRr({containerType:e}){switch(e.type){case"list":return{type:"success",example:gA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gA.literal({literal:e.literal._visit({boolean:t=>Pv.boolean(t),string:t=>Pv.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:gA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:gA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:xc(e)}}function Azn({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 vnd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=YF({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.alias({value:f}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=ynd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=YF({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:c,jsonExample:o}=d;return{type:"success",example:dS.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let d=f.shape._visit({noProperties:()=>({type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.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=ynd({currentDepth:i,maxDepth:n,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:g,jsonExample:O}=l;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=YF({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:g}=o;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:C8.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:g}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function ynd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:u}){let f={},d=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=YF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!Azn({typeDeclarations:n,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:g}=o;d.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=g}return{type:"success",example:dS.object({properties:d}),jsonExample:f}}function YF({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)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=vnd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:d,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:dO.named({shape:d,typeName:u.name})},jsonExample:c}}case"container":{let u=hnd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=cRr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:dO.container(c)},jsonExample:o}}let{example:f,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:dO.container(f)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:f}=_nd({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:dO.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:dO.unknown(u)},jsonExample:u}}}}var bnd=Xo(y1u(),1);function CPi({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:T4.ok(cN.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=YF({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}for(let c of t.queryParameters){if(i&&Azn({typeDeclarations:n,typeReference:c.valueType}))continue;let o=YF({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:c.valueType,skipOptionalProperties:i});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?NF.exploded():NF.single(),value:l})}let d=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of d)for(let o of c.params){if(i&&Azn({typeDeclarations:n,typeReference:o.valueType}))continue;let l=YF({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}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 g=YF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!Azn({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${g.message}`};if(g.type==="failure")continue;let{example:O,jsonExample:P}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=P}u.request=v$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=v$.reference(o);break}default:xc(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=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=T4.ok(cN.body({...o,jsonExample:l}));break}case"streamParameter":return{type:"failure",message:"Stream parameter unsupported"};case"streaming":return{type:"failure",message:"Streaming unsupported"};case"text":return{type:"failure",message:"Text unsupported"};default:xc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=T4.error({body:void 0,error:a.declaration.name});else{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=T4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,bnd.default)(u),url:J6w(t,u),...u},jsonExample:void 0}}function J6w(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=u});let n=e.fullPath.head+e.fullPath.parts.map(i=>r[i.pathParameter]+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}async function iQ({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,includeOptionalRequestPropertyExamples:u,audiences:f,readme:d,packageName:c,version:o,context:l}){let g=aLt({generationLanguage:r,keywords:n,smartCasing:i}),O=new NTa(f),P=dMr({casingsGenerator:g,rootApiFile:t.definition.rootApiFile.contents}),j=(t.definition.rootApiFile.contents.errors??[]).map(Gt=>({error:oRr({errorName:Gt,file:P}),docs:void 0})),M=new eM(t),q=new Nan(t),B=new RTa(M,q),I=new zan(t),C=new VDe(M),F=new QIt,K=new LTa(l,t),ee={fdrApiDefinitionId:e,apiVersion:await Wrd({file:P,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:g.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await wTa(t.definition.rootApiFile.contents.docs),auth:await Vrd({rawApiFileSchema:t.definition.rootApiFile.contents,file:P,propertyResolver:B,endpointResolver:q}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Gt,ln])=>U2e({headerKey:Gt,header:ln,file:P}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Gt,ln])=>U2e({headerKey:Gt,header:ln,file:P}))):[],types:{},errors:{},services:{},constants:Trd(g),environments:Cqu({casingsGenerator:g,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:$rd(t.definition.rootApiFile.contents["error-discrimination"],P),basePath:t.definition.rootApiFile.contents["base-path"]!=null?F2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await Szn({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:P,location:OCe.Root,variableResolver:F}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Gt,ln])=>({docs:typeof ln!="string"?ln.docs:void 0,id:Gt,name:P.casingsGenerator.generateName(Gt),type:P.parseTypeReference(ln)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},J=new zTa,G=async Gt=>{J.addSubpackage(Gt.fernFilepath),await VP(Gt.definitionFile,{imports:ll,docs:ln=>{ln!=null&&J.addDocs(Gt.fernFilepath,ln)},types:async ln=>{if(ln!=null)for(let[En,Ht]of Object.entries(ln)){if(gCe(En))continue;let tr=await nnd({typeName:En,typeDeclaration:Ht,file:Gt,typeResolver:M,exampleResolver:C,sourceResolver:K,workspace:t}),on=tr.typeDeclaration;a&&(on.userProvidedExamples=[],on.autogeneratedExamples=[]);let dn=tr.descendantFilepaths,wi=o1.generateTypeId(on.name);ee.types[wi]=on,J.addType(wi,on),O.addType({declaredTypeName:on.name,descendantTypeIds:on.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:tr.propertiesByAudience,descendantFilepaths:dn}),O.markTypeForAudiences(on.name,Ltd(Ht))}},errors:ln=>{if(ln==null)return;if(t.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[Ht,tr]of Object.entries(ln)){let on=Jrd({errorName:Ht,errorDeclaration:tr,file:Gt,typeResolver:M,exampleResolver:C,workspace:t}),dn=o1.generateErrorId(on.name);ee.errors[dn]=on,J.addError(dn,on),O.addError(on)}},service:async ln=>{if(ln==null)return;let En=await xrd({rootDefaultUrl:Gt.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:ee.pathParameters,serviceDefinition:ln,file:Gt,errorResolver:I,typeResolver:M,propertyResolver:B,exampleResolver:C,sourceResolver:K,globalErrors:j,variableResolver:F,workspace:t}),Ht=o1.generateServiceId(En.name);ee.services[Ht]=En,J.addService(Ht,En);let tr={};En.endpoints.forEach(on=>{a&&(on.autogeneratedExamples=[],on.userSpecifiedExamples=[]);let dn=ln.endpoints[on.name.originalName];O.addEndpoint(En,on,dn),tr[on.name.originalName]=on}),ln.audiences!=null&&O.markEndpointForAudience(En.name,En.endpoints,ln.audiences),Object.entries(ln.endpoints).map(([on,dn])=>{let wi=tr[on];wi!=null&&dn.audiences!=null&&O.markEndpointForAudience(En.name,[wi],dn.audiences)})},webhooks:async ln=>{if(ln==null)return;let En=o1.generateWebhookGroupId(Gt.fernFilepath),Ht=await Yrd({webhooks:ln,file:Gt,typeResolver:M,exampleResolver:C,workspace:t}),tr={};for(let on of Ht)tr[on.name.originalName]=on;Object.entries(ln).forEach(([on,dn])=>{let wi=tr[on];wi!=null&&(O.addWebhook(Gt,wi,dn),dn.audiences!=null&&O.markWebhookForAudiences(Gt,wi,dn.audiences))}),ee.webhookGroups[En]=Ht,J.addWebhookGroup(En,Gt.fernFilepath)},channel:async ln=>{if(ln==null)return;let En=o1.generateWebSocketChannelId(Gt.fernFilepath),Ht=await Hrd({channel:ln,file:Gt,variableResolver:F,typeResolver:M,exampleResolver:C,workspace:t});ee.websocketChannels!=null&&(ee.websocketChannels[En]=Ht,J.addWebSocketChannel(En,Gt.fernFilepath))}})};await W8(t,async(Gt,ln,En)=>{await G(qO({relativeFilepath:Gt,definitionFile:ln,casingsGenerator:g,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:En.defaultUrl}))}),await Enn(t,async(Gt,ln)=>{if(ln.navigation!=null)if(typeof ln.navigation=="string")J.addPackageRedirection({from:Dae({relativeFilepath:Gt,casingsGenerator:g}),to:Dae({relativeFilepath:yf(cb(Gt),Ms.of(ln.navigation)),casingsGenerator:g})});else{let En=ln.navigation.map(Ht=>o1.generateSubpackageId(Dae({relativeFilepath:yf(cb(Gt),Ms.of(Ht)),casingsGenerator:g})));Gt===$A?J.sortRootPackage(En):J.sortSubpackage(o1.generateSubpackageId(Dae({relativeFilepath:Gt,casingsGenerator:g})),En)}}),ee.serviceTypeReferenceInfo=$6w(O);let te=a?ee:G6w(ee,l,!u),Ye=t.definition.rootApiFile.contents,Re=Cqu({casingsGenerator:g,rawApiFileSchema:Ye}),wt=Re?.environments._visit({singleBaseUrl:Gt=>Gt.environments.filter(ln=>UTa(ln.id,Ye.environments)!=null).length===0,multipleBaseUrls:Gt=>Gt.environments.filter(ln=>UTa(ln.id,Ye.environments)!=null).length===0,_other:()=>!1});Re?.environments.environments.forEach(Gt=>{O.markEnvironmentForAudiences(Gt,UTa(Gt.id,Ye.environments)??[],wt)});let Ct=O.hasNoAudiences()?void 0:O.build(),Wt=K6w(te,Ct),Bt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Wt.services).every(Gt=>Gt.endpoints.every(ln=>ln.auth)),or=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.response?.body?.type==="streaming")),jr=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.pagination!=null)),Vr=Object.values(Wt.services).some(Gt=>Gt.endpoints.some(ln=>ln.response?.body?.type==="fileDownload")),It=d!=null?Krd({readme:d,services:ee.services}):void 0,{types:cr,services:fn}=and(Wt);return{...Wt,...J.build(Ct),types:cr,services:fn,sdkConfig:{isAuthMandatory:Bt,hasStreamingEndpoints:or,hasPaginatedEndpoints:jr,hasFileDownloadEndpoints:Vr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:o!=null&&c!=null?{header:"User-Agent",value:`${c}/${o}`}:void 0}},readmeConfig:It}}function G6w(e,t,r){for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=CPi({ir:e,service:i,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 $6w(e){let t={},r=[],n=e.getTypesReferencedByService();for(let[i,a]of Object.entries(n)){if(a.size===1){let u=a.values().next().value;t[u]===void 0&&(t[u]=[]),t[u]?.push(i);continue}r.push(i)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function K6w(e,t){if(t==null)return e;let r=Pkr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>lnd({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)&&d.push(c);return[u,{...f,shape:Sq.object({...f.shape,properties:d})}]}return[u,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let d=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,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:n,errors:Pkr(e.errors,u=>t.hasError(u)),services:by(Pkr(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(d=>({...d,example:Fqu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?Fqu({filteredIr:t,example:d.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(d=>t.hasQueryParameter(f.id,d.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(d=>t.hasRequestProperty(f.id,d.name.wireValue))}}:f))})),webhookGroups:i,serviceTypeReferenceInfo:Y6w(e.serviceTypeReferenceInfo,t)}}function Y6w(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}var And=Xo(vTa(),1),Mnd=Xo(bTa(),1),HTa=require("fs/promises"),xnd=Xo(cxa(),1);function sLt(e){return typeof e.subpackageId=="string"}function WDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Ran(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Lqu="__package__",lRr=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#n=new Map;#i=new Map;#r=new Map;#a=new Map;#o=new Map;#f=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return sLt(t)?t.subpackageId:Lqu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=KF.SubpackageId(t);return r===Lqu?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(n=>{let i=KF.SubpackageId(e.getSubpackageId(n)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(i,a),n.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,i);this.#e.set(f,u);let d=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{d.push(`${o} ${WDe(u.path.parts)}`),d.push(`${o} ${Ran(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,WDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ran(u.path.parts))}`);let g=gnd(l);g!=null&&(d.push(`${o} ${k1(g,WDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ran(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#f.set(o,u)})}),n.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,i);this.#t.set(f,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${WDe(u.path.parts)}`),d.push(`${o} ${Ran(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,WDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ran(u.path.parts))}`);let g=gnd(l);g!=null&&(d.push(`${o} ${k1(g,WDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ran(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.set(o,u)})}),n.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#n.set(e.createWebhookId(u,i),u)})}),this.#e.forEach((n,i)=>{this.#i.set(n,i)}),this.#t.forEach((n,i)=>{this.#r.set(n,i)}),this.#n.forEach((n,i)=>{this.#a.set(n,i)}),this.#p(t.rootPackage,[])}#p(t,r){if(t==null)return;let n=sLt(t)?[...r,t.name]:r,i=n.length===0?[Lqu]:n;if([i.join("."),i.join("/"),`${i.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#p(this.api.subpackages[t.pointsTo],n);t.endpoints.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#f.set(c,u)})}),t.websockets.forEach(u=>{let f=[...n,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=[...n,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.#p(this.api.subpackages[u],n)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#n}get endpointsByLocator(){return this.#f}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#r.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return Zc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Zc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Zc.WebhookId(`${r}.${t.id}`)}};function gnd(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 Mzn=Xo(vTa(),1),Ond=Xo(bTa(),1);function mnd(e){let t=e.split(".")[0];if(t==null)return;let n=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(n!=null)try{return new Date(n)}catch{}}Mzn.default.extend(Ond.default);var X6w="Changelog",Z6w=["summary","index","overview"],Fan=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}convert(t){if(this.changelogFiles==null||this.changelogFiles.length===0)return;let r=t.title??X6w;this.idgen=this.idgen.append("changelog");let n=[],i;for(let c of this.changelogFiles){let o=DKo(c.split("/"));if(o==null)continue;let l=mnd(o);if(l==null){let O=o.split(".")[0]?.toLowerCase();O!=null&&Z6w.includes(O)&&(i=c);continue}let g=this.toRelativeFilepath(c);n.push({date:l,pageId:Zc.PageId(g),absoluteFilepath:c})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??OF(r)}),u=n.map(c=>{let o=Mzn.default.utc(c.date);return{id:this.idgen.append(o.format("YYYY-M-D")).get(),type:"changelogEntry",title:o.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(c.absoluteFilepath)?.split("/"),urlSlug:o.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:c.date.toISOString(),pageId:c.pageId,noindex:void 0}}),f=Uqu(u,c=>c.date,"desc"),d=this.groupByYear(f,a);return{id:this.idgen.get(),type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:d,overviewPageId:i!=null?Zc.PageId(this.toRelativeFilepath(i)):void 0,noindex:void 0}}groupByYear(t,r){let n=new Map;for(let i of t){let a=Mzn.default.utc(i.date).year(),u=n.get(a)??[];u.push(i),n.set(a,u)}return Uqu(Array.from(n.entries()).map(([i,a])=>{let u=r.append(i.toString()).get();return{id:this.idgen.append(i.toString()).get(),type:"changelogYear",title:i.toString(),year:i,slug:u,icon:void 0,hidden:void 0,children:this.groupByMonth(a,r)}}),"year","desc")}groupByMonth(t,r){let n=new Map;for(let i of t){let a=Mzn.default.utc(i.date).month()+1,u=n.get(a)??[];u.push(i),n.set(a,u)}return Uqu(Array.from(n.entries()).map(([i,a])=>{let u=(0,Mzn.default)(new Date(0,i-1));return{id:this.idgen.append(u.format("YYYY-M")).get(),type:"changelogMonth",title:u.format("MMMM YYYY"),month:i,slug:r.append(i.toString()).get(),icon:void 0,hidden:void 0,children:a}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Uqu(e,t,r="asc"){return e.concat().sort((n,i)=>{let a=typeof t=="function"?t(n):n[t],u=typeof t=="function"?t(i):i[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}var fRr=class e{id;ids;static init(t){return new e(t,new Set([t]))}constructor(t,r){this.id=t,this.ids=r}get(){return Zc.V1.NodeId(this.id)}append(t){let r=`${this.id}.${t}`;if(this.ids.has(r)){let n=1;for(;this.ids.has(`${r}-${n}`);)n++;r=`${r}-${n}`}return this.ids.add(r),new e(r,this.ids)}};var VTa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#n=new Set;#i=new Set;#r=new Set;#a=new Map;#o=[];#f;#c;disableEndpointPairs;constructor(t,r,n,i,a,u,f){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Zc.V1.ApiDefinitionId(r.id),this.#e=lRr.create(r,u);let d=fRr.init(this.apiDefinitionId);this.#f=this.apiSection.overviewAbsolutePath!=null?Zc.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=n.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??OF(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,d)),this.#o=this.#d(this.#o.map(o=>this.#O(o)),this.#y(this.#e.api.rootPackage,this.#c))}get(){let t=Zc.V1.followRedirects(this.#o),r=fRr.init(this.apiDefinitionId);return{id:r.get(),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,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:new Fan(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,r).convert({parentSlug:this.#c}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#m(this.apiSection.playground)}}#s(t,r,n,i){r=this.#e.resolveSubpackage(r);let a=r!=null?lRr.getSubpackageId(r):void 0;return t.map(u=>Zxa(u)._visit({link:f=>({id:i.append(`link:${f.url}`).get(),type:"link",title:f.text,icon:f.icon,url:Zc.Url(f.url)}),page:f=>{let d=Zc.V1.PageId(this.toRelativeFilepath(f.absolutePath)),c=n.apply({fullSlug:this.markdownFilesToFullSlugs.get(f.absolutePath)?.split("/"),urlSlug:f.slug??OF(f.title)});return{id:i.append(`page:${d}`).get(),type:"page",pageId:d,title:f.title,slug:c.get(),icon:f.icon,hidden:f.hidden,noindex:f.noindex}},package:f=>this.#u(f,n,i),section:f=>this.#p(f,n,i),item:({value:f})=>this.#v(f,a,n,i),endpoint:f=>this.#_(f,a,n,i)})).filter($M)}#u(t,r,n){let i=t.overviewAbsolutePath!=null?Zc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,u=this.#e.getSubpackageByIdOrLocator(t.package);if(u!=null){let f=lRr.getSubpackageId(u),d=n.append(f);this.#r.has(f)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${f}`),this.#r.add(f),this.#a.set(d.get(),[f]);let c=t.slug??(sLt(u)?u.urlSlug:this.apiSection.slug??OF(this.apiSection.title)),o=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),l=this.#s(t.contents,u,o,d);return{id:d.get(),type:"apiPackage",children:l,title:t.title??(sLt(u)?u.displayName??wan(u.name):this.apiSection.title),slug:o.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#m(t.playground)}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let f=t.slug??OF(t.package),d=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#s(t.contents,void 0,d,n);return{id:n.append(OF(t.package)).get(),type:"apiPackage",children:c,title:t.title??t.package,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#m(t.playground)}}}#p(t,r,n){let i=t.overviewAbsolutePath!=null?Zc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,u=n.append(`section:${OF(t.title)}`),f=t.referencedSubpackages.map(l=>{let g=this.#e.getSubpackageByIdOrLocator(l);return g!=null?lRr.getSubpackageId(g):void 0}).filter(l=>(l==null&&this.taskContext.logger.error(`Subpackage ${l} not found in ${this.apiDefinitionId}`),l!=null)).filter($M);this.#a.set(u.get(),f),f.forEach(l=>{this.#r.has(l)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${l}`),this.#r.add(l)});let d=t.slug??OF(t.title),c=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,c,n);return{id:u.get(),type:"apiPackage",children:o,title:t.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.#m(t.playground)}}#v(t,r,n,i){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t);if(a!=null){let u=lRr.getSubpackageId(a),f=i.append(u);this.#r.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#r.add(u),this.#a.set(f.get(),[u]);let d=sLt(a)?a.urlSlug:"",c=n.apply({urlSlug:d});return{id:f.get(),type:"apiPackage",children:[],title:sLt(a)?a.displayName??wan(a.name):this.apiSection.title,slug:c.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}}return this.#_({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0},r,n,i)}#_(t,r,n,i){let a=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.endpoints.get(KF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let d=this.#e.getEndpointId(a);if(d==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);this.#t.has(d)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${d}`),this.#t.add(d);let c=t.slug!=null?n.append(t.slug):n.apply(a);return{id:i.append(a.id).get(),type:"endpoint",method:a.method,endpointId:d,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(a.availability),isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??WDe(a.path.parts),slug:c.get(),icon:t.icon,hidden:t.hidden,playground:this.#m(t.playground)}}let u=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webSockets.get(KF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(u!=null){let d=this.#e.getWebSocketId(u);if(d==null)throw new Error(`Expected WebSocket ID for ${u.id}. Got undefined.`);return this.#n.has(d)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${d}`),this.#n.add(d),{id:i.append(u.id).get(),type:"webSocket",webSocketId:d,title:t.title??u.name??WDe(u.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(u.availability),playground:this.#m(t.playground)}}let f=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webhooks.get(KF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Zc.V1.WebhookId(t.endpoint));if(f!=null){let d=this.#e.getWebhookId(f);if(d==null)throw new Error(`Expected Webhook ID for ${f.id}. Got undefined.`);return this.#i.has(d)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${d}`),this.#i.add(d),{id:i.append(f.id).get(),type:"webhook",webhookId:d,method:f.method,title:t.title??f.name??k1("/",...f.path),slug:(t.slug!=null?n.append(t.slug):n.apply(f)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#d(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#O(t){if(t.type==="apiPackage"){let r=Zc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#b(f,r)),a=t.children.map(f=>this.#O(f)),u=this.#d(a,i);return{...t,children:u,pointsTo:Zc.V1.followRedirects(u)}}return t}#y(t,r){let n=[];return t.endpoints.forEach(i=>{let a=this.#e.getEndpointId(i);if(a==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(i);n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??WDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0})}),t.websockets.forEach(i=>{let a=this.#e.getWebSocketId(i);if(a==null)throw new Error(`Expected WebSocket ID for ${i.id}. Got undefined.`);this.#n.has(a)||n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??WDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Zc.V1.convertAvailability(i.availability),playground:void 0})}),t.webhooks.forEach(i=>{let a=this.#e.getWebhookId(i);if(a==null)throw new Error(`Expected Webhook ID for ${i.id}. Got undefined.`);this.#i.has(a)||n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??wan(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0})}),t.subpackages.forEach(i=>{if(this.#r.has(i))return;let a=this.#e.getSubpackageByIdOrLocator(i);if(a==null){this.taskContext.logger.error(`Subpackage ${i} not found in ${this.apiDefinitionId}`);return}let u=sLt(a)?r.apply(a):r,f=this.#b(i,u);f.length>0&&n.push({id:Zc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:sLt(a)?a.displayName??wan(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:Zc.V1.followRedirects(f),noindex:void 0,playground:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((i,a)=>{let u=i.type==="endpointPair"?i.nonStream.title:i.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),n}#b(t,r){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#y(n,r)}#m(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Zc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Zc.V1.Url(t.button.href)}:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],n=new Map;return t.forEach(i=>{if(i.type!=="endpoint"){r.push(i);return}let a=this.#e.endpoints.get(i.endpointId);if(a==null)throw new Error(`Endpoint ${i.endpointId} not found`);let u=`${a.method} ${WDe(a.path.parts)}`,f=n.get(u);if(n.set(u,i),f==null||f.isResponseStream===i.isResponseStream){r.push(i);return}let d=r.indexOf(f),c=i.isResponseStream?i:f,o=i.isResponseStream?f:i,l={id:Zc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Pnd(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 WTa=Xo(O6t(),1);var DD=Xo(O6t(),1);var dRr=Xo(O6t(),1);function wnd(e){return e._visit({alias:t=>({type:"alias",value:Ex(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:J5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dRr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dRr.FernRegistry.PropertyKey(r.name.wireValue),valueType:Ex(r.valueType),availability:J5(r.availability)})),extraProperties:rIw(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:dRr.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:J5(n.availability),description:n.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?J5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[dRr.FernRegistry.TypeId(i.typeId)],properties:r}),singleProperty:i=>({extends:[],properties:[{key:dRr.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.type),description:void 0,availability:void 0},...r]}),noProperties:()=>({extends:[],properties:r}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.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:Ex(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function Ex(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:Ex(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:Ex(r),valueType:Ex(n)}),optional:r=>({type:"optional",itemType:Ex(r),defaultValue:void 0}),set:r=>({type:"set",itemType:Ex(r)}),literal:r=>lp.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:dRr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>eIw(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>tIw(t.v2),string:()=>k6w(t.v2),long:()=>({type:"long",default:0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:!1}),dateTime:()=>({type:"datetime",default:new Date(0).toISOString()}),date:()=>({type:"date",default:new Date(0).toISOString()}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",default:"0"}),bigInteger:()=>({type:"bigInteger",default:BigInt(0).toString()}),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 k6w(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.minLength,default:e!=null&&e.type==="string"?e.default:void 0}}function eIw(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 tIw(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 rIw(e){return typeof e=="boolean"?uT.unknown():typeof e=="string"?{type:"id",value:dRr.FernRegistry.TypeId(e),default:void 0}:Ex(e)}function Wqu(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?iIw(r,t):[],webhooks:n!=null?nIw(n):[],websockets:i!=null?[aIw(i,t)]:[],types:e.types.map(a=>DD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>DD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?DD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function nIw(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Rdi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:J5(r.availability)})),payload:pIw(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function iIw(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.userSpecifiedExamples.length>0&&i!=null)a.push(...n.userSpecifiedExamples.map(f=>Vqu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(Vqu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=CPi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...Vqu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:J5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:cIw(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?oIw({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Rdi(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...xzn(n.basePath),...xzn(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...t.basePath!=null?xzn(t.basePath):[],...xzn(e.basePath),...xzn(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:J5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:J5(f.availability)})),request:n.requestBody!=null?lIw(n.requestBody):void 0,response:n.response!=null?fIw(n.response):void 0,errors:void 0,errorsV2:dIw(n.errors,t),examples:a};r.push(u)}return r}function aIw(e,t){return{auth:e.auth,availability:J5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?uIw({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Rdi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:Ex(r.valueType),availability:void 0})),parts:xzn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:Ex(r.valueType),description:r.docs,availability:J5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:J5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:_Iw(r.body),description:r.docs,availability:J5(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((n,i)=>(n[DD.FernRegistry.PropertyKey(i.name.originalName)]=i.value.jsonExample,n),{}),queryParameters:r.queryParameters.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),headers:r.headers.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),messages:r.messages.map(n=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}))}}function J5(e){if(e!=null)switch(e.status){case"DEPRECATED":return DD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return DD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return DD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return DD.FernRegistry.Availability.Beta;default:xc(e.status)}}function oIw({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:i.url}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Expected environment ${i.id} to contain url for ${n}`);return{id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:xc(r)}}function uIw({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:DD.FernRegistry.EnvironmentId(n.id),baseUrl:sIw(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:xc(r)}}function sIw(e,t){return e.replace(/^[^:]+/,t)}function cIw(e){return lp.http.HttpMethod._visit(e,{get:()=>DD.FernRegistry.HttpMethod.Get,post:()=>DD.FernRegistry.HttpMethod.Post,put:()=>DD.FernRegistry.HttpMethod.Put,patch:()=>DD.FernRegistry.HttpMethod.Patch,delete:()=>DD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function xzn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:DD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function lIw(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>DD.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:DD.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:J5(n.availability)}))},description:r.docs??void 0}),reference:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"reference",value:Ex(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(n=>n._visit({file:i=>{let a=i._visit({file:u=>({type:"file",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:DD.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:i=>({type:"bodyProperty",key:DD.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.valueType),contentType:i.contentType,description:i.docs,availability:J5(i.availability)}),_other:()=>{}})).filter($M)},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 fIw(e){if(e.body==null)return;let t,r=lp.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:Ex(n.responseBodyType)}),text:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function dIw(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:Ex(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.name.name.originalName,availability:void 0,examples:i.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0}];i.type!=null&&a.push({key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:Ex(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.name.name.originalName,examples:i.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Vqu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(f=>{let d=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(d!=null)return{name:f.name,value:{jsonExample:d,shape:lp.ExampleTypeReferenceShape.primitive(lp.ExamplePrimitive.string({original:d}))}}}).filter($M),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,d)=>(f[DD.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((f,d)=>(f[d.name.wireValue]=d.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 d={};if(lS(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let g=c[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof g=="string"?g:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(g)?g:[g]).filter(P=>typeof P=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:$qt})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:lp.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let d=n.errors[f.errorId];if(d==null)throw new Error("Cannot find error "+f.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(c=>c.jsonExample)}),sse:d=>({type:"sse",value:d.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=>oDe._visit(f,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter($M)}}function pIw(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:J5(t.availability)}))},description:void 0};case"reference":return{type:{type:"reference",value:Ex(e.payloadType)},description:e.docs};default:xc(e)}}function _Iw(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:J5(t.availability)}))};case"reference":return{type:"reference",value:Ex(e.bodyType)};default:xc(e)}}var Hqu=Xo(O6t(),1);function jnd(e,t,r){let n=e.schemes[0];if(e.schemes.length===1&&n!=null)switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix};case"oauth":{let i=n.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:Hqu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Hqu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:xc(n)}}function HDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:Wqu(e.rootPackage,e),auth:jnd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:J5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:Ex(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[WTa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:wnd(a.shape),availability:J5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[WTa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:WTa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Wqu(a,e)}}return n}var Qqu=Xo(O6t(),1);async function Jqu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await iQ({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r}),d=Ttn({token:n.value}),c=HDe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await d.api.v1.register.registerApiDefinition({orgId:Qqu.FernRegistry.OrgId(e),apiId:Qqu.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 hIw=new San({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Dnd(e,t,r){return uPi(iPi(HDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),KF.ApiDefinitionId(t),hIw))}function Snd(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 _Mr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}And.default.extend(Mnd.default);var yIw=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),End=0,vIw=async({ir:e})=>(End++,`${e.apiName.snakeCase.unsafeName}-${End}`),hMr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=yIw,f=vIw){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}_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 gTe.parseDocsConfiguration({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(d=>{d.changelog?.files.forEach(c=>{let o=jq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await VTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await WTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=Snd(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=kOi(c,{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ms.of(d)]=l;for(let g of o)t.add(g)}let r=Array.from(t).map(d=>({absoluteFilePath:d,relativeFilePath:this.toRelativeFilepath(d)}));(await this.uploadFiles(r)).forEach(d=>{this.collectedFileIds.set(d.absoluteFilePath,d.fileId)});let i=this.getDocsBasePath();for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=UTu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,k1(i,l)])),{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([d,c])=>{let o=bIw(this.editThisPage,d);a[Ak.PageId(d)]={markdown:c,editThisPageUrl:o?Ak.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let d=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=rT(this.docsWorkspace.absoluteFilePath,c);(await(0,HTa.stat)(o)).isDirectory()?(await tTe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{d.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&d.add(o)})),f=Object.fromEntries(await Promise.all([...d].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,HTa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return rT(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,xnd.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(_Mr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.convertNavigationConfig();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?Ak.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:Ak.Url(n.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(n=>({...n,value:Ak.Url(n.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,playground: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(n=>n.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async convertNavigationConfig(){let t=Zc.V1.SlugGenerator.init(Zc.slugjoin(this.getDocsBasePath()));switch(this.parsedDocsConfig.navigation.type){case"versioned":return{versions:await Promise.all(this.parsedDocsConfig.navigation.versions.map(async n=>{let i=t.setVersionSlug(n.slug??OF(n.version)),a=await this.convertUnversionedNavigationConfig({landingPage:n.landingPage,navigationConfig:n.navigation,parentSlug:i});return{version:Zc.VersionId(n.version),config:a,availability:n.availability!=null?gIw(n.availability):void 0,urlSlugOverride:n.slug}}))};case"untabbed":case"tabbed":return this.convertUnversionedNavigationConfig({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:this.parsedDocsConfig.navigation,parentSlug:t});default:xc(this.parsedDocsConfig.navigation)}}async convertNavigationItem(t,r){switch(t.type){case"page":return{type:"page",title:t.title,icon:t.icon,id:Zc.PageId(this.toRelativeFilepath(t.absolutePath)),urlSlugOverride:t.slug,fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),hidden:t.hidden};case"section":{let n=r.apply({fullSlug:void 0,skipUrlSlug:t.skipUrlSlug,urlSlug:t.slug??OF(t.title)}),i=await Promise.all(t.contents.map(u=>this.convertNavigationItem(u,n))),a=this.toRelativeFilepath(t.overviewAbsolutePath);return{type:"section",title:t.title,items:i,urlSlugOverride:t.slug,collapsed:t.collapsed,icon:t.icon,hidden:t.hidden,skipUrlSlug:t.skipUrlSlug,overviewPageId:a?Zc.PageId(a):void 0,fullSlug:void 0}}case"apiSection":{let n=this.getFernWorkspaceForApiSection(t),i=Pnd(t.snippetsConfiguration),a=await iQ({workspace:n,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}),u=await this.registerApi({ir:a,snippetsConfig:i,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=Dnd(a,u,{oauth:t.playground?.oauth});return{type:"apiV2",node:new VTa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs).get()}}case"link":return{type:"link",icon:t.icon,title:t.text,url:ePi.Url(t.url)};case"changelog":{let n=t.slug??OF(t.title),i=fRr.init(r.get()).append(n),a=new Fan(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,i).convert({parentSlug:r,title:t.title,hidden:t.hidden,slug:t.slug,icon:t.icon}),u=this.toRelativeFilepath(t.changelog[0]);return{type:"changelogV3",node:a??{id:i.append("changelog").get(),type:"changelog",title:t.title,slug:r.append(n).get(),children:[],icon:t.icon,hidden:t.hidden,overviewPageId:u?Zc.PageId(u):void 0,noindex:!1}}}default:xc(t)}}async convertUnversionedNavigationConfig({landingPage:t,navigationConfig:r,parentSlug:n}){let i=t!=null?{id:Zc.PageId(this.toRelativeFilepath(t.absolutePath)),urlSlugOverride:t.slug,fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),hidden:t.hidden,title:t.title,icon:t.icon}:void 0;switch(r.type){case"untabbed":{let a=await Promise.all(r.items.map(u=>this.convertNavigationItem(u,n)));return{landingPage:i,items:a}}case"tabbed":return{landingPage:i,tabs:void 0,tabsV2:await this.convertTabbedNavigation(r.items,n)};default:xc(r)}}async convertTabbedNavigation(t,r){return Promise.all(t.map(async n=>{if(n.child.type==="link")return{type:"link",title:n.title,icon:n.icon,url:ePi.Url(n.child.href)};if(n.child.type==="changelog"){let i=fRr.init(r.get()),a=new Fan(this.markdownFilesToFullSlugs,n.child.changelog,this.docsWorkspace,i).convert({parentSlug:r,title:n.title,icon:n.icon,hidden:n.hidden,slug:n.slug}),u=this.toRelativeFilepath(n.child.changelog[0]);return{type:"changelogV3",node:a??{id:i.append("changelog").get(),type:"changelog",title:n.title,slug:r.append(n.slug??OF(n.title)).get(),children:[],icon:n.icon,hidden:n.hidden,overviewPageId:u?Zc.PageId(u):void 0,noindex:!1}}}if(n.child.type==="layout"){let i=r.apply({skipUrlSlug:n.skipUrlSlug,urlSlug:n.slug??OF(n.title)}),a=await Promise.all(n.child.layout.map(u=>this.convertNavigationItem(u,i)));return{type:"group",title:n.title,icon:n.icon,items:a,urlSlugOverride:n.slug,skipUrlSlug:n.skipUrlSlug,hidden:n.hidden,fullSlug:void 0}}xc(n.child)}))}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):Ak.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:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),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 n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.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($M),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:Ak.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return hKo(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:Ak.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function bIw(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${_Mr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function gIw(e){switch(e){case"beta":return Ak.Availability.Beta;case"deprecated":return Ak.Availability.Deprecated;case"ga":return Ak.Availability.GenerallyAvailable;case"stable":return Ak.Availability.Stable;default:xc(e)}}var B0d=Xo(Nnd(),1),y3u=Xo(H6u(),1),N0d=Xo(require("http"),1),Kqa=Xo(require("path"),1);var usd=require("events"),DCa=Xo(require("fs"),1),$an=Xo(require("path"),1);var Wud=Xo(require("os"),1),Hud=300,bRr=20,e1i=1e7,Qud=Wud.default.platform();var r5w=Qud==="darwin",Q6u=Qud==="win32",gRr=r5w||Q6u,Jud=3e3,Gud=2e4,J6u=1250;var dLt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(dLt||(dLt={}));var Gan;(function(e){e.CHANGE="change",e.RENAME="rename"})(Gan||(Gan={}));var t1i;(function(e){e.CHANGE="change",e.ERROR="error"})(t1i||(t1i={}));var Lm;(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"})(Lm||(Lm={}));var Tk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Tk||(Tk={}));var n5w=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,d=0,c=0,o=()=>{let C=Date.now(),F=C-d,K=C-c,ee=F>=t||K>=a;return[C,ee]},l=C=>{if(c=C,!u)return;let F=u;u=void 0,e.apply(void 0,F)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},P=C=>{if(c=C,n)return l(C)},j=C=>{if(i&&u)return l(C);u=void 0},M=()=>{f=void 0;let[C,F]=o();return F?j(C):q(C)},q=C=>{let F=C-d,K=C-c,ee=t-F,J=a-K,G=Math.min(ee,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[F,K]=o(),ee=!!f;if(u=C,d=F,(K||!f)&&B(t),K)return ee?l(F):P(F)};return I.cancel=g,I.flush=O,I},OCa=n5w;var X6u=Xo(require("fs"),1),wCa=Xo(require("path"),1);var Ax=Xo(require("fs"),1),aQ=require("util");var yMr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},pLt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var G6u=Xo(require("process"),1),$ud=G6u.default.getuid?!G6u.default.getuid():!1,Kud=1e4,Mae=()=>{};var r1i={isChangeErrorOk:e=>{if(!r1i.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!$ud&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!r1i.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(!r1i.isNodeError(e))throw e;if(!r1i.isChangeErrorOk(e))throw e}},K8=r1i;var $6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Kud,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(n),n=()=>t(r);this.add(n)}),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()}}}}},Yud=new $6u;var vMr=(e,t)=>function(n){return function i(...a){return Yud.schedule().then(u=>{let f=c=>(u(),c),d=c=>{if(u(),Date.now()>=n)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(g=>setTimeout(g,o)).then(()=>i.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,d)})}},bMr=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>n)throw u;if(t(u))return i.apply(void 0,a);throw u}}};var i5w={attempt:{chmod:yMr((0,aQ.promisify)(Ax.default.chmod),K8.onChangeError),chown:yMr((0,aQ.promisify)(Ax.default.chown),K8.onChangeError),close:yMr((0,aQ.promisify)(Ax.default.close),Mae),fsync:yMr((0,aQ.promisify)(Ax.default.fsync),Mae),mkdir:yMr((0,aQ.promisify)(Ax.default.mkdir),Mae),realpath:yMr((0,aQ.promisify)(Ax.default.realpath),Mae),stat:yMr((0,aQ.promisify)(Ax.default.stat),Mae),unlink:yMr((0,aQ.promisify)(Ax.default.unlink),Mae),chmodSync:pLt(Ax.default.chmodSync,K8.onChangeError),chownSync:pLt(Ax.default.chownSync,K8.onChangeError),closeSync:pLt(Ax.default.closeSync,Mae),existsSync:pLt(Ax.default.existsSync,Mae),fsyncSync:pLt(Ax.default.fsync,Mae),mkdirSync:pLt(Ax.default.mkdirSync,Mae),realpathSync:pLt(Ax.default.realpathSync,Mae),statSync:pLt(Ax.default.statSync,Mae),unlinkSync:pLt(Ax.default.unlinkSync,Mae)},retry:{close:vMr((0,aQ.promisify)(Ax.default.close),K8.isRetriableError),fsync:vMr((0,aQ.promisify)(Ax.default.fsync),K8.isRetriableError),open:vMr((0,aQ.promisify)(Ax.default.open),K8.isRetriableError),readFile:vMr((0,aQ.promisify)(Ax.default.readFile),K8.isRetriableError),rename:vMr((0,aQ.promisify)(Ax.default.rename),K8.isRetriableError),stat:vMr((0,aQ.promisify)(Ax.default.stat),K8.isRetriableError),write:vMr((0,aQ.promisify)(Ax.default.write),K8.isRetriableError),writeFile:vMr((0,aQ.promisify)(Ax.default.writeFile),K8.isRetriableError),closeSync:bMr(Ax.default.closeSync,K8.isRetriableError),fsyncSync:bMr(Ax.default.fsyncSync,K8.isRetriableError),openSync:bMr(Ax.default.openSync,K8.isRetriableError),readFileSync:bMr(Ax.default.readFileSync,K8.isRetriableError),renameSync:bMr(Ax.default.renameSync,K8.isRetriableError),statSync:bMr(Ax.default.statSync,K8.isRetriableError),writeSync:bMr(Ax.default.writeSync,K8.isRetriableError),writeFileSync:bMr(Ax.default.writeFileSync,K8.isRetriableError)}},Xud=i5w;var PCa=Xo(require("fs"),1),n1i=Xo(require("path"),1);var Zud={then:e=>{e()}};var K6u=()=>{};var Y6u=()=>{let e=K6u,t=K6u,r=!1,n=!1;return{promise:new Promise((d,c)=>{e=o=>(r=!0,d(o)),t=o=>(n=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}};Y6u.wrap=async e=>{let t=Y6u();return await e(t),t.promise};var kud=Y6u;var esd=e=>Array.isArray(e)?e:[e],tsd=e=>typeof e=="function",rsd=()=>{let{promise:e,resolve:t}=kud(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var a5w=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=esd(a).map(It=>tsd(It)?It:cr=>It.test(cr)),f=It=>u.some(cr=>cr(It)),d=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,g={},O=[],P=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,F={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},K={directories:o,directoriesNames:l,directoriesNamesToPaths:g,files:O,filesNames:P,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:ee,increment:J,decrement:G}=rsd(),te=0,Ye=(It,cr,fn,Gt)=>{C.has(cr)||te>=i||(te+=1,It.directories.push(cr),It.directoriesNames.add(fn),o.push(cr),l.add(fn),g.propertyIsEnumerable(fn)||(g[fn]=[]),g[fn].push(cr),C.add(cr),!(Gt>=n)&&(te>=i||or(cr,Gt+1)))},Re=(It,cr,fn)=>{C.has(cr)||te>=i||(te+=1,It.files.push(cr),It.filesNames.add(fn),O.push(cr),P.add(fn),j.propertyIsEnumerable(fn)||(j[fn]=[]),j[fn].push(cr),C.add(cr))},wt=(It,cr,fn,Gt)=>{C.has(cr)||te>=i||(te+=1,It.symlinks.push(cr),It.symlinksNames.add(fn),M.push(cr),q.add(fn),B.propertyIsEnumerable(fn)||(B[fn]=[]),B[fn].push(cr),C.add(cr),r&&(Gt>=n||te>=i||jr(cr,Gt+1)))},Ct=(It,cr,fn,Gt,ln)=>{d.aborted||f(cr)||(Gt.isDirectory()?Ye(It,cr,fn,ln):Gt.isFile()?Re(It,cr,fn):Gt.isSymbolicLink()&&wt(It,cr,fn,ln))},Wt=(It,cr,fn,Gt)=>{if(d.aborted)return;let ln=cr===n1i.default.sep?"":n1i.default.sep,En=fn.name,Ht=`${cr}${ln}${En}`;f(Ht)||(fn.isDirectory()?Ye(It,Ht,En,Gt):fn.isFile()?Re(It,Ht,En):fn.isSymbolicLink()&&wt(It,Ht,En,Gt))},Bt=(It,cr,fn,Gt)=>{for(let ln=0,En=fn.length;ln<En;ln++)Wt(It,cr,fn[ln],Gt)},or=(It,cr)=>{d.aborted||cr>n||te>=i||(J(),PCa.default.readdir(It,{withFileTypes:!0},(fn,Gt)=>{if(fn||d.aborted||!Gt.length)return G();(c(Gt)||Zud).then(()=>{let En=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(En,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),PCa.default.realpath(It,(fn,Gt)=>{if(fn||d.aborted)return G();PCa.default.stat(Gt,async(ln,En)=>{if(ln||d.aborted)return G();let Ht=n1i.default.basename(Gt),tr=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(tr,Gt,Ht,En,cr),G()})})};return(async(It,cr=1)=>(It=n1i.default.normalize(It),C.add(It),or(It,cr),await ee,d.aborted?F:K))(e)},nsd=a5w;var _Lt={lang:{debounce:OCa,attempt:e=>{try{return e()}catch(t){return _Lt.lang.castError(t)}},castArray:e=>_Lt.lang.isArray(e)?e:[e],castError:e=>_Lt.lang.isError(e)?e:_Lt.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(_Lt.lang.isNaN(e))return _Lt.lang.isNaN(t);if(_Lt.lang.isPrimitive(e)||_Lt.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(wCa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?X6u.default.realpathSync.native(e):X6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===wCa.default.sep&&t.length-e.length>wCa.default.sep.length,poll:(e,t=Gud)=>Xud.retry.stat(t)(e,{bigint:!0}).catch(_Lt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await nsd(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=_Lt;var jCa=Xo(require("path"),1);var Z6u=class{constructor(t,r,n){this.base=n,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||yw.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Hud){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,a=async(f,d)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=yw.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(f,d="",c=!1)=>{c?await this.eventsPopulate([d],n,!0):i.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,u]=i,f=r[u];return a===f||a===Lm.CHANGE&&f===Lm.ADD||(r[u]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,i]),u===Lm.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):u===Lm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),u=this.options.limit??e1i,[f,d]=await yw.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...d];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())yw.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Lm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!gRr&&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(Lm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Lm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(jCa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Lm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(jCa.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(Lm.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Lm.ADD?this.onTargetAdd(n):r===Lm.ADD_DIR?this.onTargetAddDir(n):r===Lm.CHANGE?this.onTargetChange(n):r===Lm.UNLINK?this.onTargetUnlink(n):r===Lm.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=Gan.CHANGE,r){if(this.watcher.isClosed())return;let n=jCa.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){Q6u&&t.code==="EPERM"?this.onWatcherChange(Gan.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(t1i.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(t1i.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Gan.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&gRr&&this.options.native!==!1?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),n=this.options.limit??e1i,[i,a]=await yw.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...i,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(Gan.CHANGE,f,t)}))}}},isd=Z6u;var Ck={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ck.intervalId||(Ck.intervalId=setInterval(Ck.resolve,Ck.interval))},reset:()=>{Ck.intervalId&&(clearInterval(Ck.intervalId),delete Ck.intervalId)},add:(e,t)=>{Ck.fns.set(e,Date.now()+t),Ck.init()},remove:e=>{Ck.fns.delete(e)},resolve:()=>{if(!Ck.fns.size)return Ck.reset();let e=Date.now();for(let[t,r]of Ck.fns)r>=e||(Ck.remove(t),t())}},i1i=Ck;var a1i=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=J6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(n||-1,g=>g!==i);if(l&&l!==i){if(yw.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return f();let d=()=>{u.add.delete(n),i1i.remove(c)},c=()=>{d(),f()};i1i.add(c,r);let o=()=>{let l=u.unlink.get(n);if(!l)return;d();let g=l();i===g?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,g,i)};u.add.set(n,o),o()}getLockUnlink(t,r=J6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,i)};if(!n)return f();let d=()=>{u.unlink.delete(n),i1i.remove(c)},c=()=>{d(),f()};i1i.add(c,r);let o=()=>(d(),i);u.unlink.set(n,o),u.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD,dLt.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD_DIR,dLt.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Lm.UNLINK,dLt.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Lm.UNLINK_DIR,dLt.DIR);return this.getLockUnlink({ino:n,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}}};a1i.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};a1i.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var asd=a1i;var k6u=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yw.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(yw.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(yw.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(yw.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return yw.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);yw.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},eIu=k6u;var tIu=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}},osd=tIu;var rIu=class{constructor(){this.inos={},this.paths=new eIu,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await yw.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new osd(n)}reset(){this.inos={},this.paths=new eIu,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Lm.ADD,i),[Lm.ADD];if(i.isDirectory())return this.updateIno(t,Lm.ADD_DIR,i),[Lm.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Lm.UNLINK,n),[Lm.UNLINK];if(n.isDirectory())return this.updateIno(t,Lm.UNLINK_DIR,n),[Lm.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Lm.CHANGE,i),[Lm.CHANGE]);if(i.isDirectory())return this.updateIno(t,Lm.UNLINK,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK,Lm.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD,i),[Lm.UNLINK_DIR,Lm.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK_DIR,Lm.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?dLt.FILE:dLt.DIR;i[t]=[n.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},nIu=rIu;var iIu=class e extends usd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Tk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(Tk.CLOSE,i)),this._readyWait=new Promise(i=>this.on(Tk.READY,i)),this._locker=new asd(this),this._roots=new Set,this._poller=new nIu,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(yw.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(Tk.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(Tk.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(Tk.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Tk.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)yw.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let i in this._watchers)this.watchersClose(i,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,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let a=new isd(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 n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yw.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(f=>f.handler===n&&(!f.filePath||f.filePath===i)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=$an.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??bRr))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&gRr&&o.options.native!==!1)))return!0;if(!gRr)break;let c=$an.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=yw.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,n,i))try{let d=!r.recursive||gRr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:DCa.default.watch(f,d),handler:n,options:r,folderPath:f,filePath:i},l=u=await this.watcherAdd(o,a);if(this._roots.has(i||f)){let O={...r,ignoreInitial:!0,recursive:!1},P=$an.default.dirname(f),j=f;await this.watchDirectories([P],O,n,j,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||gRr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??bRr,f=r.limit??e1i,[d]=await yw.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,a);if(d.length){let o=yw.fs.getDepth(t);for(let l of d){let g=yw.fs.getDepth(l),O=Math.max(0,u-(g-o)),P={...r,depth:O};await this.watchDirectories([l],P,n,i,a||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(c,o)=>{o===t&&(d(),n())},u=new e(a),f=()=>{this._subwatchers.add(i),this.on(Tk.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(Tk.CLOSE,d),u.close()};return f()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=$an.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new nIu,u=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,u(),n())})}async watchPolling(t,r,n){if(this.isClosed())return yw.lang.noop;if(this.pollerExists(t,r))return yw.lang.noop;let i={...r,interval:r.pollingInterval??Jud},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(Tk.CLOSE,f),DCa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(Tk.CLOSE,f),DCa.default.unwatchFile(t,n)};return yw.lang.attempt(u),()=>yw.lang.attempt(f)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=yw.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,d)=>d===u||!yw.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=$an.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await yw.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let a=$an.default.dirname(t);return(await yw.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=yw.lang.noop){if(yw.lang.isFunction(t))return this.watch([],{},t);if(yw.lang.isUndefined(t))return this.watch([],r,n);if(yw.lang.isFunction(r))return this.watch(t,{},r);if(yw.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=yw.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==yw.lang.noop&&this.on(Tk.ALL,n),r.readdirMap=void 0,this.ready())}},ssd=iIu;var hRw=Xo(dsd(),1),yRw=Xo(hIu(),1),vRw=Xo(vIu(),1),bRw=Xo(jIu(),1),SIu=Xo(ccd(),1);var x0d=Xo(O2a(),1),TLt=require("fs/promises"),Gqa=require("os"),f3u=Xo(require("path"),1),T0d=Xo(zne(),1),C0d=Xo(Bpd(),1),d3u=Xo(l3u(),1),lGw="etag",p3u="preview",fGw="bundle",_3u=".fern";function dGw(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u))}function $qa(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u),Ms.of(fGw))}function pGw(){return yf(y_.of((0,Gqa.homedir)()),Ms.of(_3u),Ms.of(p3u),Ms.of(lGw))}async function q0d({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let n=await(0,d3u.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let i=n.body,u=await new C0d.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=pGw();if(r){let B=await Wh(c),I;if(B&&(t.debug("Reading existing ETag"),I=(await(0,TLt.readFile)(c)).toString()),I!=null&&I===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 T0d.default.dir({prefix:"fern"}),l=y_.of(o.path);t.debug(`Downloading docs preview bundle from ${f3u.default.join(e,d)}`);let g=await(0,d3u.fetcher)({url:`${f3u.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=yf(l,Ms.of("output.zip")),P=g.body;if(P==null)return{type:"failure"};let j=Buffer.from(P);await(0,TLt.writeFile)(O,j),t.debug(`Wrote output.zip to ${O}`);let M=dGw();await Wh(M)&&await(0,TLt.rm)(M,{recursive:!0}),await(0,TLt.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let q=$qa();return await(0,TLt.mkdir)(q,{recursive:!0}),await(0,x0d.default)(O,q),await(0,TLt.writeFile)(c,f),t.debug(`Downloaded bundle to ${q}`),{type:"success"}}async function I0d({domain:e,project:t,context:r}){let n=t.docsWorkspaces,i=t.apiWorkspaces;if(n==null)throw new Error("No docs workspace found in project");let a=await Promise.all(i.map(async g=>await g.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),u=new h3u(r),f={},c=await new hMr(e,n,a,r,void 0,async g=>g.map(O=>{let P=izr();return f[P]={type:"url",url:Zc.Url(`/_local${OXo(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:P}}),async g=>u.addReferencedAPI(g)).resolve(),o=U2u({writeShape:c,files:{}}),l=W2u({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 h3u=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=izr(),a=iPi(HDe({ir:t,snippetsConfig:r,playgroundConfig:n}),MU.ApiDefinitionId(i),new San({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=uPi(a);return this.apis[i]=u,i}catch(i){let a=i;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),i}}getAPIsForDefinition(){return this.apis}};var _Gw={pages:{},apis:{},files:{},filesV2:{},config:{navigation:{landingPage:void 0,items:[]},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,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function v3u({initialProject:e,reloadProject:t,validateProject:r,context:n,port:i,bundlePath:a}){if(a!=null)n.logger.info(`Using bundle from path: ${a}`);else try{let I="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(I==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await q0d({bucketUrl:I,logger:n.logger,preferCached:!0})}catch(I){let C=$qa();if(I instanceof Error&&n.logger.debug(`Failed to download latest docs bundle: ${I.message}`),await Wh(C))n.logger.warn("Falling back to cached bundle...");else{n.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,y3u.default)(),d=N0d.default.createServer(f),c=new SIu.default({server:d}),o=new Set;function l(I){for(let C of o)C.send(JSON.stringify(I))}c.on("connection",function(C){o.add(C),C.on("close",function(){o.delete(C)})}),f.use((0,B0d.default)());let g=new URL(_Mr(e.docsWorkspaces?.config.instances[0]?.url??`localhost:${i}`)),O=e,P,j=async()=>{n.logger.info("Reloading docs...");let I=Date.now();try{O=await t(),n.logger.info("Validating docs..."),await r(O);let C=await I0d({domain:`${g.host}${g.pathname}`,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return P==null?n.logger.error("Failed to read docs configuration. Rendering blank page."):n.logger.error("Failed to read docs configuration. Rendering last successful configuration."),C instanceof Error&&C instanceof Error&&C.stack&&n.logger.debug(`${C.message}
|
|
1991
1991
|
${C.stack}`),P}};P=await j();let M=O.apiWorkspaces.flatMap(I=>I.getAbsoluteFilePaths()),q=a?y_.of(Kqa.default.resolve(a)):$qa();new ssd([u,...M],{recursive:!0,ignoreInitial:!0,debounce:1e3,renameDetection:!0}).on("all",async(I,C,F)=>{n.logger.info(nl.dim(`[${I}] ${C}`)),l({version:1,type:"startReload"});let K=await j();K!=null&&(P=K),l({version:1,type:"finishReload"})}),f.post("/v2/registry/docs/load-with-url",async(I,C)=>{try{let F=P??_Gw,K={baseUrl:{domain:g.host,basePath:g.pathname},definition:F,lightModeEnabled:F.config.colorsV3?.type!=="dark"};C.send(K)}catch(F){n.logger.error("Error loading docs",F.message),C.status(500).send()}}),f.get(/^\/_local\/(.*)/,(I,C)=>C.sendFile(`/${I.params[0]}`)),f.get("/",(I,C,F)=>I.headers.upgrade==="websocket"?c.handleUpgrade(I,I.socket,Buffer.alloc(0),K=>{c.emit("connection",K,I)}):F()),f.use("/_next",y3u.default.static(Kqa.default.join(q,"/_next"))),f.use("*",async(I,C)=>C.sendFile(Kqa.default.join(q,"/[[...slug]].html"))),f.listen(i),n.logger.info(`Running server on http://localhost:${i}`),await new Promise(()=>{})}var lQ={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function k2(e,t){return async r=>{r!=null&&await e.docs?.(r,[...t,"docs"])}}async function J2e({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(oFt)&&await t.exampleTypeReference?.(e,r);else if(lS(e))for(let n of Object.values(e))await J2e({example:n,visitor:t,nodePath:r});else if(Array.isArray(e))for(let n of e)await J2e({example:n,visitor:t,nodePath:r})}function tBt(e){return async(t,r,{_default:n,validation:i,location:a}={})=>{await e.typeReference?.({typeReference:t,_default:n,validation:i,location:a,nodePath:r},r)}}async function z0d({service:e,visitor:t,nodePath:r}){await t.httpService?.(e,r),await VP(e,{url:async n=>{await t.serviceBaseUrl?.(n,[...r,"url"])},"base-path":ll,"display-name":ll,availability:ll,headers:async n=>{await R0d({headers:n,visitor:t,nodePath:[...r,"headers"]})},audiences:ll,auth:ll,"path-parameters":async n=>{await Yqa({pathParameters:n,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:async n=>{for(let[i,a]of Object.entries(n)){let u=[...r,"endpoints",i];await hGw({endpointId:i,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:ll,transport:ll,source:ll})}async function hGw({endpointId:e,endpoint:t,service:r,visitor:n,nodePathForEndpoint:i}){let a=tBt(n);await n.httpEndpoint?.({endpointId:e,endpoint:t,service:r},i),await VP(t,{docs:k2(n,i),"display-name":ll,availability:ll,"base-path":ll,path:ll,idempotent:ll,url:async u=>{await n.endpointBaseUrl?.({baseUrl:u,service:r},[...i,"url"])},"path-parameters":async u=>{await Yqa({pathParameters:u,visitor:n,nodePath:[...i,"path-parameters"]})},request:async u=>{if(u==null)return;let f=[...i,"request"];if(typeof u=="string"){await a(u,f,{location:"requestReference"});return}await VP(u,{name:ll,docs:k2(n,f),"query-parameters":async d=>{if(d!=null)for(let[c,o]of Object.entries(d)){let l=[...f,"query-parameters",c];await n.queryParameter?.({queryParameterKey:c,queryParameter:o},l),typeof o=="string"?await a(o,l):await VP(o,{name:ll,docs:k2(n,l),availability:ll,type:async g=>{await a(g,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":ll,audiences:ll,encoding:ll,default:ll,validation:ll})}},"content-type":ll,headers:async d=>{await R0d({headers:d,visitor:n,nodePath:[...f,"headers"]})},body:async d=>{if(d==null)return;let c=[...f,"body"];typeof d=="string"?await a(d,c,{location:"requestReference"}):y6(d)?(await n.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},c),await VP(d,{extends:async o=>{if(o==null)return;let l=typeof o=="string"?[o]:o;for(let g of l){let O=[...c,"extends",g];await n.extension?.(g,O),await a(g,O)}},properties:async o=>{if(o!=null)for(let[l,g]of Object.entries(o)){let O=[...c,"properties",l];typeof g=="string"?await a(g,O,{location:lQ.InlinedRequestProperty}):await VP(g,{name:ll,docs:k2(n,O),availability:ll,type:async P=>{await a(P,[...O,"type"],{location:lQ.InlinedRequestProperty,_default:g.default,validation:g.validation})},"content-type":ll,audiences:ll,encoding:ll,default:ll,validation:ll})}},"extra-properties":ll})):(await k2(n,c)(d.docs),await a(d.type,c))}})},audiences:ll,method:ll,auth:ll,"stream-condition":async u=>{await n.streamCondition?.({streamCondition:u,endpoint:t},[...i,"stream-condition"])},"response-stream":async u=>{u!=null&&(typeof u=="string"?await a(u,[...i,"response-stream"],{location:lQ.StreamingResponse}):await a(u.type,[...i,"response-stream"],{location:lQ.StreamingResponse}))},response:async u=>{if(u==null)return;let f=[...i,"response"];typeof u=="string"?await a(u,f,{location:lQ.Response}):await VP(u,{docs:k2(n,f),type:async d=>{await a(d,[...f,"type"],{location:lQ.Response})},property:ll,"status-code":ll})},errors:async u=>{if(u!=null)for(let f of u){let d=[...i,"errors",typeof f=="string"?f:f.error];typeof f=="string"?await n.errorReference?.(f,d):await VP(f,{docs:k2(n,d),error:async c=>{await n.errorReference?.(c,[...d,"error"])}})}},examples:async u=>{if(u!=null)for(let[f,d]of u.entries())await yGw({nodePathForExample:[...i,{key:"examples",arrayIndex:f}],visitor:n,service:r,endpoint:t,example:d})},pagination:ll})}async function yGw({nodePathForExample:e,visitor:t,service:r,endpoint:n,example:i}){if(i.headers==null&&i["path-parameters"]==null&&i["query-parameters"]==null&&i.request==null&&i.response==null&&i["code-samples"]!=null)return;await t.exampleHttpEndpointCall?.({service:r,endpoint:n,example:i},e);let a=[...e,"headers"];if(await t.exampleHeaders?.({service:r,endpoint:n,examples:i.headers},a),i.headers!=null)for(let o of Object.values(i.headers))await J2e({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(await t.examplePathParameters?.({service:r,endpoint:n,examples:i["path-parameters"]},u),i["path-parameters"]!=null)for(let o of Object.values(i["path-parameters"]))await J2e({example:o,visitor:t,nodePath:u});let f=[...e,"query-parameters"];if(await t.exampleQueryParameters?.({service:r,endpoint:n,examples:i["query-parameters"]},f),i["query-parameters"]!=null)for(let o of Object.values(i["query-parameters"]))await J2e({example:o,visitor:t,nodePath:f});let d=[...e,"request"];await t.exampleRequest?.({service:r,endpoint:n,example:i.request},d),i.request!=null&&await J2e({example:i.request,visitor:t,nodePath:d});let c=[...e,"response"];if(await t.exampleResponse?.({service:r,endpoint:n,example:i.response},c),i.response!=null&&await Etn(n,i.response,{body:async o=>{o.body!=null&&await J2e({example:o.body,visitor:t,nodePath:c}),o.error!=null&&await t.errorReference?.(o.error,[...c,"error"])},stream:async o=>{for(let l of o.stream)await J2e({example:l,visitor:t,nodePath:c})},events:async o=>{for(let{data:l}of o.stream)await J2e({example:l,visitor:t,nodePath:c})}}),i["code-samples"]!=null)for(let[o,l]of i["code-samples"].entries())await t.exampleCodeSample?.({service:r,endpoint:n,example:i,sample:l},[...e,{key:"code-samples",arrayIndex:o}])}async function Yqa({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let n=tBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.pathParameter?.({pathParameterKey:i,pathParameter:a},u),NIn(a)?typeof a=="string"?await t.variableReference?.(a,u):await VP(a,{docs:k2(t,u),variable:async f=>await t.variableReference?.(f,[...u,"variable"]),availability:ll}):typeof a=="string"?await n(a,u):await VP(a,{docs:k2(t,u),type:async f=>{await n(f,[...u,"type"],{_default:a.default,validation:a.validation})},availability:ll,encoding:ll,default:ll,validation:ll,name:ll,audiences:ll})}}async function R0d({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=tBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.header?.({headerKey:i,header:a},u),typeof a=="string"?await n(a,u):await VP(a,{name:ll,availability:ll,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:k2(t,u),audiences:ll,encoding:ll,env:ll,default:ll,validation:ll})}}async function F0d({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];await t.typeName?.(n,a),await b3u({typeName:n,declaration:i,visitor:t,nodePathForType:a})}}async function b3u({typeName:e,declaration:t,visitor:r,nodePathForType:n}){let i=tBt(r);await r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:n},n);let a=async u=>{if(u!=null)for(let[f,d]of u.entries()){let c=[...n,{key:"examples",arrayIndex:f}];await r.exampleType?.({typeName:e,typeDeclaration:t,example:d},c),await J2e({example:d.value,nodePath:c,visitor:r})}};await I8(t,{alias:async u=>{typeof u=="string"?await i(u,n):await VP(u,{type:async f=>{await i(f,[...n,"type"])},docs:k2(r,n),availability:ll,audiences:ll,examples:a,validation:ll,encoding:ll,source:ll})},object:async u=>{await VP(u,{docs:k2(r,n),extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...n,"extends",c];await r.extension?.(c,o),await i(c,o)}},properties:async f=>{if(f!=null)for(let[d,c]of Object.entries(f)){let o=[...n,"properties",d];typeof c=="string"?await i(c,o):await VP(c,{name:ll,docs:k2(r,o),availability:ll,type:async l=>{await i(l,[...o,"type"],{_default:c.default,validation:c.validation})},audiences:ll,encoding:ll,default:ll,validation:ll})}},"extra-properties":ll,availability:ll,audiences:ll,encoding:ll,source:ll,examples:a})},discriminatedUnion:async u=>{await VP(u,{docs:k2(r,n),discriminant:ll,extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...n,"extends",c];await r.extension?.(c,o),await i(c,o)}},union:async f=>{for(let[d,c]of Object.entries(f)){let o=[...n,"union",d];typeof c=="string"?await i(c,o):await VP(c,{docs:k2(r,o),name:ll,key:ll,type:async l=>{typeof l=="string"&&await i(l,[...n,"type"])},"display-name":ll,availability:ll})}},"base-properties":ll,availability:ll,audiences:ll,encoding:ll,source:ll,examples:a})},undiscriminatedUnion:async u=>{await VP(u,{docs:k2(r,n),discriminated:ll,union:async f=>{for(let[d,c]of f.entries()){let o=[...n,`union[${d}]`];typeof c!="string"&&await VP(c,{docs:k2(r,o),type:async l=>{await i(l,[...n,"type"])},"display-name":ll})}},availability:ll,audiences:ll,encoding:ll,source:ll,examples:a})},enum:async u=>{await VP(u,{docs:k2(r,n),enum:async f=>{for(let d of f){let c=[...n,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&await VP(d,{docs:k2(r,c),name:ll,value:ll,casing:ll})}},availability:ll,audiences:ll,default:ll,encoding:ll,source:ll,examples:a})}})}async function L0d({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];await t.errorDeclaration?.({errorName:n,declaration:i},a),await vGw({errorName:n,declaration:i,visitor:t,nodePathForError:a})}}async function vGw({errorName:e,declaration:t,visitor:r,nodePathForError:n}){let i=tBt(r);typeof t=="string"?await i(t,n):await VP(t,{docs:k2(r,n),"status-code":ll,type:async a=>{if(a==null)return;let u=[...n,"type"];typeof a=="string"?await i(a,u):await b3u({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:async a=>{if(a!=null)for(let u of a){let f=[...n,"type"];await r.exampleError?.({errorName:e,declaration:t,example:u},f)}}})}async function U0d({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e))await t.import?.({importPath:i,importedAs:n},[...r,n])}async function V0d({webhook:e,visitor:t,nodePathForWebhook:r}){let n=tBt(t);await VP(e,{"display-name":ll,method:ll,examples:ll,headers:async i=>{await bGw({headers:i,visitor:t,nodePath:[...r,"headers"]})},payload:async i=>{let a=[...r,"payload"];if(typeof i=="string"){await n(i,a,{location:"requestReference"});return}if(gGw(i)){await n(i.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];await t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:i},u),await VP(i,{name:ll,extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...u,"extends",c];await t.extension?.(c,o),await n(c,o)}},properties:async f=>{if(f!=null)for(let[d,c]of Object.entries(f)){let o=[...u,"properties",d];typeof c=="string"?await n(c,o,{location:lQ.InlinedRequestProperty}):await VP(c,{name:ll,docs:k2(t,o),availability:ll,type:async l=>{await n(l,[...o,"type"],{_default:c.default,validation:c.validation,location:lQ.InlinedRequestProperty})},audiences:ll,encoding:ll,default:ll,validation:ll})}}})},audiences:ll,availability:ll,docs:k2(t,r)})}async function bGw({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=tBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.header?.({headerKey:i,header:a},u),typeof a=="string"?await n(a,u):await VP(a,{name:ll,availability:ll,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:k2(t,u),audiences:ll,encoding:ll,env:ll,default:ll,validation:ll})}}function gGw(e){return e.type!=null}async function fQ(e,t){await VP(e,{docs:k2(t,[]),imports:async r=>{await U0d({imports:r,visitor:t,nodePath:["imports"]})},types:async r=>{await F0d({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:async r=>{r!=null&&await z0d({service:r,visitor:t,nodePath:["service"]})},webhooks:async r=>{for(let[n,i]of Object.entries(r??{}))await V0d({webhook:i,visitor:t,nodePathForWebhook:["webhooks",n]})},channel:ll,errors:async r=>{await L0d({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}async function g3u(e,t){await VP(e,{docs:ll,imports:ll,types:ll,service:ll,webhooks:ll,errors:ll,channel:ll,export:async r=>{await t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:async r=>{await t.navigation?.(r,["navigation"])}})}async function m3u(e,t){await t.file?.(e,[]),await VP(e,{version:ll,name:ll,"default-url":ll,"display-name":ll,imports:ll,auth:ll,"idempotency-headers":ll,"auth-schemes":async r=>{await Promise.all(Object.entries(r??{}).map(async([n,i])=>{Tuu(i)&&await t.oauth?.({name:n,oauth:i},["auth-scheme",n])}))},pagination:ll,"default-environment":async r=>{await t.defaultEnvironment?.(r,["default-environment"])},docs:ll,headers:ll,environments:async r=>{if(r!=null)for(let[n,i]of Object.entries(r))await t.environment?.({environmentId:n,environment:i},["environments",n])},"error-discrimination":async r=>{await t.errorDiscrimination?.(r,["error-discrimination"])},audiences:ll,errors:async r=>{if(r!=null)for(let n of r)await t.errorReference?.(n,["errors",n])},"base-path":ll,"path-parameters":async r=>{await Yqa({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:async r=>{if(r!=null)for(let[n,i]of Object.entries(r))await t.variableDeclaration?.({variableId:n,variable:i},["variables",n])}})}var Xqa=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function W0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.definitionFile?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function H0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.packageMarker?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("export"),...i("navigation")}}function Q0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.rootApiFile?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}function mGw(e,t,r){if(!aae(r,t))return[{severity:"error",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function OGw(e){return Number(e.replace("v",""))}async function PGw(e){let t=jpa({token:void 0}),r=await t.generators.getGeneratorByImage({dockerImage:e.name});if(!r.ok||r.body==null)return;let n=await t.generators.versions.getGeneratorRelease(r.body.id,e.version);if(n.ok)return n.body.irVersion}var O3u={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=jpa({token:void 0});if(t==null)return[];let n=await r.generators.cli.getCliRelease(t);if(!n.ok)return[];let i=n.body.irVersion,a;if(e["ir-version"]!=null)a=OGw(e["ir-version"]);else{let f=await PGw(e);if(f==null)return[];a=f}if(a<=i)return[];let u=await r.generators.cli.getMinCliForIr(a);return u.ok?mGw(e.name,u.body.version,t)??[]:[]}}})};var P3u={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(BAr(e.definition)),r=new Set;return t.forEach(n=>{let i=yf(e.definition.absoluteFilePath,Ms.of(n));r.add(i)}),{definitionFile:{import:async({importedAs:n,importPath:i},{relativeFilepath:a})=>{let u=[],f=yf(e.definition.absoluteFilePath,cb(a),Ms.of(i));return r.has(f)||u.push({severity:"error",message:`Import ${nl.bold(n)} points to non-existent path ${nl.bold(i)}.`}),u}}}}};function Zqa(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(BIn(r))for(let n of Object.keys(r.urls))t.includes(n)||t.push(n);return t},[])}var w3u={name:"matching-environment-urls",create:({workspace:e})=>{let t=Zqa(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:n})=>{let i=[],a=u=>{i.push({severity:"error",message:`Environment ${r} is missing URL for ${nl.bold(u)}`})};return NEr(n,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let f of t)u.urls[f]==null&&a(f)}}),i}}}}};var j3u={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=wGw(e.definition.namedDefinitionFiles);return{definitionFile:{import:async({importPath:r},{relativeFilepath:n})=>{let i=t[n];if(i==null)return[];let a=aRr({referencedIn:n,importPath:Ms.of(r)});return i.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 wGw(e){let t={};for(let r of R8t(e))t[r]=J0d(r,[r],e);return t}function J0d(e,t,r){let n=[],i=r[e];if(i==null)return[];if(i.contents.imports!=null)for(let a of Object.values(i.contents.imports)){let u=aRr({referencedIn:e,importPath:Ms.of(a)});t.includes(u)?t[0]===u&&t[0]===jGw(t)&&n.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):n.push(...J0d(u,[...t,u],r))}return n}function jGw(e){return e.reduce((t,r)=>r<t?r:t)}var ex=aLt({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var kqa=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new eM(t)}isTypeComplex(t,r){let n=qO({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:ex,rootApiFile:this.workspace.definition.rootApiFile.contents}),i=this.typeResolver.resolveType({type:t,file:n});if(i==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:i,file:n,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:n}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:n});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":return!1;case"unknown":return!0;default:xc(t)}}isResolvedContainerComplex({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:n})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:n}))&&!(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:n});default:xc(t)}}isNamedTypeComplex({type:t,file:r,visited:n}){if(n.has(t.rawName))return!1;if(n.add(t.rawName),LNr(t.declaration))return!0;if(V6t(t.declaration))return!1;if(mA(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:n});if(RIn(t.declaration)){for(let i of t.declaration.union){let a=typeof i=="string"?i:i.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}xc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:n,visited:i}){return HIt({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:n.definitionFile,workspace:this.workspace,filepathOfDeclaration:n.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:n,visited:i}))}isComplex({type:t,file:r,visited:n}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:n});default:xc(t)}}isComplexContainer({type:t,file:r,visited:n}){switch(t._type){case"literal":return!0;case"map":return this.isComplex({type:t.keyType,file:r,visited:n})||this.isComplex({type:t.valueType,file:r,visited:n});case"optional":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:n});default:xc(t)}}};var D3u={name:"no-complex-query-params",create:({workspace:e})=>{let t=new kqa(e);return{definitionFile:{queryParameter:({queryParameter:r},n)=>{let i=typeof r=="string"?r:r.type,a=t.isTypeComplex(i,n);return a!=null&&a?[{severity:"error",message:`${i} is not a valid type for a query parameter`}]:[]}}}}};var S3u={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===DTa?[{severity:"error",message:`Path parameter ${nl.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function cwi({service:e,endpoint:t}){return e["base-path"]+t.path}var e6a=class{root=new E3u;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 cwi({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},E3u=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[n,...i]=t;if(n==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(n)?this.childPathParam??=new e:this.childPaths[n]??=new e).insert(i,r)}getMatchingEndpoints(t){let[r,...n]=t;if(r==null)return this.endpointsThatEndWithThisNode;let i=[];if(this.isPathParam(r))i.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(n)));else{let a=this.childPaths[r];a!=null&&i.push(...a.getMatchingEndpoints(n))}return this.childPathParam!=null&&i.push(...this.childPathParam.getMatchingEndpoints(n)),i}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var A3u={name:"no-conflicting-endpoint-paths",create:async({workspace:e})=>{let t=new e6a;return await W8(e,async(r,n)=>{await fQ(n,{httpEndpoint:({service:i,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:i,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:n,endpointId:i},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:i,endpoint:n,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${cwi({service:r,endpoint:n})} conflicts with other endpoints:`,...u.map(f=>` - ${f.relativeFilepath} -> ${f.endpointId} ${nl.dim(cwi({service:f.service,endpoint:f.endpoint}))}`)].join(`
|
|
1992
1992
|
`)}]}}}}};var M3u={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:n,relativeFilepath:i})=>{let a=DGw({endpoint:t,service:r,relativeFilepath:i,definitionFile:n,workspace:e}),u=[];for(let[f,d]of Object.entries(a))d.length<=1||u.push({severity:"error",message:`Multiple request properties have the name ${nl.bold(f)}. This is not suitable for code generation. Use the "name" property to deconflict.
|
|
1993
1993
|
`+d.map(c=>` - ${SGw(c)}`).join(`
|