fern-api 0.45.0-rc22 → 0.45.0-rc23
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 +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1812,7 +1812,7 @@ ${l.indent}`:""}${CYc(o)}:${f.indent?" ":""}`;return u=!1,c=!0,f.objectItem=void
|
|
|
1812
1812
|
`}),r.replaceAll(/\n$/g,"")}function Sj1(e){return e?nl.green(LNr.radioOn):LNr.radioOff}var tba=ko(Qje(),1);function avf(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var Uyi=class extends TF{_run(t){this.done=t;let r=AH(this.rl),n=r.line.pipe((0,tba.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,tba.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=`
|
|
1813
1813
|
`+nl.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?nl.cyan(avf(t,this.opt.mask)):nl.italic.dim("[hidden]"):this.opt.mask?avf(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 Tbf=ko(xbf(),1),Cbf=ko(Qje(),1);var Xyi=class extends TF{_run(t){this.done=t,this.editorResult=new Cbf.Subject;let r=AH(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,Tbf.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 Lbf=ko(Bbf(),1);var Rbf=ko(require("readline"),1),Fbf=ko(zbf(),1),Htn=class{constructor(t){this.rl||=Rbf.default.createInterface(yD1(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 yD1(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 Fbf.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Zyi=class extends Htn{constructor(t={}){super(t),this.log=(0,Lbf.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return qyi(this.rl,this.bottomBar.split(`
|
|
1814
1814
|
`).length),this}updateBottomBar(t){return qyi(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+`
|
|
1815
|
-
`}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&&Xva(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Ybf=ko(Wbf(),1),Xbf=ko(Rdu(),1),Zbf=ko($bf(),1),QC=ko(Qje(),1),kbf=ko(Uhi(),1);var Oba=ko(Qje(),1),Kbf=ko(Uhi(),1),Pba=function(e,t,r){return typeof e[t]!="function"?(0,Oba.of)(e):(0,Oba.from)((0,Kbf.default)(e[t])(r).then(n=>(e[t]=n,e)))};var kyi={isPlainObject:Ybf.default,set:Zbf.default,get:Xbf.default},VBn=class extends Htn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=kyi.isPlainObject(r)?{...r}:{},kyi.isPlainObject(t)&&(t=Object.values(t).every(i=>kyi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,QC.from)(t):t;return this.process=n.pipe((0,QC.concatMap)(this.processQuestion.bind(this)),(0,QC.publish)()),this.process.connect(),this.process.pipe((0,QC.reduce)((i,a)=>(kyi.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,QC.defer)(()=>(0,QC.of)(t).pipe((0,QC.concatMap)(this.setDefaultType.bind(this)),(0,QC.concatMap)(this.filterIfRunnable.bind(this)),(0,QC.concatMap)(()=>Pba(t,"message",this.answers)),(0,QC.concatMap)(()=>Pba(t,"default",this.answers)),(0,QC.concatMap)(()=>Pba(t,"choices",this.answers)),(0,QC.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,QC.defer)(()=>(0,QC.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,QC.defer)(()=>(0,QC.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&kyi.get(this.answers,t.name)!==void 0)return(0,QC.empty)();if(t.when===!1)return(0,QC.empty)();if(typeof t.when!="function")return(0,QC.of)(t);let{answers:r}=this;return(0,QC.defer)(()=>(0,QC.from)((0,kbf.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,QC.filter)(n=>n!=null)))}};function egf(e){let t=function(r,n){let i;try{i=new VBn(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",Byi),this.registerPrompt("input",ztn),this.registerPrompt("number",Nyi),this.registerPrompt("confirm",zyi),this.registerPrompt("rawlist",Ryi),this.registerPrompt("expand",Fyi),this.registerPrompt("checkbox",Lyi),this.registerPrompt("password",Uyi),this.registerPrompt("editor",Xyi)},t.restoreDefaultPrompts(),t}var B_u=egf();function ID1(e,t){B_u.registerPrompt(e,t)}function BD1(){B_u.restoreDefaultPrompts()}var ND1={prompt:B_u,ui:{BottomBar:Zyi,Prompt:VBn},createPromptModule:egf,registerPrompt:ID1,restoreDefaultPrompts:BD1,Separator:zie},wba=ND1;var cgf=ko(tgf()),lgf=ko(Kou()),z_u=function(e,t){return z_u=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])},z_u(e,t)};function WBn(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");z_u(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 zD1(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 yC(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 vC(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 fgf(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 R_u="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 RD1(e,t){if(!e)throw new Error(t)}function FD1(e){return e?.replace(/\/+$/,"")}function LD1(e,t){return t===void 0&&(t={}),yC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return vC(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 F_u(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 UD1(){return new Date().getTime()}function rgf(){return new Date().toISOString()}function dgf(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var t0i=String.fromCharCode,ngf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",jba={};function VD1(e,t){if(!jba[e]){jba[e]={};for(var r=0;r<e.length;r++)jba[e][e.charAt(r)]=r}return jba[e][t]}var r0i={compressToBase64:function(e){if(e==null)return"";var t=r0i._compress(e,6,function(r){return ngf.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:r0i._decompress(e.length,32,function(t){return VD1(ngf,e.charAt(t))})},compress:function(e){return r0i._compress(e,16,function(t){return t0i(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,w=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++)w=w<<1,j==t-1?(j=0,a.push(r(w)),w=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)w=w<<1|f,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1,j==t-1?(j=0,a.push(r(w)),w=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)w=w<<1|f,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1;for(;;)if(w=w<<1,j==t-1){a.push(r(w));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:r0i._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,w,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,w=Math.pow(2,2),j=1;j!=w;)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,w=Math.pow(2,8),j=1;j!=w;)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=t0i(g);break;case 1:for(g=0,w=Math.pow(2,16),j=1;j!=w;)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=t0i(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,w=Math.pow(2,d),j=1;j!=w;)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,w=Math.pow(2,8),j=1;j!=w;)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++]=t0i(g),M=f-1,u--;break;case 1:for(g=0,w=Math.pow(2,16),j=1;j!=w;)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++]=t0i(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++)}}},WD1=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}(),HD1=function(e){WBn(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),QD1=function(e){WBn(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 igf(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var pgf=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new WD1,RD1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=FD1(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:igf},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={}),yC(this,void 0,void 0,function(){var u,f;return vC(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={}),yC(this,void 0,void 0,function(){var f,d;return vC(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={}),yC(this,void 0,void 0,function(){var f,d;return vC(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={}),yC(this,void 0,void 0,function(){var u,f=this;return vC(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={}),yC(this,void 0,void 0,function(){return vC(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={}),yC(this,void 0,void 0,function(){var u,f,d,c;return vC(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:rgf()}),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=dgf(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:rgf()},f=F_u(),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(UD1(),"&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(r0i.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 yC(this,void 0,void 0,function(){var u=this;return vC(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,LD1(function(){return yC(u,void 0,void 0,function(){var d,c;return vC(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 QD1(c);case 4:if(d.status<200||d.status>=400)throw new HD1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return yC(this,void 0,void 0,function(){var t;return vC(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(),!igf(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){WBn(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=fgf([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=F_u(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=F_u(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),yC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return vC(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),w=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},w),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),yC(this,void 0,void 0,function(){return vC(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 yC(n,void 0,void 0,function(){var i;return vC(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 yC(i,void 0,void 0,function(){var a;return vC(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})(pgf);var JD1=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}(),_gf=function(e,t){return yC(void 0,void 0,void 0,function(){var r;return vC(this,function(n){switch(n.label){case 0:return[4,lgf.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 yC(void 0,void 0,void 0,function(){return vC(this,function(i){return[2,r.data]})})},json:function(){return yC(void 0,void 0,void 0,function(){return vC(this,function(i){return[2,r.data]})})}}]}})})},GD1=1152921504606847e3,agf=function(e){WBn(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),UZ=function(e){WBn(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),$D1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=zD1(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||_gf,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={}),yC(this,void 0,void 0,function(){var u,f,d,c,o;return vC(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 UZ?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 yC(this,void 0,void 0,function(){var l;return vC(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={}),yC(this,void 0,void 0,function(){var a,u,f,d=this;return vC(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 yC(d,void 0,void 0,function(){var l,g,O;return vC(this,function(w){switch(w.label){case 0:return w.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=w.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=w.sent(),O instanceof UZ||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 UZ("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 UZ("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=fgf([],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 UZ)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var w=O[g],j=o(w);if(j==="break")break}if(d!==void 0)return d;if(f)throw new UZ("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=ygf(d,i,this.cohorts):o=hgf(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&ogf(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=ogf(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),yC(this,void 0,void 0,function(){return vC(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 yC(this,void 0,void 0,function(){var t,r,n,i=this;return vC(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 agf("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 agf)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return yC(this,void 0,void 0,function(){var t,r,n,i,a;return vC(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(R_u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=dgf(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 ogf(e,t,r){r===void 0&&(r="");var n=(0,cgf.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/GD1}function hgf(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new UZ("Operator is_not_set is not supported")}else throw new UZ("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 ugf(String(n))&&String(a).match(String(n))!==null;case"not_regex":return ugf(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=sgf(n),f=sgf(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function ygf(e,t,r){var n=String(e.value);if(!(n in r))throw new UZ("can't match cohort without a given cohort property value");var i=r[n];return vgf(i,t,r)}function vgf(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=vgf(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof UZ)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new UZ("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=ygf(d,t,r):c=hgf(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(w){if(w instanceof UZ)console.debug("Failed to compute property ".concat(d," locally: ").concat(w)),a=!0;else throw w}}if(a)throw new UZ("can't match cohort without a given cohort property value");return n==="AND"}}function ugf(e){try{return new RegExp(e),!0}catch{return!1}}function sgf(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 UZ("".concat(e," is in an invalid date format"))}else throw new UZ("The date provided ".concat(e," must be a string, number, or date object"))}var KD1=30*1e3,YD1=50*1e3,Dba=function(e){WBn(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 JD1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new $D1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:KD1,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||YD1,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):_gf(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return R_u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(R_u)},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 w=0,j=Object.entries(g);w<j.length;w++){var M=j[w],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(L){return g?.[L]!==!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 yC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,w,j,M,q;return vC(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 w=B.sent(),j=w!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:w=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(w),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:w,locally_evaluated:j},q["$feature/".concat(r)]=w,q),groups:f,disableGeoip:o})),[2,w]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return yC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,w,j;return vC(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,w=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:w=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=w!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:w=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(w)]}catch{return[2,w]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return yC(this,void 0,void 0,function(){var a;return vC(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 yC(this,void 0,void 0,function(){var i;return vC(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 yC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,w,j;return vC(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={},w=!0,l&&(g=l.response,O=l.payloads,w=l.fallbackToDecide),w&&!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 yC(this,void 0,void 0,function(){return vC(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 yC(this,void 0,void 0,function(){return vC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(pgf);var Sba=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Dba(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-rc22",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var n0i=class{async sendEvent(){}async identify(){}async flush(){}};var HBn=require("fs/promises"),Ogf=require("os"),Pgf=require("path");var bgf=ko(require("crypto")),Aba=new Uint8Array(256),Eba=Aba.length;function L_u(){return Eba>Aba.length-16&&(bgf.default.randomFillSync(Aba),Eba=0),Aba.slice(Eba,Eba+=16)}var TH=[];for(let e=0;e<256;++e)TH.push((e+256).toString(16).slice(1));function ggf(e,t=0){return TH[e[t+0]]+TH[e[t+1]]+TH[e[t+2]]+TH[e[t+3]]+"-"+TH[e[t+4]]+TH[e[t+5]]+"-"+TH[e[t+6]]+TH[e[t+7]]+"-"+TH[e[t+8]]+TH[e[t+9]]+"-"+TH[e[t+10]]+TH[e[t+11]]+TH[e[t+12]]+TH[e[t+13]]+TH[e[t+14]]+TH[e[t+15]]}var mgf=ko(require("crypto")),U_u={randomUUID:mgf.default.randomUUID};function XD1(e,t,r){if(U_u.randomUUID&&!t&&!e)return U_u.randomUUID();e=e||{};let n=e.random||(e.rng||L_u)();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 ggf(n)}var Ozr=XD1;var ZD1="id",kD1=".fern",i0i=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Dba(r),this.userId=t==null?void 0:Kuu(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-rc22",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(v_.of((0,Ogf.homedir)()),Ms.of(kD1),Ms.of(ZD1));await Wh(t)||(await(0,HBn.mkdir)((0,Pgf.dirname)(t),{recursive:!0}),await(0,HBn.writeFile)(t,Ozr())),this.persistedDistinctId=(await(0,HBn.readFile)(t)).toString()}return this.persistedDistinctId}};var V_u;async function QBn(){return V_u==null&&(V_u=await eS1()),V_u}async function eS1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new n0i;let r=await tpa();return r!=null?new i0i({token:r,posthogApiKey:e}):await epa()!=null?new Sba({posthogApiKey:e}):new i0i({token:void 0,posthogApiKey:e})}catch{return new n0i}}function a0i(e,t){return function(){return e.apply(t,arguments)}}var{toString:tS1}=Object.prototype,{getPrototypeOf:Q_u}=Object,xba=(e=>t=>{let r=tS1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),G6t=e=>(e=e.toLowerCase(),t=>xba(t)===e),Tba=e=>t=>typeof t===e,{isArray:JBn}=Array,o0i=Tba("undefined");function rS1(e){return e!==null&&!o0i(e)&&e.constructor!==null&&!o0i(e.constructor)&&Jje(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Dgf=G6t("ArrayBuffer");function nS1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Dgf(e.buffer),t}var iS1=Tba("string"),Jje=Tba("function"),Sgf=Tba("number"),Cba=e=>e!==null&&typeof e=="object",aS1=e=>e===!0||e===!1,Mba=e=>{if(xba(e)!=="object")return!1;let t=Q_u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},oS1=G6t("Date"),uS1=G6t("File"),sS1=G6t("Blob"),cS1=G6t("FileList"),lS1=e=>Cba(e)&&Jje(e.pipe),fS1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Jje(e.append)&&((t=xba(e))==="formdata"||t==="object"&&Jje(e.toString)&&e.toString()==="[object FormData]"))},dS1=G6t("URLSearchParams"),[pS1,_S1,hS1,yS1]=["ReadableStream","Request","Response","Headers"].map(G6t),vS1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function u0i(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),JBn(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 Egf(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 Qtn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Agf=e=>!o0i(e)&&e!==Qtn;function H_u(){let{caseless:e}=Agf(this)&&this||{},t={},r=(n,i)=>{let a=e&&Egf(t,i)||i;Mba(t[a])&&Mba(n)?t[a]=H_u(t[a],n):Mba(n)?t[a]=H_u({},n):JBn(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&u0i(arguments[n],r);return t}var bS1=(e,t,r,{allOwnKeys:n}={})=>(u0i(t,(i,a)=>{r&&Jje(i)?e[a]=a0i(i,r):e[a]=i},{allOwnKeys:n}),e),gS1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),mS1=(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)},OS1=(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&&Q_u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},PS1=(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},wS1=e=>{if(!e)return null;if(JBn(e))return e;let t=e.length;if(!Sgf(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},jS1=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Q_u(Uint8Array)),DS1=(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])}},SS1=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},ES1=G6t("HTMLFormElement"),AS1=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),wgf=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),MS1=G6t("RegExp"),Mgf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};u0i(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},xS1=e=>{Mgf(e,(t,r)=>{if(Jje(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(Jje(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+"'")})}})},TS1=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return JBn(e)?n(e):n(String(e).split(t)),r},CS1=()=>{},qS1=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,W_u="abcdefghijklmnopqrstuvwxyz",jgf="0123456789",xgf={DIGIT:jgf,ALPHA:W_u,ALPHA_DIGIT:W_u+W_u.toUpperCase()+jgf},IS1=(e=16,t=xgf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function BS1(e){return!!(e&&Jje(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var NS1=e=>{let t=new Array(10),r=(n,i)=>{if(Cba(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=JBn(n)?[]:{};return u0i(n,(u,f)=>{let d=r(u,i+1);!o0i(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},zS1=G6t("AsyncFunction"),RS1=e=>e&&(Cba(e)||Jje(e))&&Jje(e.then)&&Jje(e.catch),Tgf=((e,t)=>e?setImmediate:t?((r,n)=>(Qtn.addEventListener("message",({source:i,data:a})=>{i===Qtn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Qtn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Jje(Qtn.postMessage)),FS1=typeof queueMicrotask<"u"?queueMicrotask.bind(Qtn):typeof process<"u"&&process.nextTick||Tgf,Jl={isArray:JBn,isArrayBuffer:Dgf,isBuffer:rS1,isFormData:fS1,isArrayBufferView:nS1,isString:iS1,isNumber:Sgf,isBoolean:aS1,isObject:Cba,isPlainObject:Mba,isReadableStream:pS1,isRequest:_S1,isResponse:hS1,isHeaders:yS1,isUndefined:o0i,isDate:oS1,isFile:uS1,isBlob:sS1,isRegExp:MS1,isFunction:Jje,isStream:lS1,isURLSearchParams:dS1,isTypedArray:jS1,isFileList:cS1,forEach:u0i,merge:H_u,extend:bS1,trim:vS1,stripBOM:gS1,inherits:mS1,toFlatObject:OS1,kindOf:xba,kindOfTest:G6t,endsWith:PS1,toArray:wS1,forEachEntry:DS1,matchAll:SS1,isHTMLForm:ES1,hasOwnProperty:wgf,hasOwnProp:wgf,reduceDescriptors:Mgf,freezeMethods:xS1,toObjectSet:TS1,toCamelCase:AS1,noop:CS1,toFiniteNumber:qS1,findKey:Egf,global:Qtn,isContextDefined:Agf,ALPHABET:xgf,generateString:IS1,isSpecCompliantForm:BS1,toJSONObject:NS1,isAsyncFn:zS1,isThenable:RS1,setImmediate:Tgf,asap:FS1};function GBn(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(GBn,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 Cgf=GBn.prototype,qgf={};["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=>{qgf[e]={value:e}});Object.defineProperties(GBn,qgf);Object.defineProperty(Cgf,"isAxiosError",{value:!0});GBn.from=(e,t,r,n,i,a)=>{let u=Object.create(Cgf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),GBn.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var zy=GBn;var Igf=ko(pen(),1),qba=Igf.default;function J_u(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function Ngf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function Bgf(e,t,r){return e?e.concat(t).map(function(i,a){return i=Ngf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function LS1(e){return Jl.isArray(e)&&!e.some(J_u)}var US1=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function VS1(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(qba||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(w){if(w===null)return"";if(Jl.isDate(w))return w.toISOString();if(!d&&Jl.isBlob(w))throw new zy("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(w)||Jl.isTypedArray(w)?d&&typeof Blob=="function"?new Blob([w]):Buffer.from(w):w}function o(w,j,M){let q=w;if(w&&!M&&typeof w=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),w=JSON.stringify(w);else if(Jl.isArray(w)&&LS1(w)||(Jl.isFileList(w)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(w)))return j=Ngf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?Bgf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return J_u(w)?!0:(t.append(Bgf(M,j,a),c(w)),!1)}let l=[],g=Object.assign(US1,{defaultVisitor:o,convertValue:c,isVisitable:J_u});function O(w,j){if(!Jl.isUndefined(w)){if(l.indexOf(w)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(w),Jl.forEach(w,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 Pzr=VS1;function zgf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function Rgf(e,t){this._pairs=[],e&&Pzr(e,this,t)}var Fgf=Rgf.prototype;Fgf.append=function(t,r){this._pairs.push([t,r])};Fgf.toString=function(t){let r=t?function(n){return t.call(this,n,zgf)}:zgf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Lgf=Rgf;function WS1(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Jtn(e,t,r){if(!t)return e;let n=r&&r.encode||WS1,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new Lgf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var G_u=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)})}},$_u=G_u;var $Bn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Ugf=ko(require("url"),1),Vgf=Ugf.default.URLSearchParams;var Wgf={isNode:!0,classes:{URLSearchParams:Vgf,FormData:qba,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var X_u={};kc(X_u,{hasBrowserEnv:()=>Y_u,hasStandardBrowserEnv:()=>HS1,hasStandardBrowserWebWorkerEnv:()=>QS1,navigator:()=>K_u,origin:()=>JS1});var Y_u=typeof window<"u"&&typeof document<"u",K_u=typeof navigator=="object"&&navigator||void 0,HS1=Y_u&&(!K_u||["ReactNative","NativeScript","NS"].indexOf(K_u.product)<0),QS1=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",JS1=Y_u&&window.location.href||"http://localhost";var y6={...X_u,...Wgf};function Z_u(e,t){return Pzr(e,new y6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return y6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function GS1(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $S1(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 KS1(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]=$S1(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(GS1(n),i,r,0)}),r}return null}var Iba=KS1;function YS1(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 k_u={transitional:$Bn,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(Iba(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 Z_u(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Pzr(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),YS1(t)):t}],transformResponse:[function(t){let r=this.transitional||k_u.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"?zy.from(f,zy.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:y6.classes.FormData,Blob:y6.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=>{k_u.headers[e]={}});var KBn=k_u;var XS1=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"]),Hgf=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1815
|
+
`}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&&Xva(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Ybf=ko(Wbf(),1),Xbf=ko(Rdu(),1),Zbf=ko($bf(),1),QC=ko(Qje(),1),kbf=ko(Uhi(),1);var Oba=ko(Qje(),1),Kbf=ko(Uhi(),1),Pba=function(e,t,r){return typeof e[t]!="function"?(0,Oba.of)(e):(0,Oba.from)((0,Kbf.default)(e[t])(r).then(n=>(e[t]=n,e)))};var kyi={isPlainObject:Ybf.default,set:Zbf.default,get:Xbf.default},VBn=class extends Htn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=kyi.isPlainObject(r)?{...r}:{},kyi.isPlainObject(t)&&(t=Object.values(t).every(i=>kyi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,QC.from)(t):t;return this.process=n.pipe((0,QC.concatMap)(this.processQuestion.bind(this)),(0,QC.publish)()),this.process.connect(),this.process.pipe((0,QC.reduce)((i,a)=>(kyi.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,QC.defer)(()=>(0,QC.of)(t).pipe((0,QC.concatMap)(this.setDefaultType.bind(this)),(0,QC.concatMap)(this.filterIfRunnable.bind(this)),(0,QC.concatMap)(()=>Pba(t,"message",this.answers)),(0,QC.concatMap)(()=>Pba(t,"default",this.answers)),(0,QC.concatMap)(()=>Pba(t,"choices",this.answers)),(0,QC.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,QC.defer)(()=>(0,QC.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,QC.defer)(()=>(0,QC.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&kyi.get(this.answers,t.name)!==void 0)return(0,QC.empty)();if(t.when===!1)return(0,QC.empty)();if(typeof t.when!="function")return(0,QC.of)(t);let{answers:r}=this;return(0,QC.defer)(()=>(0,QC.from)((0,kbf.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,QC.filter)(n=>n!=null)))}};function egf(e){let t=function(r,n){let i;try{i=new VBn(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",Byi),this.registerPrompt("input",ztn),this.registerPrompt("number",Nyi),this.registerPrompt("confirm",zyi),this.registerPrompt("rawlist",Ryi),this.registerPrompt("expand",Fyi),this.registerPrompt("checkbox",Lyi),this.registerPrompt("password",Uyi),this.registerPrompt("editor",Xyi)},t.restoreDefaultPrompts(),t}var B_u=egf();function ID1(e,t){B_u.registerPrompt(e,t)}function BD1(){B_u.restoreDefaultPrompts()}var ND1={prompt:B_u,ui:{BottomBar:Zyi,Prompt:VBn},createPromptModule:egf,registerPrompt:ID1,restoreDefaultPrompts:BD1,Separator:zie},wba=ND1;var cgf=ko(tgf()),lgf=ko(Kou()),z_u=function(e,t){return z_u=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])},z_u(e,t)};function WBn(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");z_u(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 zD1(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 yC(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 vC(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 fgf(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 R_u="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 RD1(e,t){if(!e)throw new Error(t)}function FD1(e){return e?.replace(/\/+$/,"")}function LD1(e,t){return t===void 0&&(t={}),yC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return vC(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 F_u(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 UD1(){return new Date().getTime()}function rgf(){return new Date().toISOString()}function dgf(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var t0i=String.fromCharCode,ngf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",jba={};function VD1(e,t){if(!jba[e]){jba[e]={};for(var r=0;r<e.length;r++)jba[e][e.charAt(r)]=r}return jba[e][t]}var r0i={compressToBase64:function(e){if(e==null)return"";var t=r0i._compress(e,6,function(r){return ngf.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:r0i._decompress(e.length,32,function(t){return VD1(ngf,e.charAt(t))})},compress:function(e){return r0i._compress(e,16,function(t){return t0i(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,w=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++)w=w<<1,j==t-1?(j=0,a.push(r(w)),w=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)w=w<<1|f,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1,j==t-1?(j=0,a.push(r(w)),w=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)w=w<<1|f,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=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++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)w=w<<1|f&1,j==t-1?(j=0,a.push(r(w)),w=0):j++,f=f>>1;for(;;)if(w=w<<1,j==t-1){a.push(r(w));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:r0i._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,w,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,w=Math.pow(2,2),j=1;j!=w;)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,w=Math.pow(2,8),j=1;j!=w;)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=t0i(g);break;case 1:for(g=0,w=Math.pow(2,16),j=1;j!=w;)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=t0i(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,w=Math.pow(2,d),j=1;j!=w;)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,w=Math.pow(2,8),j=1;j!=w;)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++]=t0i(g),M=f-1,u--;break;case 1:for(g=0,w=Math.pow(2,16),j=1;j!=w;)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++]=t0i(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++)}}},WD1=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}(),HD1=function(e){WBn(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),QD1=function(e){WBn(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 igf(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var pgf=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new WD1,RD1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=FD1(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:igf},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={}),yC(this,void 0,void 0,function(){var u,f;return vC(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={}),yC(this,void 0,void 0,function(){var f,d;return vC(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={}),yC(this,void 0,void 0,function(){var f,d;return vC(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={}),yC(this,void 0,void 0,function(){var u,f=this;return vC(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={}),yC(this,void 0,void 0,function(){return vC(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={}),yC(this,void 0,void 0,function(){var u,f,d,c;return vC(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:rgf()}),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=dgf(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:rgf()},f=F_u(),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(UD1(),"&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(r0i.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 yC(this,void 0,void 0,function(){var u=this;return vC(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,LD1(function(){return yC(u,void 0,void 0,function(){var d,c;return vC(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 QD1(c);case 4:if(d.status<200||d.status>=400)throw new HD1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return yC(this,void 0,void 0,function(){var t;return vC(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(),!igf(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){WBn(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=fgf([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=F_u(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=F_u(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),yC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return vC(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),w=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},w),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),yC(this,void 0,void 0,function(){return vC(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 yC(n,void 0,void 0,function(){var i;return vC(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 yC(i,void 0,void 0,function(){var a;return vC(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})(pgf);var JD1=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}(),_gf=function(e,t){return yC(void 0,void 0,void 0,function(){var r;return vC(this,function(n){switch(n.label){case 0:return[4,lgf.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 yC(void 0,void 0,void 0,function(){return vC(this,function(i){return[2,r.data]})})},json:function(){return yC(void 0,void 0,void 0,function(){return vC(this,function(i){return[2,r.data]})})}}]}})})},GD1=1152921504606847e3,agf=function(e){WBn(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),UZ=function(e){WBn(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),$D1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=zD1(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||_gf,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={}),yC(this,void 0,void 0,function(){var u,f,d,c,o;return vC(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 UZ?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 yC(this,void 0,void 0,function(){var l;return vC(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={}),yC(this,void 0,void 0,function(){var a,u,f,d=this;return vC(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 yC(d,void 0,void 0,function(){var l,g,O;return vC(this,function(w){switch(w.label){case 0:return w.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=w.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=w.sent(),O instanceof UZ||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 UZ("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 UZ("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=fgf([],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 UZ)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var w=O[g],j=o(w);if(j==="break")break}if(d!==void 0)return d;if(f)throw new UZ("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=ygf(d,i,this.cohorts):o=hgf(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&ogf(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=ogf(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),yC(this,void 0,void 0,function(){return vC(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 yC(this,void 0,void 0,function(){var t,r,n,i=this;return vC(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 agf("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 agf)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return yC(this,void 0,void 0,function(){var t,r,n,i,a;return vC(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(R_u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=dgf(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 ogf(e,t,r){r===void 0&&(r="");var n=(0,cgf.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/GD1}function hgf(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new UZ("Operator is_not_set is not supported")}else throw new UZ("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 ugf(String(n))&&String(a).match(String(n))!==null;case"not_regex":return ugf(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=sgf(n),f=sgf(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function ygf(e,t,r){var n=String(e.value);if(!(n in r))throw new UZ("can't match cohort without a given cohort property value");var i=r[n];return vgf(i,t,r)}function vgf(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=vgf(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof UZ)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new UZ("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=ygf(d,t,r):c=hgf(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(w){if(w instanceof UZ)console.debug("Failed to compute property ".concat(d," locally: ").concat(w)),a=!0;else throw w}}if(a)throw new UZ("can't match cohort without a given cohort property value");return n==="AND"}}function ugf(e){try{return new RegExp(e),!0}catch{return!1}}function sgf(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 UZ("".concat(e," is in an invalid date format"))}else throw new UZ("The date provided ".concat(e," must be a string, number, or date object"))}var KD1=30*1e3,YD1=50*1e3,Dba=function(e){WBn(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 JD1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new $D1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:KD1,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||YD1,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):_gf(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return R_u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(R_u)},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 w=0,j=Object.entries(g);w<j.length;w++){var M=j[w],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(L){return g?.[L]!==!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 yC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,w,j,M,q;return vC(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 w=B.sent(),j=w!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:w=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(w),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:w,locally_evaluated:j},q["$feature/".concat(r)]=w,q),groups:f,disableGeoip:o})),[2,w]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return yC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,w,j;return vC(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,w=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:w=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=w!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:w=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(w)]}catch{return[2,w]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return yC(this,void 0,void 0,function(){var a;return vC(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 yC(this,void 0,void 0,function(){var i;return vC(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 yC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,w,j;return vC(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={},w=!0,l&&(g=l.response,O=l.payloads,w=l.fallbackToDecide),w&&!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 yC(this,void 0,void 0,function(){return vC(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 yC(this,void 0,void 0,function(){return vC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(pgf);var Sba=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Dba(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-rc23",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var n0i=class{async sendEvent(){}async identify(){}async flush(){}};var HBn=require("fs/promises"),Ogf=require("os"),Pgf=require("path");var bgf=ko(require("crypto")),Aba=new Uint8Array(256),Eba=Aba.length;function L_u(){return Eba>Aba.length-16&&(bgf.default.randomFillSync(Aba),Eba=0),Aba.slice(Eba,Eba+=16)}var TH=[];for(let e=0;e<256;++e)TH.push((e+256).toString(16).slice(1));function ggf(e,t=0){return TH[e[t+0]]+TH[e[t+1]]+TH[e[t+2]]+TH[e[t+3]]+"-"+TH[e[t+4]]+TH[e[t+5]]+"-"+TH[e[t+6]]+TH[e[t+7]]+"-"+TH[e[t+8]]+TH[e[t+9]]+"-"+TH[e[t+10]]+TH[e[t+11]]+TH[e[t+12]]+TH[e[t+13]]+TH[e[t+14]]+TH[e[t+15]]}var mgf=ko(require("crypto")),U_u={randomUUID:mgf.default.randomUUID};function XD1(e,t,r){if(U_u.randomUUID&&!t&&!e)return U_u.randomUUID();e=e||{};let n=e.random||(e.rng||L_u)();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 ggf(n)}var Ozr=XD1;var ZD1="id",kD1=".fern",i0i=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Dba(r),this.userId=t==null?void 0:Kuu(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-rc23",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(v_.of((0,Ogf.homedir)()),Ms.of(kD1),Ms.of(ZD1));await Wh(t)||(await(0,HBn.mkdir)((0,Pgf.dirname)(t),{recursive:!0}),await(0,HBn.writeFile)(t,Ozr())),this.persistedDistinctId=(await(0,HBn.readFile)(t)).toString()}return this.persistedDistinctId}};var V_u;async function QBn(){return V_u==null&&(V_u=await eS1()),V_u}async function eS1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new n0i;let r=await tpa();return r!=null?new i0i({token:r,posthogApiKey:e}):await epa()!=null?new Sba({posthogApiKey:e}):new i0i({token:void 0,posthogApiKey:e})}catch{return new n0i}}function a0i(e,t){return function(){return e.apply(t,arguments)}}var{toString:tS1}=Object.prototype,{getPrototypeOf:Q_u}=Object,xba=(e=>t=>{let r=tS1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),G6t=e=>(e=e.toLowerCase(),t=>xba(t)===e),Tba=e=>t=>typeof t===e,{isArray:JBn}=Array,o0i=Tba("undefined");function rS1(e){return e!==null&&!o0i(e)&&e.constructor!==null&&!o0i(e.constructor)&&Jje(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Dgf=G6t("ArrayBuffer");function nS1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Dgf(e.buffer),t}var iS1=Tba("string"),Jje=Tba("function"),Sgf=Tba("number"),Cba=e=>e!==null&&typeof e=="object",aS1=e=>e===!0||e===!1,Mba=e=>{if(xba(e)!=="object")return!1;let t=Q_u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},oS1=G6t("Date"),uS1=G6t("File"),sS1=G6t("Blob"),cS1=G6t("FileList"),lS1=e=>Cba(e)&&Jje(e.pipe),fS1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Jje(e.append)&&((t=xba(e))==="formdata"||t==="object"&&Jje(e.toString)&&e.toString()==="[object FormData]"))},dS1=G6t("URLSearchParams"),[pS1,_S1,hS1,yS1]=["ReadableStream","Request","Response","Headers"].map(G6t),vS1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function u0i(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),JBn(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 Egf(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 Qtn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Agf=e=>!o0i(e)&&e!==Qtn;function H_u(){let{caseless:e}=Agf(this)&&this||{},t={},r=(n,i)=>{let a=e&&Egf(t,i)||i;Mba(t[a])&&Mba(n)?t[a]=H_u(t[a],n):Mba(n)?t[a]=H_u({},n):JBn(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&u0i(arguments[n],r);return t}var bS1=(e,t,r,{allOwnKeys:n}={})=>(u0i(t,(i,a)=>{r&&Jje(i)?e[a]=a0i(i,r):e[a]=i},{allOwnKeys:n}),e),gS1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),mS1=(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)},OS1=(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&&Q_u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},PS1=(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},wS1=e=>{if(!e)return null;if(JBn(e))return e;let t=e.length;if(!Sgf(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},jS1=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Q_u(Uint8Array)),DS1=(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])}},SS1=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},ES1=G6t("HTMLFormElement"),AS1=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),wgf=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),MS1=G6t("RegExp"),Mgf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};u0i(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},xS1=e=>{Mgf(e,(t,r)=>{if(Jje(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(Jje(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+"'")})}})},TS1=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return JBn(e)?n(e):n(String(e).split(t)),r},CS1=()=>{},qS1=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,W_u="abcdefghijklmnopqrstuvwxyz",jgf="0123456789",xgf={DIGIT:jgf,ALPHA:W_u,ALPHA_DIGIT:W_u+W_u.toUpperCase()+jgf},IS1=(e=16,t=xgf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function BS1(e){return!!(e&&Jje(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var NS1=e=>{let t=new Array(10),r=(n,i)=>{if(Cba(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=JBn(n)?[]:{};return u0i(n,(u,f)=>{let d=r(u,i+1);!o0i(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},zS1=G6t("AsyncFunction"),RS1=e=>e&&(Cba(e)||Jje(e))&&Jje(e.then)&&Jje(e.catch),Tgf=((e,t)=>e?setImmediate:t?((r,n)=>(Qtn.addEventListener("message",({source:i,data:a})=>{i===Qtn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Qtn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Jje(Qtn.postMessage)),FS1=typeof queueMicrotask<"u"?queueMicrotask.bind(Qtn):typeof process<"u"&&process.nextTick||Tgf,Jl={isArray:JBn,isArrayBuffer:Dgf,isBuffer:rS1,isFormData:fS1,isArrayBufferView:nS1,isString:iS1,isNumber:Sgf,isBoolean:aS1,isObject:Cba,isPlainObject:Mba,isReadableStream:pS1,isRequest:_S1,isResponse:hS1,isHeaders:yS1,isUndefined:o0i,isDate:oS1,isFile:uS1,isBlob:sS1,isRegExp:MS1,isFunction:Jje,isStream:lS1,isURLSearchParams:dS1,isTypedArray:jS1,isFileList:cS1,forEach:u0i,merge:H_u,extend:bS1,trim:vS1,stripBOM:gS1,inherits:mS1,toFlatObject:OS1,kindOf:xba,kindOfTest:G6t,endsWith:PS1,toArray:wS1,forEachEntry:DS1,matchAll:SS1,isHTMLForm:ES1,hasOwnProperty:wgf,hasOwnProp:wgf,reduceDescriptors:Mgf,freezeMethods:xS1,toObjectSet:TS1,toCamelCase:AS1,noop:CS1,toFiniteNumber:qS1,findKey:Egf,global:Qtn,isContextDefined:Agf,ALPHABET:xgf,generateString:IS1,isSpecCompliantForm:BS1,toJSONObject:NS1,isAsyncFn:zS1,isThenable:RS1,setImmediate:Tgf,asap:FS1};function GBn(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(GBn,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 Cgf=GBn.prototype,qgf={};["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=>{qgf[e]={value:e}});Object.defineProperties(GBn,qgf);Object.defineProperty(Cgf,"isAxiosError",{value:!0});GBn.from=(e,t,r,n,i,a)=>{let u=Object.create(Cgf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),GBn.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var zy=GBn;var Igf=ko(pen(),1),qba=Igf.default;function J_u(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function Ngf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function Bgf(e,t,r){return e?e.concat(t).map(function(i,a){return i=Ngf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function LS1(e){return Jl.isArray(e)&&!e.some(J_u)}var US1=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function VS1(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(qba||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(w){if(w===null)return"";if(Jl.isDate(w))return w.toISOString();if(!d&&Jl.isBlob(w))throw new zy("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(w)||Jl.isTypedArray(w)?d&&typeof Blob=="function"?new Blob([w]):Buffer.from(w):w}function o(w,j,M){let q=w;if(w&&!M&&typeof w=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),w=JSON.stringify(w);else if(Jl.isArray(w)&&LS1(w)||(Jl.isFileList(w)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(w)))return j=Ngf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?Bgf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return J_u(w)?!0:(t.append(Bgf(M,j,a),c(w)),!1)}let l=[],g=Object.assign(US1,{defaultVisitor:o,convertValue:c,isVisitable:J_u});function O(w,j){if(!Jl.isUndefined(w)){if(l.indexOf(w)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(w),Jl.forEach(w,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 Pzr=VS1;function zgf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function Rgf(e,t){this._pairs=[],e&&Pzr(e,this,t)}var Fgf=Rgf.prototype;Fgf.append=function(t,r){this._pairs.push([t,r])};Fgf.toString=function(t){let r=t?function(n){return t.call(this,n,zgf)}:zgf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Lgf=Rgf;function WS1(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Jtn(e,t,r){if(!t)return e;let n=r&&r.encode||WS1,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new Lgf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var G_u=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)})}},$_u=G_u;var $Bn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Ugf=ko(require("url"),1),Vgf=Ugf.default.URLSearchParams;var Wgf={isNode:!0,classes:{URLSearchParams:Vgf,FormData:qba,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var X_u={};kc(X_u,{hasBrowserEnv:()=>Y_u,hasStandardBrowserEnv:()=>HS1,hasStandardBrowserWebWorkerEnv:()=>QS1,navigator:()=>K_u,origin:()=>JS1});var Y_u=typeof window<"u"&&typeof document<"u",K_u=typeof navigator=="object"&&navigator||void 0,HS1=Y_u&&(!K_u||["ReactNative","NativeScript","NS"].indexOf(K_u.product)<0),QS1=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",JS1=Y_u&&window.location.href||"http://localhost";var y6={...X_u,...Wgf};function Z_u(e,t){return Pzr(e,new y6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return y6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function GS1(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $S1(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 KS1(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]=$S1(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(GS1(n),i,r,0)}),r}return null}var Iba=KS1;function YS1(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 k_u={transitional:$Bn,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(Iba(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 Z_u(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Pzr(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),YS1(t)):t}],transformResponse:[function(t){let r=this.transitional||k_u.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"?zy.from(f,zy.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:y6.classes.FormData,Blob:y6.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=>{k_u.headers[e]={}});var KBn=k_u;var XS1=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"]),Hgf=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1816
1816
|
`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),n=u.substring(i+1).trim(),!(!r||t[r]&&XS1[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var Qgf=Symbol("internals");function s0i(e){return e&&String(e).trim().toLowerCase()}function Bba(e){return e===!1||e==null?e:Jl.isArray(e)?e.map(Bba):String(e)}function ZS1(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 kS1=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ehu(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 eE1(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function tE1(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 YBn=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(f,d,c){let o=s0i(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]=Bba(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())&&!kS1(t))u(Hgf(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=s0i(t),t){let n=Jl.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return ZS1(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=s0i(t),t){let n=Jl.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||ehu(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(u){if(u=s0i(u),u){let f=Jl.findKey(n,u);f&&(!r||ehu(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||ehu(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]=Bba(i),delete r[a];return}let f=t?eE1(a):String(a).trim();f!==a&&delete r[a],r[f]=Bba(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(`
|
|
1817
1817
|
`)}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[Qgf]=this[Qgf]={accessors:{}}).accessors,i=this.prototype;function a(u){let f=s0i(u);n[f]||(tE1(i,u),n[f]=!0)}return Jl.isArray(t)?t.forEach(a):a(t),this}};YBn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Jl.reduceDescriptors(YBn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Jl.freezeMethods(YBn);var E3=YBn;function c0i(e,t){let r=this||KBn,n=t||r,i=E3.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 l0i(e){return!!(e&&e.__CANCEL__)}function Jgf(e,t,r){zy.call(this,e??"canceled",zy.ERR_CANCELED,t,r),this.name="CanceledError"}Jl.inherits(Jgf,zy,{__CANCEL__:!0});var Gje=Jgf;function HFt(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new zy("Request failed with status code "+r.status,[zy.ERR_BAD_REQUEST,zy.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function thu(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function rhu(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Gtn(e,t){return e&&!thu(t)?rhu(e,t):t}var lmf=ko($gf(),1),fmf=ko(require("http"),1),dmf=ko(require("https"),1),pmf=ko(require("util"),1),_mf=ko(zda(),1),zEr=ko(require("zlib"),1);var $tn="1.7.7";function f0i(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var uE1=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function nhu(e,t,r){let n=r&&r.Blob||y6.classes.Blob,i=f0i(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=uE1.exec(e);if(!a)throw new zy("Invalid URL",zy.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 zy("Blob is not supported",zy.ERR_NOT_SUPPORT);return new n([c],{type:u})}return c}throw new zy("Unsupported protocol "+i,zy.ERR_NOT_SUPPORT)}var Ktn=ko(require("stream"),1);var Kgf=ko(require("stream"),1);var ihu=Symbol("internals"),ahu=class extends Kgf.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[ihu]={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[ihu];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[ihu],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,w)=>{let j=Buffer.byteLength(O);i.bytesSeen+=j,i.bytes+=j,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(O)?process.nextTick(w):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(w)}},g=(O,w)=>{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(()=>{w(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(w,null,M)}:w)};g(t,function O(w,j){if(w)return n(w);j?g(j,O):n(null)})}},ohu=ahu;var hmf=require("events");var Xgf=require("util"),Zgf=require("stream");var{asyncIterator:Ygf}=Symbol,sE1=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Ygf]?yield*e[Ygf]():yield e},Nba=sE1;var cE1=Jl.ALPHABET.ALPHA_DIGIT+"-_",d0i=new Xgf.TextEncoder,wzr=`\r
|
|
1818
1818
|
`,lE1=d0i.encode(wzr),fE1=2,uhu=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)}"`:""}${wzr}`;i?r=d0i.encode(String(r).replace(/\r?\n|\r\n?/g,wzr)):a+=`Content-Type: ${r.type||"application/octet-stream"}${wzr}`,this.headers=d0i.encode(a+wzr),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+fE1,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Jl.isTypedArray(t)?yield t:yield*Nba(t),yield lE1}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},dE1=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+Jl.generateString(i,cE1)}=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=d0i.encode("--"+a+wzr),f=d0i.encode("--"+a+"--"+wzr+wzr),d=f.byteLength,c=Array.from(e.entries()).map(([l,g])=>{let O=new uhu(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),Zgf.Readable.from(async function*(){for(let l of c)yield u,yield*l.encode();yield f}())},kgf=dE1;var emf=ko(require("stream"),1),shu=class extends emf.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)}},tmf=shu;var pE1=(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,rmf=pE1;function _E1(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 nmf=_E1;function hE1(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 imf=hE1;var NEr=(e,t,r=3)=>{let n=0,i=nmf(50,250);return imf(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)},ZBn=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},kBn=e=>(...t)=>Jl.asap(()=>e(...t));var amf={flush:zEr.default.constants.Z_SYNC_FLUSH,finishFlush:zEr.default.constants.Z_SYNC_FLUSH},yE1={flush:zEr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:zEr.default.constants.BROTLI_OPERATION_FLUSH},omf=Jl.isFunction(zEr.default.createBrotliDecompress),{http:vE1,https:bE1}=_mf.default,gE1=/https:?/,umf=y6.protocols.map(e=>e+":"),smf=(e,[t,r])=>(e.on("end",r).on("error",r),t);function mE1(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function ymf(e,t,r){let n=t;if(!n&&n!==!1){let i=(0,lmf.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){ymf(a,t,a.href)}}var OE1=typeof process<"u"&&Jl.kindOf(process)==="process",PE1=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)}),wE1=({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)}},cmf=(e,t)=>wE1(Jl.isObject(e)?e:{address:e,family:t}),vmf=OE1&&function(t){return PE1(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,w;if(f){let or=rmf(f,jr=>Jl.isArray(jr)?jr:[jr]);f=(jr,Vr,It)=>{or(jr,Vr,(cr,Hr,Gt)=>{if(cr)return It(cr);let wn=Jl.isArray(Hr)?Hr.map(An=>cmf(An)):[cmf(Hr,Gt)];Vr.all?It(cr,wn):It(cr,wn[0].address,wn[0].family)})}}let j=new hmf.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 Gje(null,t,w):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=Gtn(t.baseURL,t.url),I=new URL(B,y6.hasBrowserEnv?y6.origin:void 0),C=I.protocol||umf[0];if(C==="data:"){let or;if(l!=="GET")return HFt(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{or=nhu(t.url,c==="blob",{Blob:t.env&&t.env.Blob})}catch(jr){throw zy.from(jr,zy.ERR_BAD_REQUEST,t)}return c==="text"?(or=or.toString(o),(!o||o==="utf8")&&(or=Jl.stripBOM(or))):c==="stream"&&(or=Ktn.default.Readable.from(or)),HFt(n,i,{data:or,status:200,statusText:"OK",headers:new E3,config:t})}if(umf.indexOf(C)===-1)return i(new zy("Unsupported protocol "+C,zy.ERR_BAD_REQUEST,t));let L=E3.from(t.headers).normalize();L.set("User-Agent","axios/"+$tn,!1);let{onUploadProgress:K,onDownloadProgress:te}=t,J=t.maxRate,G,re;if(Jl.isSpecCompliantForm(u)){let or=L.getContentType(/boundary=([-_\w\d]{10,70})/i);u=kgf(u,jr=>{L.set(jr)},{tag:`axios-${$tn}-boundary`,boundary:or&&or[1]||void 0})}else if(Jl.isFormData(u)&&Jl.isFunction(u.getHeaders)){if(L.set(u.getHeaders()),!L.hasContentLength())try{let or=await pmf.default.promisify(u.getLength).call(u);Number.isFinite(or)&&or>=0&&L.setContentLength(or)}catch{}}else if(Jl.isBlob(u))u.size&&L.setContentType(u.type||"application/octet-stream"),L.setContentLength(u.size||0),u=Ktn.default.Readable.from(Nba(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 zy("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",zy.ERR_BAD_REQUEST,t));if(L.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return i(new zy("Request body larger than maxBodyLength limit",zy.ERR_BAD_REQUEST,t))}let Xe=Jl.toFiniteNumber(L.getContentLength());Jl.isArray(J)?(G=J[0],re=J[1]):G=re=J,u&&(K||G)&&(Jl.isStream(u)||(u=Ktn.default.Readable.from(u,{objectMode:!1})),u=Ktn.default.pipeline([u,new ohu({maxRate:Jl.toFiniteNumber(G)})],Jl.noop),K&&u.on("progress",smf(u,ZBn(Xe,NEr(kBn(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&&L.delete("authorization");let Dt;try{Dt=Jtn(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)}L.set("Accept-Encoding","gzip, compress, deflate"+(omf?", br":""),!1);let Ct={path:Dt,method:l,headers:L.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Re,protocol:C,family:d,beforeRedirect:mE1,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,ymf(Ct,t.proxy,C+"//"+I.hostname+(I.port?":"+I.port:"")+Ct.path));let Wt,Bt=gE1.test(Ct.protocol);if(Ct.agent=Bt?t.httpsAgent:t.httpAgent,t.transport?Wt=t.transport:t.maxRedirects===0?Wt=Bt?dmf.default:fmf.default:(t.maxRedirects&&(Ct.maxRedirects=t.maxRedirects),t.beforeRedirect&&(Ct.beforeRedirects.config=t.beforeRedirect),Wt=Bt?bE1:vE1),t.maxBodyLength>-1?Ct.maxBodyLength=t.maxBodyLength:Ct.maxBodyLength=1/0,t.insecureHTTPParser&&(Ct.insecureHTTPParser=t.insecureHTTPParser),w=Wt.request(Ct,function(jr){if(w.destroyed)return;let Vr=[jr],It=+jr.headers["content-length"];if(te||re){let An=new ohu({maxRate:Jl.toFiniteNumber(re)});te&&An.on("progress",smf(An,ZBn(It,NEr(kBn(te),!0,3)))),Vr.push(An)}let cr=jr,Hr=jr.req||w;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(zEr.default.createUnzip(amf)),delete jr.headers["content-encoding"];break;case"deflate":Vr.push(new tmf),Vr.push(zEr.default.createUnzip(amf)),delete jr.headers["content-encoding"];break;case"br":omf&&(Vr.push(zEr.default.createBrotliDecompress(yE1)),delete jr.headers["content-encoding"])}cr=Vr.length>1?Ktn.default.pipeline(Vr,Jl.noop):Vr[0];let Gt=Ktn.default.finished(cr,()=>{Gt(),M()}),wn={status:jr.statusCode,statusText:jr.statusMessage,headers:new E3(jr.headers),config:t,request:Hr};if(c==="stream")wn.data=cr,HFt(n,i,wn);else{let An=[],Ht=0;cr.on("data",function(dn){An.push(dn),Ht+=dn.length,t.maxContentLength>-1&&Ht>t.maxContentLength&&(O=!0,cr.destroy(),i(new zy("maxContentLength size of "+t.maxContentLength+" exceeded",zy.ERR_BAD_RESPONSE,t,Hr)))}),cr.on("aborted",function(){if(O)return;let dn=new zy("maxContentLength size of "+t.maxContentLength+" exceeded",zy.ERR_BAD_RESPONSE,t,Hr);cr.destroy(dn),i(dn)}),cr.on("error",function(dn){w.destroyed||i(zy.from(dn,null,t,Hr))}),cr.on("end",function(){try{let dn=An.length===1?An[0]:Buffer.concat(An);c!=="arraybuffer"&&(dn=dn.toString(o),(!o||o==="utf8")&&(dn=Jl.stripBOM(dn))),wn.data=dn}catch(dn){return i(zy.from(dn,null,t,wn.request,wn))}HFt(n,i,wn)})}j.once("abort",An=>{cr.destroyed||(cr.emit("error",An),cr.destroy())})}),j.once("abort",or=>{i(or),w.destroy(or)}),w.on("error",function(jr){i(zy.from(jr,null,t,w))}),w.on("socket",function(jr){jr.setKeepAlive(!0,1e3*60)}),t.timeout){let or=parseInt(t.timeout,10);if(Number.isNaN(or)){i(new zy("error trying to parse `config.timeout` to int",zy.ERR_BAD_OPTION_VALUE,t,w));return}w.setTimeout(or,function(){if(g)return;let Vr=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",It=t.transitional||$Bn;t.timeoutErrorMessage&&(Vr=t.timeoutErrorMessage),i(new zy(Vr,It.clarifyTimeoutError?zy.ETIMEDOUT:zy.ECONNABORTED,t,w)),q()})}if(Jl.isStream(u)){let or=!1,jr=!1;u.on("end",()=>{or=!0}),u.once("error",Vr=>{jr=!0,w.destroy(Vr)}),u.on("close",()=>{!or&&!jr&&q(new Gje("Request stream has been aborted",t,w))}),u.pipe(w)}else w.end(u)})};var bmf=y6.hasStandardBrowserEnv?function(){let t=y6.navigator&&/(msie|trident)/i.test(y6.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 gmf=y6.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 mmf=e=>e instanceof E3?{...e}:e;function $6t(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(mmf(c),mmf(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 zba=e=>{let t=$6t({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:u,auth:f}=t;t.headers=u=E3.from(u),t.url=Jtn(Gtn(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(y6.hasStandardBrowserEnv||y6.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(y6.hasStandardBrowserEnv&&(n&&Jl.isFunction(n)&&(n=n(t)),n||n!==!1&&bmf(t.url))){let c=i&&a&&gmf.read(a);c&&u.set(i,c)}return t};var jE1=typeof XMLHttpRequest<"u",Omf=jE1&&function(e){return new Promise(function(r,n){let i=zba(e),a=i.data,u=E3.from(i.headers).normalize(),{responseType:f,onUploadProgress:d,onDownloadProgress:c}=i,o,l,g,O,w;function j(){O&&O(),w&&w(),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=E3.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),L={data:!f||f==="text"||f==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:I,config:e,request:M};HFt(function(te){r(te),j()},function(te){n(te),j()},L),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 zy("Request aborted",zy.ECONNABORTED,e,M)),M=null)},M.onerror=function(){n(new zy("Network Error",zy.ERR_NETWORK,e,M)),M=null},M.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",L=i.transitional||$Bn;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),n(new zy(C,L.clarifyTimeoutError?zy.ETIMEDOUT:zy.ECONNABORTED,e,M)),M=null},a===void 0&&u.setContentType(null),"setRequestHeader"in M&&Jl.forEach(u.toJSON(),function(C,L){M.setRequestHeader(L,C)}),Jl.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),f&&f!=="json"&&(M.responseType=i.responseType),c&&([g,w]=NEr(c,!0),M.addEventListener("progress",g)),d&&M.upload&&([l,O]=NEr(d),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",O)),(i.cancelToken||i.signal)&&(o=I=>{M&&(n(!I||I.type?new Gje(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=f0i(i.url);if(B&&y6.protocols.indexOf(B)===-1){n(new zy("Unsupported protocol "+B+":",zy.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var DE1=(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 zy?o:new Gje(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new zy(`timeout ${t} of ms exceeded`,zy.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}},Pmf=DE1;var SE1=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},EE1=async function*(e,t){for await(let r of AE1(e))yield*SE1(r,t)},AE1=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()}},chu=(e,t,r,n)=>{let i=EE1(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 Fba=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",jmf=Fba&&typeof ReadableStream=="function",ME1=Fba&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Dmf=(e,...t)=>{try{return!!e(...t)}catch{return!1}},xE1=jmf&&Dmf(()=>{let e=!1,t=new Request(y6.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),wmf=64*1024,lhu=jmf&&Dmf(()=>Jl.isReadableStream(new Response("").body)),Rba={stream:lhu&&(e=>e.body)};Fba&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Rba[t]&&(Rba[t]=Jl.isFunction(e[t])?r=>r[t]():(r,n)=>{throw new zy(`Response type '${t}' is not supported`,zy.ERR_NOT_SUPPORT,n)})})})(new Response);var TE1=async e=>{if(e==null)return 0;if(Jl.isBlob(e))return e.size;if(Jl.isSpecCompliantForm(e))return(await new Request(y6.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 ME1(e)).byteLength},CE1=async(e,t)=>{let r=Jl.toFiniteNumber(e.getContentLength());return r??TE1(t)},Smf=Fba&&(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}=zba(e);c=c?(c+"").toLowerCase():"text";let O=Pmf([i,a&&a.toAbortSignal()],u),w,j=O&&O.unsubscribe&&(()=>{O.unsubscribe()}),M;try{if(d&&xE1&&r!=="get"&&r!=="head"&&(M=await CE1(o,n))!==0){let L=new Request(t,{method:"POST",body:n,duplex:"half"}),K;if(Jl.isFormData(n)&&(K=L.headers.get("content-type"))&&o.setContentType(K),L.body){let[te,J]=ZBn(M,NEr(kBn(d)));n=chu(L.body,wmf,te,J)}}Jl.isString(l)||(l=l?"include":"omit");let q="credentials"in Request.prototype;w=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(w),I=lhu&&(c==="stream"||c==="response");if(lhu&&(f||I&&j)){let L={};["status","statusText","headers"].forEach(G=>{L[G]=B[G]});let K=Jl.toFiniteNumber(B.headers.get("content-length")),[te,J]=f&&ZBn(K,NEr(kBn(f),!0))||[];B=new Response(chu(B.body,wmf,te,()=>{J&&J(),j&&j()}),L)}c=c||"text";let C=await Rba[Jl.findKey(Rba,c)||"text"](B,e);return!I&&j&&j(),await new Promise((L,K)=>{HFt(L,K,{data:C,headers:E3.from(B.headers),status:B.status,statusText:B.statusText,config:e,request:w})})}catch(q){throw j&&j(),q&&q.name==="TypeError"&&/fetch/i.test(q.message)?Object.assign(new zy("Network Error",zy.ERR_NETWORK,e,w),{cause:q.cause||q}):zy.from(q,q&&q.code,e,w)}});var fhu={http:vmf,xhr:Omf,fetch:Smf};Jl.forEach(fhu,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Emf=e=>`- ${e}`,qE1=e=>Jl.isFunction(e)||e===null||e===!1,Lba={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,!qE1(r)&&(n=fhu[(u=String(r)).toLowerCase()],n===void 0))throw new zy(`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 :
|
|
@@ -1935,7 +1935,7 @@ errors:
|
|
|
1935
1935
|
Run ${nl.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
1936
1936
|
Run ${nl.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),t4n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function cvu({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!pDf(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+=`
|
|
1937
1937
|
${await YB1(f.generatorName)} (${f.apiName!=null?"API: "+f.apiName+", ":""}Group: ${f.generatorGroup}) `+nl.dim(f.currentVersion)+nl.reset(" \u2192 ")+nl.green(f.latestVersion);return i+=`
|
|
1938
|
-
`,n?t4n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function YB1(e){let r=await new dDf.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 XB1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await hDf({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 hDf({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 hDf({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 yDf(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=Lie(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 Yga({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await XB1({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(...yDf(c,d,t.logger));else u.push(...yDf(f.versions,void 0,t.logger))}return u}var X0i=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 M4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var x4n=e=>e!==null&&typeof e=="object";var Z0i=(...e)=>{for(let t of e)if((!x4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return dvu({},...e)},lvu=(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 Xga(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:dvu(e[r]??[],t[r]??[])}var fvu=(e={},t={})=>({beforeRequest:Xga(e,t,"beforeRequest"),beforeRetry:Xga(e,t,"beforeRetry"),afterResponse:Xga(e,t,"afterResponse"),beforeError:Xga(e,t,"beforeError")}),dvu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(x4n(i)){for(let[a,u]of Object.entries(i))x4n(u)&&a in t&&(u=dvu(t[a],u)),t={...t,[a]:u};x4n(i.hooks)&&(n=fvu(n,i.hooks),t.hooks=n),x4n(i.headers)&&(r=lvu(r,i.headers),t.headers=r)}return t};var vDf=(()=>{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})(),bDf=typeof globalThis.AbortController=="function",gDf=typeof globalThis.ReadableStream=="function",mDf=typeof globalThis.FormData=="function",Zga=["get","post","put","patch","head","delete"],ZB1=()=>{};ZB1();var ODf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},kga=2147483647,ema=Symbol("stop"),PDf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wDf={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 DDf=e=>Zga.includes(e)?e.toUpperCase():e,kB1=["get","put","head","delete","options","trace"],e41=[408,413,429,500,502,503,504],t41=[413,429,503],jDf={limit:2,methods:kB1,statusCodes:e41,afterStatusCodes:t41,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},SDf=(e={})=>{if(typeof e=="number")return{...jDf,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{...jDf,...e}};async function pvu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new M4n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function _vu(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 EDf=(e,t)=>{let r={};for(let n in t)!(n in wDf)&&!(n in PDf)&&!(n in e)&&(r[n]=t[n]);return r};var k0i=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>kga)throw new RangeError(`The \`timeout\` option cannot be greater than ${kga}`);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 X0i(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(!gDf)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(ODf))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:lvu(this._input.headers,r.headers),hooks:fvu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:DDf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:SDf(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(bDf){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(vDf&&(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);(mDf&&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 M4n)throw t;if(t instanceof X0i){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),kga);if(this._retryCount<1)throw r;await _vu(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})===ema)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=EDf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):pvu(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 hvu=e=>{let t=(r,n)=>k0i.create(r,Z0i(e,n));for(let r of Zga)t[r]=(n,i)=>k0i.create(n,Z0i(e,i,{method:r}));return t.create=r=>hvu(Z0i(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),hvu(Z0i(e,r))),t.stop=ema,t},r41=hvu(),ADf=r41;var XDf=ko(YDf(),1);function mvu(e){let t=(0,XDf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var NAf=ko(HSf(),1),zAf=ko(BAf(),1),Zvu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},kvu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ebu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??mvu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,NAf.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 ADf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Zvu(e):l}if(t.allVersions)return c;let o=new kvu(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,w]of Object.entries(c.versions))w.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=zAf.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 dvi(e,t){let{version:r}=await ebu(e.toLowerCase(),t);return r}async function F4n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:dvi(e.packageName,{version:t?"prerelease":"latest"})}var RAf=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Pma=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=GA.Info;constructor(t){this.ttyAwareLogger=new Kga(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-rc22"}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 zxe}failWithoutThrowing(t,r){this.didSucceed=!1,Qga({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await QBn()).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 _Df({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1938
|
+
`,n?t4n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function YB1(e){let r=await new dDf.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 XB1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await hDf({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 hDf({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 hDf({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 yDf(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=Lie(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 Yga({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await XB1({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(...yDf(c,d,t.logger));else u.push(...yDf(f.versions,void 0,t.logger))}return u}var X0i=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 M4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var x4n=e=>e!==null&&typeof e=="object";var Z0i=(...e)=>{for(let t of e)if((!x4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return dvu({},...e)},lvu=(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 Xga(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:dvu(e[r]??[],t[r]??[])}var fvu=(e={},t={})=>({beforeRequest:Xga(e,t,"beforeRequest"),beforeRetry:Xga(e,t,"beforeRetry"),afterResponse:Xga(e,t,"afterResponse"),beforeError:Xga(e,t,"beforeError")}),dvu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(x4n(i)){for(let[a,u]of Object.entries(i))x4n(u)&&a in t&&(u=dvu(t[a],u)),t={...t,[a]:u};x4n(i.hooks)&&(n=fvu(n,i.hooks),t.hooks=n),x4n(i.headers)&&(r=lvu(r,i.headers),t.headers=r)}return t};var vDf=(()=>{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})(),bDf=typeof globalThis.AbortController=="function",gDf=typeof globalThis.ReadableStream=="function",mDf=typeof globalThis.FormData=="function",Zga=["get","post","put","patch","head","delete"],ZB1=()=>{};ZB1();var ODf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},kga=2147483647,ema=Symbol("stop"),PDf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wDf={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 DDf=e=>Zga.includes(e)?e.toUpperCase():e,kB1=["get","put","head","delete","options","trace"],e41=[408,413,429,500,502,503,504],t41=[413,429,503],jDf={limit:2,methods:kB1,statusCodes:e41,afterStatusCodes:t41,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},SDf=(e={})=>{if(typeof e=="number")return{...jDf,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{...jDf,...e}};async function pvu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new M4n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function _vu(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 EDf=(e,t)=>{let r={};for(let n in t)!(n in wDf)&&!(n in PDf)&&!(n in e)&&(r[n]=t[n]);return r};var k0i=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>kga)throw new RangeError(`The \`timeout\` option cannot be greater than ${kga}`);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 X0i(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(!gDf)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(ODf))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:lvu(this._input.headers,r.headers),hooks:fvu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:DDf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:SDf(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(bDf){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(vDf&&(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);(mDf&&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 M4n)throw t;if(t instanceof X0i){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),kga);if(this._retryCount<1)throw r;await _vu(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})===ema)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=EDf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):pvu(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 hvu=e=>{let t=(r,n)=>k0i.create(r,Z0i(e,n));for(let r of Zga)t[r]=(n,i)=>k0i.create(n,Z0i(e,i,{method:r}));return t.create=r=>hvu(Z0i(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),hvu(Z0i(e,r))),t.stop=ema,t},r41=hvu(),ADf=r41;var XDf=ko(YDf(),1);function mvu(e){let t=(0,XDf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var NAf=ko(HSf(),1),zAf=ko(BAf(),1),Zvu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},kvu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ebu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??mvu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,NAf.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 ADf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Zvu(e):l}if(t.allVersions)return c;let o=new kvu(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,w]of Object.entries(c.versions))w.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=zAf.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 dvi(e,t){let{version:r}=await ebu(e.toLowerCase(),t);return r}async function F4n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:dvi(e.packageName,{version:t?"prerelease":"latest"})}var RAf=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Pma=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=GA.Info;constructor(t){this.ttyAwareLogger=new Kga(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-rc23"}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 zxe}failWithoutThrowing(t,r){this.didSucceed=!1,Qga({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await QBn()).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 _Df({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1939
1939
|
`)||(r+=`
|
|
1940
1940
|
`),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=PJo(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 H0i(t);return this.ttyAwareLogger.registerTask(r),r}async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw n.failWithoutThrowing(void 0,a),new zxe}finally{n.finish()}return i}async instrumentPostHogEvent(t){(await QBn()).sendEvent(t)}logger=ydi(this.log.bind(this));constructTaskInitForWorkspace(t){let r=FAf(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?FAf(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=RAf[this.numTasks++%RAf.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===P4.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=>$4r.indexOf(n.level)>=$4r.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===GA.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 F4n({cliEnvironment:this.environment,includePreReleases:t}),n=Lie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await Yga({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}};function FAf(e){return`[${e}]:`}var pxf=ko(dxf(),1);async function rDe(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,pxf.default)(t,r,u);return n||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr)),c}function xma(e,{logger:t,...r}={}){return(n,i)=>rDe(t,e,n,{...r,...i})}var Cma=require("fs/promises"),_xf=ko(bne(),1),G81="buf.gen.yaml",hxf="output",$81=`${hxf}/openapi.yaml`,K81=`
|
|
1941
1941
|
version: v1
|
|
@@ -1981,7 +1981,7 @@ ${g}
|
|
|
1981
1981
|
`+Object.keys(t.union).map(B=>` - ${B}`).join(`
|
|
1982
1982
|
`)}];let g=typeof l=="string"?l:l.type;if(typeof g!="string")return pXf(o);let O=n.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&gA(O.declaration))return bzn({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:o,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f});let w=typeof l!="string"&&typeof l.key=="string"?l.key:void 0;if(w==null)return[];let{[w]:j,...M}=o,q=[];return j==null?q.push({message:`Missing property "${w}"`}):q.push(...JH({rawTypeReference:g,example:j,typeResolver:n,exampleResolver:i,file:a,workspace:u,breadcrumbs:f})),q.push(...pXf(M)),q}function pXf(e){return Object.keys(e).map(t=>({severity:"error",message:`Unexpected property "${t}"`}))}function MMa({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}){return Mz(t,{alias:d=>oXf({rawAlias:d,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}),enum:d=>uXf({rawEnum:d,example:a,breadcrumbs:f}),object:d=>bzn({typeName:e,typeNameForBreadcrumb:e,rawObject:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),discriminatedUnion:d=>_Xf({typeName:e,rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),undiscriminatedUnion:d=>sXf({rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f})})}var wXf=/^([+-]?\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)?)?)?)?$/,wDw=/^[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}$/,jDw=/^\d{4}-\d{2}-\d{2}$/;function JH({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}){if(typeof t=="string"&&t.startsWith(RRt)){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?[]:oOi({expected:f,actual:c})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return Ien({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>DDw({primitiveType:f,example:t}),named:f=>{let d=r.getDeclarationOfNamedType({referenceToNamedType:f,file:i});return d==null?[]:MMa({typeName:d.typeName,typeDeclaration:d.declaration,file:d.file,example:t,typeResolver:r,exampleResolver:n,workspace:a,breadcrumbs:u})},map:({keyType:f,valueType:d})=>cS(t)?Object.entries(t).flatMap(([c,o])=>[...JH({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]}),...JH({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]})]):m2e(t,"a map"),list:f=>Array.isArray(t)?t.flatMap((d,c)=>JH({rawTypeReference:f,example:d,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${c}`]})):m2e(t,"a list"),set:f=>{if(!Array.isArray(t))return m2e(t,"a list");let d=aJo(t);return d.length>0?[{severity:"error",message:`Set has duplicate elements:
|
|
1983
1983
|
`+d.map(c=>` - ${JSON.stringify(c)}`).join(`
|
|
1984
|
-
`)}]:t.flatMap((c,o)=>JH({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:JH({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return mDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return mDe(d=>d===f.string,`"${f.string}"`)(t);default:Lc(f)}}}})}function DDw({primitiveType:e,example:t}){return e.v2!=null?XA._visit(e.v2,{integer:r=>SDw({example:t,rules:r.validation}),long:()=>bXf(t),uint:()=>hXf(t),uint64:()=>yXf(t),double:r=>EDw({example:t,rules:r.validation}),float:()=>vXf(t),boolean:()=>gXf(t),string:r=>ADw({example:t,rules:r.validation}),uuid:()=>mXf(t),date:()=>PXf(t),dateTime:()=>OXf(t),base64:()=>mzn(t),bigInteger:()=>mzn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>jXf(t),long:()=>bXf(t),uint:()=>hXf(t),uint64:()=>yXf(t),double:()=>DXf(t),float:()=>vXf(t),boolean:()=>gXf(t),string:()=>mzn(t),uuid:()=>mXf(t),dateTime:()=>OXf(t),date:()=>PXf(t),base64:()=>mzn(t),bigInteger:()=>mzn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function SDw({example:e,rules:t}){let r=jXf(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 EDw({example:e,rules:t}){let r=DXf(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 ADw({example:e,rules:t}){let r=mzn(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 mzn=mDe(e=>typeof e=="string","a string"),jXf=mDe(e=>Number.isInteger(e),"an integer"),hXf=mDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),yXf=mDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),vXf=mDe(e=>typeof e=="number","a float"),DXf=mDe(e=>typeof e=="number","a double"),bXf=mDe(e=>Number.isInteger(e),"an integer"),gXf=mDe(e=>typeof e=="boolean","a boolean"),mXf=mDe(e=>typeof e=="string"&&wDw.test(e),"a UUID"),OXf=mDe(e=>typeof e=="string"&&wXf.test(e),"an ISO 8601 timestamp"),PXf=mDe(e=>typeof e=="string"&&jDw.test(e)&&wXf.test(e),"a date");function mDe(e,t){return r=>e(r)?[]:m2e(r,t)}function oOi({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&&oOi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return oOi({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&&oOi({expected:e.container.keyType,actual:t.container.keyType})&&oOi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:MDw({expected:e.container.literal,actual:t.container.literal});default:Lc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Lc(e)}function MDw({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:Lc(e)}}async function xMa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await F$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:Ozn(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 SXf(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 Ozn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function DTu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return Mz(t,{alias:d=>fS.alias({value:uT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>EXf({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=jin(d);if(!cS(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 fS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:D5r(d).name,wireValue:c}),singleUnionType:TDw({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 fS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:SXf(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(JH({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return fS.undiscriminatedUnion({index:c,singleUnionType:uT({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 uT({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:Ien({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>xDw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!cS(f))throw new Error("Example is not an object");return dO.container(bA.map({map:Object.entries(f).map(([O,w])=>({key:uT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:uT({example:w,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(bA.list({list:f.map(g=>uT({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(bA.set({set:f.map(g=>uT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(bA.optional({optional:f!=null?uT({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(bA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(bA.literal({literal:Pv.string({original:l.string})}));default:Lc(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 w={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:w,shape:DTu({typeName:w,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function xDw({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 EXf({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!cS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return fS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=AXf({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=uT({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:QH({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function AXf({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:uOi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function uOi({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"||!gA(u.declaration))throw new Error("Extension is not of a named object");let f=AXf({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function TDw({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:gzn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:Ez.noProperties()};let l=jTu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!cS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:Ez.singleProperty(uT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!cS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,w=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!gA(w.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:Ez.samePropertiesAsObject({typeId:s1.generateTypeId(j),object:EXf({rawObject:w.declaration,example:O,fileContainingType:w.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:Lc(l)}}async function TMa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=BAr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await F$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function BAr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function CDw(e){let t=JSON.stringify(e);return MXf.default.createHash("sha256").update(t).digest("hex")}function xXf({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=IDw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??CDw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:FDw({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...BDw({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:BAr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:uT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:qDw({queryParameter:g})}}):[],request:NDw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:zDw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function qDw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?EF.exploded():EF.single()}function IDw({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:w})=>{let j=sOi({parameter:O,variableResolver:a,file:u});return{name:g,value:uT({example:w,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 w=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(w!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,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 BDw({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:F9t({headerKey:c,header:l}).name,wireValue:c}),value:uT({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:F9t({headerKey:c,header:g}).name,wireValue:c}),value:uT({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 NDw({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"&&N_i(u)!=null)return;if(!_6(u))return a$.reference(uT({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(!cS(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&&cCe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:QH({propertyKey:d,property:o}).name,wireValue:d}),value:uT({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=uOi({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:QH({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:uT({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 a$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function zDw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?S4.ok(rN.body(void 0)):Nen(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return S4.error({error:w5r({errorName:f.error,file:a}),body:d.declaration.type!=null?uT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return S4.ok(rN.body(RDw({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 S4.ok(rN.stream(f.stream.map(c=>{if(d!=null)return uT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(QM)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return S4.ok(rN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=uT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter(QM)))}})}function RDw({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 uT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function FDw({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 TXf({endpoint:e,file:t,typeResolver:r}){return{body:await LDw({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function LDw({endpoint:e,file:t,typeResolver:r}){let n=await UDw({endpoint:e,file:t,typeResolver:r}),i=await VDw({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Oie.fileDownload({...n});break}case"json":{a=Oie.json({...n.value});break}case"text":{a=Oie.text({...n});break}default:Lc(n)}return w3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return w3.streaming(i)}}async function UDw({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 cCe(a)!=null?w3.fileDownload({docs:i}):z_i(a)!=null?w3.text({docs:i}):await WDw(n,i,t,r)}}async function VDw({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 Sqn(a)?Pie.text({docs:i}):typeof n!="string"&&u==="sse"?Pie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Pie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function WDw(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?w3.json(v6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await nOi({typeResolver:n,file:r,resolvedType:a,property:u})})):w3.json(v6t.response({docs:t,responseBodyType:i}))}async function CXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return nCe.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 qXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return nCe.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 IXf(e){return HDw(e)?{type:"offset",offset:DIt(e.offset),results:qAr(e.results),step:e.step!=null?DIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?qAr(e["has-next-page"]):void 0}:{type:"cursor",cursor:DIt(e.cursor),next_cursor:qAr(e.next_cursor),results:qAr(e.results)}}function HDw(e){return e.offset!=null&&e.results!=null}async function BXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=IXf(i);switch(a.type){case"cursor":return await CXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return qXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:Lc(a)}}function NXf({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=w5r({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function CMa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function zXf({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:CMa({source:e}),name:j5r.generateName(r)}}async function RXf({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return eCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return eCe.http();let i=zXf({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return eCe.grpc({service:i})}async function FXf({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 Pzn({pathParameters:r["path-parameters"],location:tCe.Service,file:n,variableResolver:d}),O=await RXf({file:n,serviceDeclaration:r,sourceResolver:c}),w={fernFilepath:n.fernFilepath};return{availability:uae(r.availability),name:w,displayName:r["display-name"]??void 0,basePath:g2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>O2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:$Dw(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await Pzn({pathParameters:q["path-parameters"],location:tCe.Endpoint,file:n,variableResolver:d}),I={...await F$(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?GDw(q.method):gie.Post,basePath:q["base-path"]!=null?g2e(q["base-path"]):void 0,path:g2e(q.path),fullPath:g2e(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,L])=>await TMa({file:n,queryParameterKey:C,queryParameter:L}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,L])=>O2e({headerKey:C,header:L,file:n}))):[],requestBody:ZYf({request:q.request,file:n}),sdkRequest:await nXf({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await TXf({endpoint:q,file:n,typeResolver:a}),errors:[...NXf({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:xXf({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(L=>aXf({codeSample:L,file:n}))})):[],autogeneratedExamples:[],pagination:await BXf({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=s1.generateEndpointId(w,I),I}))}}async function Pzn({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>QDw({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function QDw({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await F$(t),name:n.casingsGenerator.generateName(e),valueType:JDw({parameter:t,variableResolver:i,file:n}),location:r,variable:d6n(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function JDw({parameter:e,variableResolver:t,file:r}){let n=sOi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function sOi({parameter:e,variableResolver:t,file:r}){let n=qMa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function qMa({parameter:e,variableResolver:t,file:r}){if(d6n(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 GDw(e){switch(e){case"GET":return gie.Get;case"POST":return gie.Post;case"PUT":return gie.Put;case"PATCH":return gie.Patch;case"DELETE":return gie.Delete;default:Lc(e)}}async function O2e({headerKey:e,header:t,file:r}){let{name:n}=F9t({headerKey:e,header:t});return{...await F$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function F9t({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function $Dw(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Lc(e)}}var L$={};kc(L$,{validateObjectExample:()=>bzn,validateTypeExample:()=>MMa,validateTypeReferenceExample:()=>JH});function LXf(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function IMa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function UXf({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:IMa({fernFilePath:i.file.fernFilepath})?void 0:s1.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 VXf({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:IMa({fernFilePath:i.file.fernFilepath})?void 0:s1.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 WXf({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await VXf({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 UXf({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 cOi={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}},STu={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 HXf(e){return{endpoint:e["get-token"].endpoint,requestProperties:KDw({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:YDw({responseProperties:e["get-token"]?.["response-properties"]})}}function QXf(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:XDw({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:ZDw({responseProperties:e["refresh-token"]?.["response-properties"]})}}function KDw({requestProperties:e}){if(e==null)return cOi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?DIt(t):cOi.requestProperties.client_id,client_secret:r!=null?DIt(r):cOi.requestProperties.client_secret,scopes:n!=null?DIt(n):cOi.requestProperties.scopes}}function YDw({responseProperties:e}){return JXf({responseProperties:e,defaultValue:cOi.responseProperties})}function XDw({requestProperties:e}){if(e==null)return STu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?DIt(t):STu.requestProperties.refresh_token}}function ZDw({responseProperties:e}){return JXf({responseProperties:e,defaultValue:STu.responseProperties})}function JXf({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?qAr(r):t.access_token,expires_in:n!=null?qAr(n):t.expires_in,refresh_token:i!=null?qAr(i):t.refresh_token}}async function XXf({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:V7r.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return R_i(e.auth,{single:async a=>{let u=await GXf({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:V7r.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:V7r.Any,schemes:await Promise.all(a.map(async u=>await GXf({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function GXf({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 lau(c,{header:async o=>yH.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=>KXf({file:r,docs:d,rawScheme:o}),bearer:async o=>$Xf({file:r,docs:d,rawScheme:o}),oauth:async o=>await YXf({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return $Xf({file:r,docs:void 0,rawScheme:void 0});case"basic":return KXf({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await YXf({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function $Xf({file:e,docs:t,rawScheme:r}){return yH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function KXf({file:e,docs:t,rawScheme:r}){return yH.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 YXf({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return yH.oauth({docs:t,configuration:W7r.clientCredentials(await WXf({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:HXf(r),refreshTokenEndpoint:QXf(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function ZXf({file:e,rawApiFileSchema:t}){if(t.version!=null)return Q7r.header({header:await kDw({file:e,header:t.version.header}),value:await eSw({file:e,versionDeclaration:t.version})})}async function kDw({file:e,header:t}){return typeof t=="string"?await O2e({file:e,headerKey:t,header:{type:"string"}}):await O2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function eSw({file:e,versionDeclaration:t}){return await xMa({_enum:{default:t.default,enum:t.values},file:e})}async function kXf({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:uae(d.availability),docs:d.docs,origin:d.origin,body:nSw({body:d.body,file:i}),displayName:d["display-name"]});return{availability:uae(e.availability),path:g2e(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])=>O2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await Pzn({pathParameters:e["path-parameters"],location:tCe.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}=BAr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await F$(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=aSw({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:uSw({channel:e,example:f,pathParams:d}),...d,...oSw({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:BAr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:uT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:tSw({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:rSw({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function tSw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?EF.exploded():EF.single()}function rSw({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!sSw(e.body))return m6t.reference(uT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!cS(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:QH({propertyKey:f,property:c}).name,wireValue:f}),value:uT({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=uOi({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:QH({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:uT({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 m6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function nSw({body:e,file:t}){return typeof e=="string"?aCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):iSw(e)?aCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):aCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:jIt(e.extends??[]).map(r=>OU({typeName:r,file:t})),properties:[]})}function iSw(e){return e.type!=null}function aSw({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=sOi({parameter:o,variableResolver:i,file:a});return{name:c,value:uT({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 oSw({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:F9t({headerKey:f,header:c}).name,wireValue:f}),value:uT({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 uSw({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 sSw(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function ETu({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:iEr(n,{singleBaseUrl:()=>_6t.singleBaseUrl(cSw({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>_6t.multipleBaseUrls(lSw({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function cSw({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>iEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:eZf(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function lSw({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>iEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>eZf(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function eZf(e){return e.endsWith("/")?e.slice(0,-1):e}function tZf({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:uT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:w5r({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 rZf="content";function nZf(e,t){if(e==null||e.strategy==="status-code")return b6t.statusCode();switch(e.strategy){case"property":return b6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:rZf,wireValue:rZf})});default:Lc(e)}}function iZf({readme:e,services:t}){let r=new ATu(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 ATu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=dSw({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:fSw(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function fSw(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 dSw({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 aZf({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:s1.generateWebhookId(t.fernFilepath,u),availability:uae(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])=>O2e({headerKey:d,header:c,file:t}))):[],payload:pSw({payload:f.payload,file:t}),examples:f.examples!=null?hSw({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function pSw({payload:e,file:t}){return typeof e=="string"?Sie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):BMa(e)?Sie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Sie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:jIt(e.extends).map(r=>OU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>_Sw({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?uae(n.availability):void 0,file:t})):[]})}function _Sw({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:QH({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function hSw({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:BMa(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:uT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!cS(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:uT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function BMa(e){return e.type!=null}function wzn(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 oZf({name:e,source:t}){return wD.userDefined({file:CMa({source:t}),name:j5r.generateName(e)})}function uZf({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=ySw({type:e.proto.type});if(t!=null)return t}}function ySw({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 sZf({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=P3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&gA(a.declaration)){let u=P3(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 wq.object({extends:jIt(a.declaration.extends).map(d=>OU({typeName:d,file:t})),properties:await rOi({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 cZf({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return kTe(n)?await sZf({generic:n,file:t,typeResolver:r}):wq.alias({aliasOf:t.parseTypeReference(e),resolvedType:vSw({aliasOf:n,file:t,typeResolver:r})})}function vSw({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return vH.primitive(n.originalTypeReference.primitive);case"container":return vH.container(n.originalTypeReference.container);case"unknown":return vH.unknown();case"named":{let i=gA(n.declaration)?g6t.Object:nNr(n.declaration)?g6t.Union:w6t(n.declaration)?g6t.Enum:_6n(n.declaration)?g6t.UndiscriminatedUnion:Lc(n.declaration);return vH.named({name:n.name,shape:i})}}}function lZf({union:e,file:t}){return wq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function fZf(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 xTu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new MTu}){let i=Mz(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=P3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=P3(o.typeName)?.arguments;if(gA(o.declaration)){let g=fZf(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>fZf(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=c$({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=OU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(kTe(o.typeName))continue;a.push(...xTu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var MTu=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 dZf({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await F$(t),d=OU({typeName:e,file:r}),c=xTu({typeDeclaration:t,file:r,typeResolver:n}),o={};gA(t)&&(o=wzn(t.properties??{}));let l=await gSw({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await bSw({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:mSw({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:DTu({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 bSw({typeDeclaration:e,file:t,typeResolver:r}){return await Mz(e,{alias:n=>cZf({alias:n,file:t,typeResolver:r}),object:n=>YYf({object:n,file:t}),discriminatedUnion:n=>dXf({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>lZf({union:n,file:t}),enum:async n=>wq.enum(await xMa({_enum:n,file:t}))})}async function gSw({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=uZf({encoding:t.encoding});if(a!=null)return rEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return rEr.proto(oZf({source:i,name:r}))}function mSw({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?OSw(e.encoding):PSw(t)}function OSw(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function PSw(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function pZf(e,t){let r=t[e];if(r==null)throw new _Sr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function _Zf(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,jSw({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>wSw({endpoint:n,ir:e}))}]))}}function wSw({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>hZf(r,t))}}}function jSw({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>hZf(r,t))}}}return e}function hZf(e,t){let r=TTu(e.typeId,t);return yZf({objectTypeDeclaration:r,ir:t})}function TTu(e,t){let r=pZf(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return TTu(r.shape.resolvedType.name.typeId,t)}throw new _Sr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function yZf({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=TTu(n.typeId,t);return yZf({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var NMa=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=s1.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=s1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=s1.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 zMa=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=DSw(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=s1.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=s1.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=s1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&F5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=s1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])F5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])F5(c.valueType,u,d);for(let c of r.queryParameters)F5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=wzn(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&w5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)CTu(o,u,d);for(let o of c.properties)F5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&_6(n.request.body)){let o=wzn(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{F5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)mie._visit(o,{file:cl,bodyProperty:({valueType:l})=>{F5(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&&w3._visit(r.response.body,{fileDownload:cl,json:c=>{F5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>F5(o.payload,u,d),json:o=>F5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>F5(o.payload,u,d),json:o=>F5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&F5(c.nonStreamResponse.value.responseBodyType,u,d)},text:cl,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(s1.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=s1.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&&Sie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)CTu(d,a,u);for(let d of f.properties)F5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!BMa(n.payload)){let d=wzn(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{F5(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 NMa({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:Lc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(s1.generateSubpackageId(n))}}};function DSw(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Lc(e)}}function F5(e,t,r){iT._visit(e,{container:n=>{SSw(n,t,r)},named:n=>{CTu(n,t,r)},primitive:cl,unknown:cl,_other:cl})}function CTu(e,t,r){t.add(s1.generateTypeId(e)),r.add(e.fernFilepath)}function SSw(e,t,r){jq._visit(e,{list:n=>{F5(n,t,r)},map:n=>{F5(n.keyType,t,r),F5(n.valueType,t,r)},optional:n=>{F5(n,t,r)},set:n=>{F5(n,t,r)},literal:cl,_other:cl})}function bZf({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:_N({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Ez.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=_N({filteredIr:e,exampleTypeReference:r});return n!==void 0?Ez.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function _N({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(bA.list({...n,list:n.list.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(bA.set({...n,set:n.set.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?_N({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(bA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(bA.map({...n,map:n.map.map(i=>{let a=_N({filteredIr:e,exampleTypeReference:i.key}),u=_N({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=_N({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:fS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:fS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:_N({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=bZf({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=_N({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qTu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function ESw({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function vZf({filteredIr:e,headers:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function ASw({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=_N({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=_N({filteredIr:e,exampleTypeReference:r});return n!==void 0?a$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function MSw({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>S4.ok(rN.body(n!=null?_N({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>S4.ok(rN.stream(n.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(QM))),sse:n=>S4.ok(rN.sse(n.map(({event:i,data:a})=>{let u=_N({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter(QM))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>S4.error({error:r,body:n!=null?_N({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function ITu({filteredIr:e,example:t}){return{...t,rootPathParameters:qTu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qTu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qTu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:vZf({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:vZf({filteredIr:e,headers:t.endpointHeaders}),queryParameters:ESw({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?ASw({filteredIr:e,requestBody:t.request}):void 0,response:MSw({filteredIr:e,response:t.response})}}function gZf({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:fS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:fS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:_N({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=bZf({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:fS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=_N({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:fS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var RMa=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:s1.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(!mZf(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(!mZf(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=s1.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 mZf(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 OZf({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:P5r({referencedIn:t,importPath:f})}}var Din=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 Rz(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:j5r,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 Nrn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:j5r,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 F_i().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=OZf({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(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 Sin=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=gDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(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 ODe=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(cS(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(`\\${RRt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(RRt))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(RRt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(RRt.length),exampleName:i}}};var FMa=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:wie.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:wie.query(await TMa({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:wie.body(u)}}if(_6(n.body)){let u=await PTu({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:wie.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:wie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await OTu({typeResolver:this.typeResolver,file:iOi(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 PZf=require("fs/promises"),LMa=class{async parse({absoluteFilePath:t}){let r=await(0,PZf.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 UMa=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(Oua(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 Oua(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 LMa().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 ZA=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=gDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=P3(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 c$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:iT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:iT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:iT.container(jq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:iT.container(jq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:iT.container(jq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:iT.container(jq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:iT.container(jq.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(p6n(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=AMa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||Qie(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 EIt=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:IAr({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 VMa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function wZf({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:Lc(t.v1)}}function jZf({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return S5r({containerType:t});switch(t.type){case"list":{let u=UF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:bA.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 S5r({containerType:t});let u=UF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=UF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=UF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=UF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:Lc(t)}}function S5r({containerType:e}){switch(e.type){case"list":return{type:"success",example:bA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:bA.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:bA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:bA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:bA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Lc(e)}}function jzn({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 SZf({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=UF({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:fS.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:fS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=DZf({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:fS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=UF({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:fS.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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.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=DZf({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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=UF({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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.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 DZf({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=UF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!jzn({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:fS.object({properties:d}),jsonExample:f}}function UF({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=SZf({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=jZf({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=S5r({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}=wZf({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 EZf=ko(umu(),1);function lOi({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:S4.ok(rN.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=UF({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&&jzn({typeDeclarations:n,typeReference:c.valueType}))continue;let o=UF({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?EF.exploded():EF.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&&jzn({typeDeclarations:n,typeReference:o.valueType}))continue;let l=UF({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=UF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!jzn({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:w}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=w}u.request=a$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=UF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=a$.reference(o);break}default:Lc(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=UF({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=S4.ok(rN.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:Lc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=S4.error({body:void 0,error:a.declaration.name});else{let c=UF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=S4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,EZf.default)(u),url:xSw(t,u),...u},jsonExample:void 0}}function xSw(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 GH({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,audiences:u,readme:f,packageName:d,version:c,context:o}){let l=z9t({generationLanguage:r,keywords:n,smartCasing:i}),g=new zMa(u),O=IAr({casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents}),w=(t.definition.rootApiFile.contents.errors??[]).map(Hr=>({error:w5r({errorName:Hr,file:O}),docs:void 0})),j=new ZA(t),M=new Din(t),q=new FMa(j,M),B=new Sin(t),I=new ODe(j),C=new EIt,L=new UMa(o,t),K={fdrApiDefinitionId:e,apiVersion:await ZXf({file:O,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:l.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await jMa(t.definition.rootApiFile.contents.docs),auth:await XXf({rawApiFileSchema:t.definition.rootApiFile.contents,file:O,propertyResolver:q,endpointResolver:M}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Hr,Gt])=>O2e({headerKey:Hr,header:Gt,file:O}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Hr,Gt])=>O2e({headerKey:Hr,header:Gt,file:O}))):[],types:{},errors:{},services:{},constants:LXf(l),environments:ETu({casingsGenerator:l,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:nZf(t.definition.rootApiFile.contents["error-discrimination"],O),basePath:t.definition.rootApiFile.contents["base-path"]!=null?g2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await Pzn({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:O,location:tCe.Root,variableResolver:C}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Hr,Gt])=>({docs:typeof Gt!="string"?Gt.docs:void 0,id:Hr,name:O.casingsGenerator.generateName(Hr),type:O.parseTypeReference(Gt)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},te=new RMa,J=async Hr=>{te.addSubpackage(Hr.fernFilepath),await VP(Hr.definitionFile,{imports:cl,docs:Gt=>{Gt!=null&&te.addDocs(Hr.fernFilepath,Gt)},types:async Gt=>{if(Gt!=null)for(let[wn,An]of Object.entries(Gt)){if(kTe(wn))continue;let Ht=await dZf({typeName:wn,typeDeclaration:An,file:Hr,typeResolver:j,exampleResolver:I,sourceResolver:L,workspace:t}),er=Ht.typeDeclaration;a&&(er.userProvidedExamples=[],er.autogeneratedExamples=[]);let dn=Ht.descendantFilepaths,fn=s1.generateTypeId(er.name);K.types[fn]=er,te.addType(fn,er),g.addType({declaredTypeName:er.name,descendantTypeIds:er.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Ht.propertiesByAudience,descendantFilepaths:dn}),g.markTypeForAudiences(er.name,KYf(An))}},errors:Gt=>{if(Gt==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[An,Ht]of Object.entries(Gt)){let er=tZf({errorName:An,errorDeclaration:Ht,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),dn=s1.generateErrorId(er.name);K.errors[dn]=er,te.addError(dn,er),g.addError(er)}},service:async Gt=>{if(Gt==null)return;let wn=await FXf({rootDefaultUrl:Hr.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:K.pathParameters,serviceDefinition:Gt,file:Hr,errorResolver:B,typeResolver:j,propertyResolver:q,exampleResolver:I,sourceResolver:L,globalErrors:w,variableResolver:C,workspace:t}),An=s1.generateServiceId(wn.name);K.services[An]=wn,te.addService(An,wn);let Ht={};wn.endpoints.forEach(er=>{a&&(er.autogeneratedExamples=[],er.userSpecifiedExamples=[]);let dn=Gt.endpoints[er.name.originalName];g.addEndpoint(wn,er,dn),Ht[er.name.originalName]=er}),Gt.audiences!=null&&g.markEndpointForAudience(wn.name,wn.endpoints,Gt.audiences),Object.entries(Gt.endpoints).map(([er,dn])=>{let fn=Ht[er];fn!=null&&dn.audiences!=null&&g.markEndpointForAudience(wn.name,[fn],dn.audiences)})},webhooks:async Gt=>{if(Gt==null)return;let wn=s1.generateWebhookGroupId(Hr.fernFilepath),An=await aZf({webhooks:Gt,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),Ht={};for(let er of An)Ht[er.name.originalName]=er;Object.entries(Gt).forEach(([er,dn])=>{let fn=Ht[er];fn!=null&&(g.addWebhook(Hr,fn,dn),dn.audiences!=null&&g.markWebhookForAudiences(Hr,fn,dn.audiences))}),K.webhookGroups[wn]=An,te.addWebhookGroup(wn,Hr.fernFilepath)},channel:async Gt=>{if(Gt==null)return;let wn=s1.generateWebSocketChannelId(Hr.fernFilepath),An=await kXf({channel:Gt,file:Hr,variableResolver:C,typeResolver:j,exampleResolver:I,workspace:t});K.websocketChannels!=null&&(K.websocketChannels[wn]=An,te.addWebSocketChannel(wn,Hr.fernFilepath))}})};await Rz(t,async(Hr,Gt,wn)=>{await J(qO({relativeFilepath:Hr,definitionFile:Gt,casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:wn.defaultUrl}))}),await Nrn(t,async(Hr,Gt)=>{if(Gt.navigation!=null)if(typeof Gt.navigation=="string")te.addPackageRedirection({from:oae({relativeFilepath:Hr,casingsGenerator:l}),to:oae({relativeFilepath:yf(cb(Hr),Ms.of(Gt.navigation)),casingsGenerator:l})});else{let wn=Gt.navigation.map(An=>s1.generateSubpackageId(oae({relativeFilepath:yf(cb(Hr),Ms.of(An)),casingsGenerator:l})));Hr===JA?te.sortRootPackage(wn):te.sortSubpackage(s1.generateSubpackageId(oae({relativeFilepath:Hr,casingsGenerator:l})),wn)}}),K.serviceTypeReferenceInfo=CSw(g);let G=a?K:TSw(K,o),re=t.definition.rootApiFile.contents,Xe=ETu({casingsGenerator:l,rawApiFileSchema:re}),Re=Xe?.environments._visit({singleBaseUrl:Hr=>Hr.environments.filter(Gt=>VMa(Gt.id,re.environments)!=null).length===0,multipleBaseUrls:Hr=>Hr.environments.filter(Gt=>VMa(Gt.id,re.environments)!=null).length===0,_other:()=>!1});Xe?.environments.environments.forEach(Hr=>{g.markEnvironmentForAudiences(Hr,VMa(Hr.id,re.environments)??[],Re)});let Dt=g.hasNoAudiences()?void 0:g.build(),Ct=qSw(G,Dt),Wt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Ct.services).every(Hr=>Hr.endpoints.every(Gt=>Gt.auth)),Bt=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="streaming")),or=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.pagination!=null)),jr=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="fileDownload")),Vr=f!=null?iZf({readme:f,services:K.services}):void 0,{types:It,services:cr}=_Zf(Ct);return{...Ct,...te.build(Dt),types:It,services:cr,sdkConfig:{isAuthMandatory:Wt,hasStreamingEndpoints:Bt,hasPaginatedEndpoints:or,hasFileDownloadEndpoints:jr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:c!=null&&d!=null?{header:"User-Agent",value:`${d}/${c}`}:void 0}},readmeConfig:Vr}}function TSw(e,t){for(let[r,n]of Object.entries(e.services))for(let i of n.endpoints){t.logger.debug(`Generating example for ${i.id}`);let a=lOi({ir:e,service:n,endpoint:i,typeDeclarations:e.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(a.type==="failure"){t.logger.debug(`Failed to generate example for ${i.id}. ${a.message}`);continue}let{example:u}=a;i.autogeneratedExamples=[{example:u}]}return e}function CSw(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 qSw(e,t){if(t==null)return e;let r=xZr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>gZf({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:wq.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:xZr(e.errors,u=>t.hasError(u)),services:by(xZr(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:ITu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?ITu({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:ISw(e.serviceTypeReferenceInfo,t)}}function ISw(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 RZf=ko(bMa(),1),FZf=ko(gMa(),1),JMa=require("fs/promises"),LZf=ko(hAa(),1);function L9t(e){return typeof e.subpackageId=="string"}function PDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Ein(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var BTu="__package__",E5r=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 L9t(t)?t.subpackageId:BTu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=LF.SubpackageId(t);return r===BTu?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=LF.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} ${PDe(u.path.parts)}`),d.push(`${o} ${Ein(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,PDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ein(u.path.parts))}`);let g=AZf(l);g!=null&&(d.push(`${o} ${k1(g,PDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ein(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} ${PDe(u.path.parts)}`),d.push(`${o} ${Ein(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,PDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ein(u.path.parts))}`);let g=AZf(l);g!=null&&(d.push(`${o} ${k1(g,PDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ein(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.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let n=L9t(t)?[...r,t.name]:r,i=n.length===0?[BTu]: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.#d(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.#d(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 Yc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Yc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Yc.WebhookId(`${r}.${t.id}`)}};function AZf(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 Dzn=ko(bMa(),1),xZf=ko(gMa(),1);function MZf(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{}}Dzn.default.extend(xZf.default);var BSw="Changelog",NSw=["summary","index","overview"],Ain=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}toChangelogNode(t){let r=t.title??BSw,n=[],i;for(let l of this.changelogFiles??[]){let g=vJo(l.split("/"));if(g==null)continue;let O=MZf(g);if(O==null){let j=g.split(".")[0]?.toLowerCase();j!=null&&NSw.includes(j)&&(i=l);continue}let w=this.toRelativeFilepath(l);n.push({date:O,pageId:Yc.PageId(w),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??QW(r)}),u=n.map(l=>{let g=Dzn.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=NTu(u,l=>l.date,"desc"),d=i!=null?Yc.PageId(this.toRelativeFilepath(i)):void 0,c=this.idgen.get(d??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}groupByYear(t,r,n){let i=new Map;for(let a of r){let u=Dzn.default.utc(a.date).year(),f=i.get(u)??[];f.push(a),i.set(u,f)}return NTu(Array.from(i.entries()).map(([a,u])=>{let f=n.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,n),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,n){let i=new Map;for(let a of r){let u=Dzn.default.utc(a.date).month()+1,f=i.get(u)??[];f.push(a),i.set(u,f)}return NTu(Array.from(i.entries()).map(([a,u])=>{let f=(0,Dzn.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.format("MMMM YYYY"),month:a,slug:n.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}};function NTu(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 WMa=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;#s;disableEndpointPairs;constructor(t,r,n,i,a,u,f,d){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Yc.V1.ApiDefinitionId(r.id),this.#e=E5r.create(r,u),this.#s=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Yc.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??QW(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#o=this.#y(this.#o.map(o=>this.#g(o)),this.#j(this.#e.api.rootPackage,this.#c))}get(){let t=Yc.V1.followRedirects(this.#o);return{id:this.#s.get(this.apiDefinitionId),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 Ain(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(r=>r.absoluteFilepath),this.docsWorkspace,this.#s).toChangelogNode({parentSlug:this.#c,viewers:[]}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,n){r=this.#e.resolveSubpackage(r);let i=r!=null?E5r.getSubpackageId(r):void 0;return t.map(a=>NAa(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:Yc.Url(u.url)}),page:u=>this.#d(u,n),package:u=>this.#v(u,n),section:u=>this.#_(u,n),item:({value:u})=>this.#p(u,i,n),endpoint:u=>this.#P(u,i,n)})).filter(QM)}#d(t,r){let n=Yc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??QW(t.title)});return{id:this.#s.get(n),type:"page",pageId:n,title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=E5r.getSubpackageId(a),f=this.#s.get(n??`${this.apiDefinitionId}:${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,[u]);let d=t.slug??(L9t(a)?a.urlSlug:this.apiSection.slug??QW(this.apiSection.title)),c=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(L9t(a)?a.displayName??pin(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??QW(t.package),f=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#u(t.contents,void 0,f);return{id:this.#s.get(n??`${this.apiDefinitionId}:${QW(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:f.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(n??i??r.get()),u=t.referencedSubpackages.map(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?E5r.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(QM);this.#a.set(a,u),u.forEach(o=>{this.#r.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#r.add(o)});let f=t.slug??QW(t.title),d=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,d);return{id:a,type:"apiPackage",children:c,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,n){t=t.trim();let i=this.#e.getSubpackageByIdOrLocator(t);if(i!=null){let a=E5r.getSubpackageId(i),u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#r.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#r.add(a),this.#a.set(u,[a]);let f=L9t(i)?i.urlSlug:"",d=n.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:L9t(i)?i.displayName??pin(i.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}return this.#P({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0},r,n)}#P(t,r,n){let i=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.endpoints.get(LF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(i!=null){let f=this.#e.getEndpointId(i);if(f==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let d=t.slug!=null?n.append(t.slug):n.apply(i);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:i.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:t.title??i.name??PDe(i.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.webSockets.get(LF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??PDe(a.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.webhooks.get(LF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Yc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??k1("/",...u.path),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=Yc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,i);return{...t,children:u,pointsTo:Yc.V1.followRedirects(u)}}return t}#j(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??PDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.websockets.forEach(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??PDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned: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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??pin(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.subpackages.forEach(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=L9t(a)?r.apply(a):r,f=this.#m(i,u);f.length>0&&n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:L9t(a)?a.displayName??pin(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:Yc.V1.followRedirects(f),noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned: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}#m(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.#j(n,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Yc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Yc.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} ${PDe(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}};var TZf=ko(require("crypto"),1);function zSw(e){return TZf.default.createHash("sha256").update(e).digest("hex")}var HMa=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#n(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),zSw(r===0?t:`${t}-${r}`)}#i(t){let r=this.#n(t),n=0;for(;this.#t.has(r);)if(r=this.#n(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Yc.V1.NodeId(this.#i(t))}};function CZf(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 QMa=ko(t6t(),1);var DD=ko(t6t(),1);var A5r=ko(t6t(),1);function qZf(e){return e._visit({alias:t=>({type:"alias",value:jx(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:L5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>A5r.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:A5r.FernRegistry.PropertyKey(r.name.wireValue),valueType:jx(r.valueType),availability:L5(r.availability)})),extraProperties:USw(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:A5r.FernRegistry.PropertyKey(n.name.wireValue),valueType:jx(n.valueType),availability:L5(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?L5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[A5r.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:A5r.FernRegistry.PropertyKey(i.name.wireValue),valueType:jx(i.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_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:jx(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jx(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jx(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:jx(r),valueType:jx(n)}),optional:r=>({type:"optional",itemType:jx(r),defaultValue:void 0}),set:r=>({type:"set",itemType:jx(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:A5r.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>FSw(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>LSw(t.v2),string:()=>RSw(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 RSw(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 FSw(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 LSw(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 USw(e){return typeof e=="boolean"?iT.unknown():typeof e=="string"?{type:"id",value:A5r.FernRegistry.TypeId(e),default:void 0}:jx(e)}function RTu(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?WSw(r,t):[],webhooks:n!=null?VSw(n):[],websockets:i!=null?[HSw(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 VSw(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??_fi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jx(r.valueType),availability:L5(r.availability)})),payload:ZSw(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function WSw(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=>zTu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(zTu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=lOi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...zTu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:L5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:$Sw(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?QSw({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??_fi(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:jx(f.valueType),availability:void 0})),parts:[...Szn(n.basePath),...Szn(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:jx(f.valueType),availability:void 0})),parts:[...t.basePath!=null?Szn(t.basePath):[],...Szn(e.basePath),...Szn(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:jx(f.valueType),availability:L5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:jx(f.valueType),availability:L5(f.availability)})),request:n.requestBody!=null?KSw(n.requestBody):void 0,response:n.response!=null?YSw(n.response):void 0,errors:void 0,errorsV2:XSw(n.errors,t),examples:a};r.push(u)}return r}function HSw(e,t){return{auth:e.auth,availability:L5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?JSw({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??_fi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:jx(r.valueType),availability:void 0})),parts:Szn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:jx(r.valueType),description:r.docs,availability:L5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jx(r.valueType),availability:L5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:kSw(r.body),description:r.docs,availability:L5(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 L5(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:Lc(e.status)}}function QSw({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:Lc(r)}}function JSw({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:GSw(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Lc(r)}}function GSw(e,t){return e.replace(/^[^:]+/,t)}function $Sw(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 Szn(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 KSw(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??m4.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:jx(n.valueType),availability:L5(n.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??m4.APPLICATION_JSON,shape:{type:"reference",value:jx(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:jx(i.valueType),contentType:i.contentType,description:i.docs,availability:L5(i.availability)}),_other:()=>{}})).filter(QM)},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 YSw(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:jx(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:jx(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:jx(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 XSw(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:jx(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:jx(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},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 zTu({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(QM),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(cS(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(w=>typeof w=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:Sqt})}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=>Fje._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(QM)}}function ZSw(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:jx(t.valueType),availability:L5(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jx(e.payloadType)},description:e.docs};default:Lc(e)}}function kSw(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:jx(t.valueType),availability:L5(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:jx(e.bodyType)};default:Lc(e)}}var FTu=ko(t6t(),1);function IZf(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:FTu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:FTu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:Lc(n)}}function wDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:RTu(e.rootPackage,e),auth:IZf(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:L5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:jx(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[QMa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:qZf(a.shape),availability:L5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[QMa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:QMa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...RTu(a,e)}}return n}var LTu=ko(t6t(),1);async function UTu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await GH({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=Len({token:n.value}),c=wDe({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:LTu.FernRegistry.OrgId(e),apiId:LTu.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 eEw=new yin({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function BZf(e,t,r){return Fmi(Nmi(wDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),LF.ApiDefinitionId(t),eEw))}function NZf(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 NAr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}RZf.default.extend(FZf.default);var tEw=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),zZf=0,rEw=async({ir:e})=>(zZf++,`${e.apiName.snakeCase.unsafeName}-${zZf}`),zAr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=tEw,f=rEw){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=HMa.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await kxe.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=Oq(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 qAu({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 IAu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=NZf(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=Cmi(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)]=CAu(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=nEw(this.editThisPage,d);a[wIt.PageId(d)]={markdown:c,editThisPageUrl:o?wIt.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=kx(this.docsWorkspace.absoluteFilePath,c);(await(0,JMa.stat)(o)).isDirectory()?(await Bxe(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,JMa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return kx(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,LZf.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(NAr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?wIt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:wIt.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:wIt.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 toRootNode(){let t=Yc.V1.SlugGenerator.init(Yc.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}async toRootChild(t){return Fxn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??QW(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.version),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:Yc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:n,availability:t.availability!=null?iEw(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(i,f,n))),u=[];return a.forEach(f=>{switch(f.type){case"apiReference":case"section":u.push(f);return;case"changelog":case"link":case"page":{let d=u[u.length-1];d?.type!=="sidebarGroup"&&(d={id:this.#e.get(`${i}/group`),type:"sidebarGroup",children:[]},u.push(d)),d.children.push(f);return}default:Lc(f)}}),{type:"sidebarRoot",id:i,children:u}}async toNavigationChild(t,r,n){return Fxn(r)._visit({page:async i=>this.toPageNode(i,n),apiSection:async i=>this.toApiSectionNode(i,n),section:async i=>this.toSectionNode(t,i,n),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toApiSectionNode(t,r){let n=this.getFernWorkspaceForApiSection(t),i=CZf(t.snippetsConfiguration),a=await GH({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=BZf(a,u,{oauth:t.playground?.oauth});return new WMa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new Ain(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Yc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??QW(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:i.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toSectionNode(t,r,n){let i=this.toRelativeFilepath(r.overviewAbsolutePath),a=i?Yc.PageId(i):void 0,u=this.#e.get(a??`${t}/section`),f=n.apply({urlSlug:r.slug??QW(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}async convertTabbedNavigation(t,r,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return Fxn(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n)})}async toTabChangelogNode(t,r,n){return new Ain(this.markdownFilesToFullSlugs,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Yc.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),u=i.apply({urlSlug:r.slug??QW(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,u)}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):wIt.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(QM),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:wIt.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 Fxn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:wIt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function nEw(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${NAr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function iEw(e){switch(e){case"beta":return Yc.V1.NavigationV1Availability.Beta;case"deprecated":return Yc.V1.NavigationV1Availability.Deprecated;case"ga":return Yc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Yc.V1.NavigationV1Availability.Stable;default:Lc(e)}}var ksd=ko(JZf(),1),Cqu=ko(FCu(),1),ecd=ko(require("http"),1),VTa=ko(require("path"),1);var vnd=require("events"),Exa=ko(require("fs"),1),zin=ko(require("path"),1);var krd=ko(require("os"),1),end=300,I5r=20,COi=1e7,tnd=krd.default.platform();var Uqw=tnd==="darwin",LCu=tnd==="win32",B5r=Uqw||LCu,rnd=3e3,nnd=2e4,UCu=1250;var H9t;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(H9t||(H9t={}));var Nin;(function(e){e.CHANGE="change",e.RENAME="rename"})(Nin||(Nin={}));var qOi;(function(e){e.CHANGE="change",e.ERROR="error"})(qOi||(qOi={}));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 _k;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(_k||(_k={}));var Vqw=(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(),L=C-d,K=C-c,te=L>=t||K>=a;return[C,te]},l=C=>{if(c=C,!u)return;let L=u;u=void 0,e.apply(void 0,L)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},w=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,L]=o();return L?j(C):q(C)},q=C=>{let L=C-d,K=C-c,te=t-L,J=a-K,G=Math.min(te,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[L,K]=o(),te=!!f;if(u=C,d=L,(K||!f)&&B(t),K)return te?l(L):w(L)};return I.cancel=g,I.flush=O,I},wxa=Vqw;var JCu=ko(require("fs"),1),Dxa=ko(require("path"),1);var Dx=ko(require("fs"),1),$H=require("util");var RAr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Q9t=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var VCu=ko(require("process"),1),ind=VCu.default.getuid?!VCu.default.getuid():!1,and=1e4,lae=()=>{};var IOi={isChangeErrorOk:e=>{if(!IOi.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!ind&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!IOi.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(!IOi.isNodeError(e))throw e;if(!IOi.isChangeErrorOk(e))throw e}},Hz=IOi;var WCu=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=and,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()}}}}},ond=new WCu;var FAr=(e,t)=>function(n){return function i(...a){return ond.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)})}},LAr=(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 Wqw={attempt:{chmod:RAr((0,$H.promisify)(Dx.default.chmod),Hz.onChangeError),chown:RAr((0,$H.promisify)(Dx.default.chown),Hz.onChangeError),close:RAr((0,$H.promisify)(Dx.default.close),lae),fsync:RAr((0,$H.promisify)(Dx.default.fsync),lae),mkdir:RAr((0,$H.promisify)(Dx.default.mkdir),lae),realpath:RAr((0,$H.promisify)(Dx.default.realpath),lae),stat:RAr((0,$H.promisify)(Dx.default.stat),lae),unlink:RAr((0,$H.promisify)(Dx.default.unlink),lae),chmodSync:Q9t(Dx.default.chmodSync,Hz.onChangeError),chownSync:Q9t(Dx.default.chownSync,Hz.onChangeError),closeSync:Q9t(Dx.default.closeSync,lae),existsSync:Q9t(Dx.default.existsSync,lae),fsyncSync:Q9t(Dx.default.fsync,lae),mkdirSync:Q9t(Dx.default.mkdirSync,lae),realpathSync:Q9t(Dx.default.realpathSync,lae),statSync:Q9t(Dx.default.statSync,lae),unlinkSync:Q9t(Dx.default.unlinkSync,lae)},retry:{close:FAr((0,$H.promisify)(Dx.default.close),Hz.isRetriableError),fsync:FAr((0,$H.promisify)(Dx.default.fsync),Hz.isRetriableError),open:FAr((0,$H.promisify)(Dx.default.open),Hz.isRetriableError),readFile:FAr((0,$H.promisify)(Dx.default.readFile),Hz.isRetriableError),rename:FAr((0,$H.promisify)(Dx.default.rename),Hz.isRetriableError),stat:FAr((0,$H.promisify)(Dx.default.stat),Hz.isRetriableError),write:FAr((0,$H.promisify)(Dx.default.write),Hz.isRetriableError),writeFile:FAr((0,$H.promisify)(Dx.default.writeFile),Hz.isRetriableError),closeSync:LAr(Dx.default.closeSync,Hz.isRetriableError),fsyncSync:LAr(Dx.default.fsyncSync,Hz.isRetriableError),openSync:LAr(Dx.default.openSync,Hz.isRetriableError),readFileSync:LAr(Dx.default.readFileSync,Hz.isRetriableError),renameSync:LAr(Dx.default.renameSync,Hz.isRetriableError),statSync:LAr(Dx.default.statSync,Hz.isRetriableError),writeSync:LAr(Dx.default.writeSync,Hz.isRetriableError),writeFileSync:LAr(Dx.default.writeFileSync,Hz.isRetriableError)}},und=Wqw;var jxa=ko(require("fs"),1),BOi=ko(require("path"),1);var snd={then:e=>{e()}};var HCu=()=>{};var QCu=()=>{let e=HCu,t=HCu,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}};QCu.wrap=async e=>{let t=QCu();return await e(t),t.promise};var cnd=QCu;var lnd=e=>Array.isArray(e)?e:[e],fnd=e=>typeof e=="function",dnd=()=>{let{promise:e,resolve:t}=cnd(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var Hqw=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=lnd(a).map(It=>fnd(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=[],w=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,L={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:w,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:te,increment:J,decrement:G}=dnd(),re=0,Xe=(It,cr,Hr,Gt)=>{C.has(cr)||re>=i||(re+=1,It.directories.push(cr),It.directoriesNames.add(Hr),o.push(cr),l.add(Hr),g.propertyIsEnumerable(Hr)||(g[Hr]=[]),g[Hr].push(cr),C.add(cr),!(Gt>=n)&&(re>=i||or(cr,Gt+1)))},Re=(It,cr,Hr)=>{C.has(cr)||re>=i||(re+=1,It.files.push(cr),It.filesNames.add(Hr),O.push(cr),w.add(Hr),j.propertyIsEnumerable(Hr)||(j[Hr]=[]),j[Hr].push(cr),C.add(cr))},Dt=(It,cr,Hr,Gt)=>{C.has(cr)||re>=i||(re+=1,It.symlinks.push(cr),It.symlinksNames.add(Hr),M.push(cr),q.add(Hr),B.propertyIsEnumerable(Hr)||(B[Hr]=[]),B[Hr].push(cr),C.add(cr),r&&(Gt>=n||re>=i||jr(cr,Gt+1)))},Ct=(It,cr,Hr,Gt,wn)=>{d.aborted||f(cr)||(Gt.isDirectory()?Xe(It,cr,Hr,wn):Gt.isFile()?Re(It,cr,Hr):Gt.isSymbolicLink()&&Dt(It,cr,Hr,wn))},Wt=(It,cr,Hr,Gt)=>{if(d.aborted)return;let wn=cr===BOi.default.sep?"":BOi.default.sep,An=Hr.name,Ht=`${cr}${wn}${An}`;f(Ht)||(Hr.isDirectory()?Xe(It,Ht,An,Gt):Hr.isFile()?Re(It,Ht,An):Hr.isSymbolicLink()&&Dt(It,Ht,An,Gt))},Bt=(It,cr,Hr,Gt)=>{for(let wn=0,An=Hr.length;wn<An;wn++)Wt(It,cr,Hr[wn],Gt)},or=(It,cr)=>{d.aborted||cr>n||re>=i||(J(),jxa.default.readdir(It,{withFileTypes:!0},(Hr,Gt)=>{if(Hr||d.aborted||!Gt.length)return G();(c(Gt)||snd).then(()=>{let An=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(An,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),jxa.default.realpath(It,(Hr,Gt)=>{if(Hr||d.aborted)return G();jxa.default.stat(Gt,async(wn,An)=>{if(wn||d.aborted)return G();let Ht=BOi.default.basename(Gt),er=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(er,Gt,Ht,An,cr),G()})})};return(async(It,cr=1)=>(It=BOi.default.normalize(It),C.add(It),or(It,cr),await te,d.aborted?L:K))(e)},pnd=Hqw;var J9t={lang:{debounce:wxa,attempt:e=>{try{return e()}catch(t){return J9t.lang.castError(t)}},castArray:e=>J9t.lang.isArray(e)?e:[e],castError:e=>J9t.lang.isError(e)?e:J9t.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(J9t.lang.isNaN(e))return J9t.lang.isNaN(t);if(J9t.lang.isPrimitive(e)||J9t.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(Dxa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?JCu.default.realpathSync.native(e):JCu.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Dxa.default.sep&&t.length-e.length>Dxa.default.sep.length,poll:(e,t=nnd)=>und.retry.stat(t)(e,{bigint:!0}).catch(J9t.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 pnd(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=J9t;var Sxa=ko(require("path"),1);var GCu=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=end){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??I5r:Math.min(1,this.options.depth??I5r),u=this.options.limit??COi,[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&&!B5r&&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(Sxa.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(Sxa.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=Nin.CHANGE,r){if(this.watcher.isClosed())return;let n=Sxa.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){LCu&&t.code==="EPERM"?this.onWatcherChange(Nin.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(qOi.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(qOi.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Nin.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&B5r&&this.options.native!==!1?this.options.depth??I5r:Math.min(1,this.options.depth??I5r),n=this.options.limit??COi,[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(Nin.CHANGE,f,t)}))}}},_nd=GCu;var hk={interval:100,intervalId:void 0,fns:new Map,init:()=>{hk.intervalId||(hk.intervalId=setInterval(hk.resolve,hk.interval))},reset:()=>{hk.intervalId&&(clearInterval(hk.intervalId),delete hk.intervalId)},add:(e,t)=>{hk.fns.set(e,Date.now()+t),hk.init()},remove:e=>{hk.fns.delete(e)},resolve:()=>{if(!hk.fns.size)return hk.reset();let e=Date.now();for(let[t,r]of hk.fns)r>=e||(hk.remove(t),t())}},NOi=hk;var zOi=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=UCu){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),NOi.remove(c)},c=()=>{d(),f()};NOi.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=UCu){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),NOi.remove(c)},c=()=>{d(),f()};NOi.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,H9t.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,H9t.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,H9t.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,H9t.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}}};zOi.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};zOi.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var hnd=zOi;var $Cu=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}},KCu=$Cu;var YCu=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}},ynd=YCu;var XCu=class{constructor(){this.inos={},this.paths=new KCu,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 ynd(n)}reset(){this.inos={},this.paths=new KCu,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()?H9t.FILE:H9t.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)}}},ZCu=XCu;var kCu=class e extends vnd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(_k.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(_k.CLOSE,i)),this._readyWait=new Promise(i=>this.on(_k.READY,i)),this._locker=new hnd(this),this._roots=new Set,this._poller=new ZCu,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(_k.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(_k.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(_k.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(_k.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 _nd(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=zin.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??I5r))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&B5r&&o.options.native!==!1)))return!0;if(!B5r)break;let c=zin.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||B5r&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Exa.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},w=zin.default.dirname(f),j=f;await this.watchDirectories([w],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||B5r&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??I5r,f=r.limit??COi,[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)),w={...r,depth:O};await this.watchDirectories([l],w,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(_k.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(_k.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=zin.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new ZCu,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??rnd},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(_k.CLOSE,f),Exa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(_k.CLOSE,f),Exa.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=zin.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=zin.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(_k.ALL,n),r.readdirMap=void 0,this.ready())}},bnd=kCu;var eIw=ko(Pnd(),1),tIw=ko(l2u(),1),rIw=ko(d2u(),1),nIw=ko(g2u(),1),O2u=ko(gid(),1);var Jsd=ko(wTa(),1),Gsd=require("fs"),kAr=require("fs/promises"),LTa=require("os"),Aqu=ko(require("path"),1),$sd=require("stream/promises"),Ksd=ko(bne(),1),Ysd=ko(Qsd(),1),p3w="etag",Mqu="preview",_3w="bundle",xqu=".fern";function h3w(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu))}function UTa(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu),Ms.of(_3w))}function y3w(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu),Ms.of(p3w))}async function Xsd({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(await fetch(e)).text(),u=await new Ysd.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=y3w();if(r){let q=await Wh(c),B;if(q&&(t.debug("Reading existing ETag"),B=(await(0,kAr.readFile)(c)).toString()),B!=null&&B===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 Ksd.default.dir({prefix:"fern"}),l=v_.of(o.path);t.debug(`Downloading docs preview bundle from ${Aqu.default.join(e,d)}`);let g=await fetch(`${Aqu.default.join(e,d)}`);if(!g.ok)return t.error(`Failed to download docs preview bundle. ${g.statusText}`),{type:"failure"};let O=yf(l,Ms.of("output.zip")),w=g.body;if(w==null)return{type:"failure"};await(0,$sd.pipeline)(w,(0,Gsd.createWriteStream)(O)),t.debug(`Wrote output.zip to ${O}`);let j=h3w();await Wh(j)&&await(0,kAr.rm)(j,{recursive:!0}),await(0,kAr.mkdir)(j,{recursive:!0}),t.debug(`rm -rf ${j}`);let M=UTa();return await(0,kAr.mkdir)(M,{recursive:!0}),await(0,Jsd.default)(O,M),await(0,kAr.writeFile)(c,f),t.debug(`Downloaded bundle to ${M}`),{type:"success"}}async function Zsd({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 Tqu(r),f={},c=await new zAr(e,n,a,r,void 0,async g=>g.map(O=>{let w=Ozr();return f[w]={type:"url",url:Yc.Url(`/_local${p$o(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:w}}),async g=>u.addReferencedAPI(g)).resolve(),o=zxu({writeShape:c,files:{}}),l=Fxu({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 Tqu=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=Ozr(),a=Nmi(wDe({ir:t,snippetsConfig:r,playgroundConfig:n}),bU.ApiDefinitionId(i),new yin({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=Fmi(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 v3w={pages:{},apis:{},files:{},filesV2:{},config:{navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function qqu({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 Xsd({bucketUrl:I,logger:n.logger,preferCached:!0})}catch{let C=UTa();if(await Wh(C))n.logger.warn("Failed to download latest docs application. Falling back to existing bundle.");else{n.logger.warn("Failed to download docs application. Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,Cqu.default)(),d=ecd.default.createServer(f),c=new O2u.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,ksd.default)());let g=new URL(NAr(e.docsWorkspaces?.config.instances[0]?.url??`localhost:${i}`)),O=e,w,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 Zsd({domain:g.host,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return w==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}
|
|
1984
|
+
`)}]:t.flatMap((c,o)=>JH({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:JH({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return mDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return mDe(d=>d===f.string,`"${f.string}"`)(t);default:Lc(f)}}}})}function DDw({primitiveType:e,example:t}){return e.v2!=null?XA._visit(e.v2,{integer:r=>SDw({example:t,rules:r.validation}),long:()=>bXf(t),uint:()=>hXf(t),uint64:()=>yXf(t),double:r=>EDw({example:t,rules:r.validation}),float:()=>vXf(t),boolean:()=>gXf(t),string:r=>ADw({example:t,rules:r.validation}),uuid:()=>mXf(t),date:()=>PXf(t),dateTime:()=>OXf(t),base64:()=>mzn(t),bigInteger:()=>mzn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>jXf(t),long:()=>bXf(t),uint:()=>hXf(t),uint64:()=>yXf(t),double:()=>DXf(t),float:()=>vXf(t),boolean:()=>gXf(t),string:()=>mzn(t),uuid:()=>mXf(t),dateTime:()=>OXf(t),date:()=>PXf(t),base64:()=>mzn(t),bigInteger:()=>mzn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function SDw({example:e,rules:t}){let r=jXf(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 EDw({example:e,rules:t}){let r=DXf(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 ADw({example:e,rules:t}){let r=mzn(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 mzn=mDe(e=>typeof e=="string","a string"),jXf=mDe(e=>Number.isInteger(e),"an integer"),hXf=mDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),yXf=mDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),vXf=mDe(e=>typeof e=="number","a float"),DXf=mDe(e=>typeof e=="number","a double"),bXf=mDe(e=>Number.isInteger(e),"an integer"),gXf=mDe(e=>typeof e=="boolean","a boolean"),mXf=mDe(e=>typeof e=="string"&&wDw.test(e),"a UUID"),OXf=mDe(e=>typeof e=="string"&&wXf.test(e),"an ISO 8601 timestamp"),PXf=mDe(e=>typeof e=="string"&&jDw.test(e)&&wXf.test(e),"a date");function mDe(e,t){return r=>e(r)?[]:m2e(r,t)}function oOi({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&&oOi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return oOi({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&&oOi({expected:e.container.keyType,actual:t.container.keyType})&&oOi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:MDw({expected:e.container.literal,actual:t.container.literal});default:Lc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Lc(e)}function MDw({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:Lc(e)}}async function xMa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await F$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:Ozn(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 SXf(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 Ozn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function DTu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return Mz(t,{alias:d=>fS.alias({value:uT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>EXf({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=jin(d);if(!cS(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 fS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:D5r(d).name,wireValue:c}),singleUnionType:TDw({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 fS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:SXf(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(JH({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return fS.undiscriminatedUnion({index:c,singleUnionType:uT({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 uT({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:Ien({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>xDw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!cS(f))throw new Error("Example is not an object");return dO.container(bA.map({map:Object.entries(f).map(([O,w])=>({key:uT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:uT({example:w,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(bA.list({list:f.map(g=>uT({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(bA.set({set:f.map(g=>uT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(bA.optional({optional:f!=null?uT({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(bA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(bA.literal({literal:Pv.string({original:l.string})}));default:Lc(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 w={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:w,shape:DTu({typeName:w,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function xDw({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 EXf({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!cS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return fS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=AXf({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=uT({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:QH({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function AXf({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:uOi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function uOi({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"||!gA(u.declaration))throw new Error("Extension is not of a named object");let f=AXf({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function TDw({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:gzn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:Ez.noProperties()};let l=jTu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!cS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:Ez.singleProperty(uT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!cS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,w=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!gA(w.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:Ez.samePropertiesAsObject({typeId:s1.generateTypeId(j),object:EXf({rawObject:w.declaration,example:O,fileContainingType:w.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:Lc(l)}}async function TMa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=BAr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await F$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function BAr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function CDw(e){let t=JSON.stringify(e);return MXf.default.createHash("sha256").update(t).digest("hex")}function xXf({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=IDw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??CDw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:FDw({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...BDw({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:BAr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:uT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:qDw({queryParameter:g})}}):[],request:NDw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:zDw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function qDw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?EF.exploded():EF.single()}function IDw({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:w})=>{let j=sOi({parameter:O,variableResolver:a,file:u});return{name:g,value:uT({example:w,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 w=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(w!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,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 BDw({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:F9t({headerKey:c,header:l}).name,wireValue:c}),value:uT({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:F9t({headerKey:c,header:g}).name,wireValue:c}),value:uT({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 NDw({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"&&N_i(u)!=null)return;if(!_6(u))return a$.reference(uT({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(!cS(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&&cCe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:QH({propertyKey:d,property:o}).name,wireValue:d}),value:uT({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=uOi({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:QH({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:uT({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 a$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function zDw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?S4.ok(rN.body(void 0)):Nen(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return S4.error({error:w5r({errorName:f.error,file:a}),body:d.declaration.type!=null?uT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return S4.ok(rN.body(RDw({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 S4.ok(rN.stream(f.stream.map(c=>{if(d!=null)return uT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(QM)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return S4.ok(rN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=uT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter(QM)))}})}function RDw({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 uT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function FDw({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 TXf({endpoint:e,file:t,typeResolver:r}){return{body:await LDw({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function LDw({endpoint:e,file:t,typeResolver:r}){let n=await UDw({endpoint:e,file:t,typeResolver:r}),i=await VDw({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Oie.fileDownload({...n});break}case"json":{a=Oie.json({...n.value});break}case"text":{a=Oie.text({...n});break}default:Lc(n)}return w3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return w3.streaming(i)}}async function UDw({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 cCe(a)!=null?w3.fileDownload({docs:i}):z_i(a)!=null?w3.text({docs:i}):await WDw(n,i,t,r)}}async function VDw({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 Sqn(a)?Pie.text({docs:i}):typeof n!="string"&&u==="sse"?Pie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Pie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function WDw(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?w3.json(v6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await nOi({typeResolver:n,file:r,resolvedType:a,property:u})})):w3.json(v6t.response({docs:t,responseBodyType:i}))}async function CXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return nCe.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 qXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return nCe.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 IXf(e){return HDw(e)?{type:"offset",offset:DIt(e.offset),results:qAr(e.results),step:e.step!=null?DIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?qAr(e["has-next-page"]):void 0}:{type:"cursor",cursor:DIt(e.cursor),next_cursor:qAr(e.next_cursor),results:qAr(e.results)}}function HDw(e){return e.offset!=null&&e.results!=null}async function BXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=IXf(i);switch(a.type){case"cursor":return await CXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return qXf({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:Lc(a)}}function NXf({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=w5r({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function CMa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function zXf({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:CMa({source:e}),name:j5r.generateName(r)}}async function RXf({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return eCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return eCe.http();let i=zXf({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return eCe.grpc({service:i})}async function FXf({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 Pzn({pathParameters:r["path-parameters"],location:tCe.Service,file:n,variableResolver:d}),O=await RXf({file:n,serviceDeclaration:r,sourceResolver:c}),w={fernFilepath:n.fernFilepath};return{availability:uae(r.availability),name:w,displayName:r["display-name"]??void 0,basePath:g2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>O2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:$Dw(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await Pzn({pathParameters:q["path-parameters"],location:tCe.Endpoint,file:n,variableResolver:d}),I={...await F$(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?GDw(q.method):gie.Post,basePath:q["base-path"]!=null?g2e(q["base-path"]):void 0,path:g2e(q.path),fullPath:g2e(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,L])=>await TMa({file:n,queryParameterKey:C,queryParameter:L}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,L])=>O2e({headerKey:C,header:L,file:n}))):[],requestBody:ZYf({request:q.request,file:n}),sdkRequest:await nXf({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await TXf({endpoint:q,file:n,typeResolver:a}),errors:[...NXf({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:xXf({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(L=>aXf({codeSample:L,file:n}))})):[],autogeneratedExamples:[],pagination:await BXf({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=s1.generateEndpointId(w,I),I}))}}async function Pzn({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>QDw({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function QDw({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await F$(t),name:n.casingsGenerator.generateName(e),valueType:JDw({parameter:t,variableResolver:i,file:n}),location:r,variable:d6n(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function JDw({parameter:e,variableResolver:t,file:r}){let n=sOi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function sOi({parameter:e,variableResolver:t,file:r}){let n=qMa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function qMa({parameter:e,variableResolver:t,file:r}){if(d6n(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 GDw(e){switch(e){case"GET":return gie.Get;case"POST":return gie.Post;case"PUT":return gie.Put;case"PATCH":return gie.Patch;case"DELETE":return gie.Delete;default:Lc(e)}}async function O2e({headerKey:e,header:t,file:r}){let{name:n}=F9t({headerKey:e,header:t});return{...await F$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function F9t({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function $Dw(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Lc(e)}}var L$={};kc(L$,{validateObjectExample:()=>bzn,validateTypeExample:()=>MMa,validateTypeReferenceExample:()=>JH});function LXf(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function IMa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function UXf({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:IMa({fernFilePath:i.file.fernFilepath})?void 0:s1.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 VXf({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:IMa({fernFilePath:i.file.fernFilepath})?void 0:s1.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 WXf({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await VXf({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 UXf({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 cOi={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}},STu={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 HXf(e){return{endpoint:e["get-token"].endpoint,requestProperties:KDw({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:YDw({responseProperties:e["get-token"]?.["response-properties"]})}}function QXf(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:XDw({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:ZDw({responseProperties:e["refresh-token"]?.["response-properties"]})}}function KDw({requestProperties:e}){if(e==null)return cOi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?DIt(t):cOi.requestProperties.client_id,client_secret:r!=null?DIt(r):cOi.requestProperties.client_secret,scopes:n!=null?DIt(n):cOi.requestProperties.scopes}}function YDw({responseProperties:e}){return JXf({responseProperties:e,defaultValue:cOi.responseProperties})}function XDw({requestProperties:e}){if(e==null)return STu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?DIt(t):STu.requestProperties.refresh_token}}function ZDw({responseProperties:e}){return JXf({responseProperties:e,defaultValue:STu.responseProperties})}function JXf({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?qAr(r):t.access_token,expires_in:n!=null?qAr(n):t.expires_in,refresh_token:i!=null?qAr(i):t.refresh_token}}async function XXf({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:V7r.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return R_i(e.auth,{single:async a=>{let u=await GXf({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:V7r.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:V7r.Any,schemes:await Promise.all(a.map(async u=>await GXf({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function GXf({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 lau(c,{header:async o=>yH.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=>KXf({file:r,docs:d,rawScheme:o}),bearer:async o=>$Xf({file:r,docs:d,rawScheme:o}),oauth:async o=>await YXf({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return $Xf({file:r,docs:void 0,rawScheme:void 0});case"basic":return KXf({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await YXf({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function $Xf({file:e,docs:t,rawScheme:r}){return yH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function KXf({file:e,docs:t,rawScheme:r}){return yH.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 YXf({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return yH.oauth({docs:t,configuration:W7r.clientCredentials(await WXf({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:HXf(r),refreshTokenEndpoint:QXf(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function ZXf({file:e,rawApiFileSchema:t}){if(t.version!=null)return Q7r.header({header:await kDw({file:e,header:t.version.header}),value:await eSw({file:e,versionDeclaration:t.version})})}async function kDw({file:e,header:t}){return typeof t=="string"?await O2e({file:e,headerKey:t,header:{type:"string"}}):await O2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function eSw({file:e,versionDeclaration:t}){return await xMa({_enum:{default:t.default,enum:t.values},file:e})}async function kXf({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:uae(d.availability),docs:d.docs,origin:d.origin,body:nSw({body:d.body,file:i}),displayName:d["display-name"]});return{availability:uae(e.availability),path:g2e(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])=>O2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await Pzn({pathParameters:e["path-parameters"],location:tCe.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}=BAr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await F$(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=aSw({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:uSw({channel:e,example:f,pathParams:d}),...d,...oSw({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:BAr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:uT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:tSw({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:rSw({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function tSw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?EF.exploded():EF.single()}function rSw({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!sSw(e.body))return m6t.reference(uT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!cS(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:QH({propertyKey:f,property:c}).name,wireValue:f}),value:uT({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=uOi({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:QH({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:uT({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 m6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function nSw({body:e,file:t}){return typeof e=="string"?aCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):iSw(e)?aCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):aCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:jIt(e.extends??[]).map(r=>OU({typeName:r,file:t})),properties:[]})}function iSw(e){return e.type!=null}function aSw({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=sOi({parameter:o,variableResolver:i,file:a});return{name:c,value:uT({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 oSw({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:F9t({headerKey:f,header:c}).name,wireValue:f}),value:uT({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 uSw({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 sSw(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function ETu({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:iEr(n,{singleBaseUrl:()=>_6t.singleBaseUrl(cSw({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>_6t.multipleBaseUrls(lSw({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function cSw({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>iEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:eZf(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function lSw({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>iEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>eZf(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function eZf(e){return e.endsWith("/")?e.slice(0,-1):e}function tZf({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:uT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:w5r({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 rZf="content";function nZf(e,t){if(e==null||e.strategy==="status-code")return b6t.statusCode();switch(e.strategy){case"property":return b6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:rZf,wireValue:rZf})});default:Lc(e)}}function iZf({readme:e,services:t}){let r=new ATu(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 ATu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=dSw({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:fSw(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function fSw(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 dSw({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 aZf({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:s1.generateWebhookId(t.fernFilepath,u),availability:uae(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])=>O2e({headerKey:d,header:c,file:t}))):[],payload:pSw({payload:f.payload,file:t}),examples:f.examples!=null?hSw({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function pSw({payload:e,file:t}){return typeof e=="string"?Sie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):BMa(e)?Sie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Sie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:jIt(e.extends).map(r=>OU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>_Sw({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?uae(n.availability):void 0,file:t})):[]})}function _Sw({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:QH({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function hSw({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:BMa(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:uT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!cS(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:uT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function BMa(e){return e.type!=null}function wzn(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 oZf({name:e,source:t}){return wD.userDefined({file:CMa({source:t}),name:j5r.generateName(e)})}function uZf({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=ySw({type:e.proto.type});if(t!=null)return t}}function ySw({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 sZf({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=P3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&gA(a.declaration)){let u=P3(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 wq.object({extends:jIt(a.declaration.extends).map(d=>OU({typeName:d,file:t})),properties:await rOi({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 cZf({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return kTe(n)?await sZf({generic:n,file:t,typeResolver:r}):wq.alias({aliasOf:t.parseTypeReference(e),resolvedType:vSw({aliasOf:n,file:t,typeResolver:r})})}function vSw({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return vH.primitive(n.originalTypeReference.primitive);case"container":return vH.container(n.originalTypeReference.container);case"unknown":return vH.unknown();case"named":{let i=gA(n.declaration)?g6t.Object:nNr(n.declaration)?g6t.Union:w6t(n.declaration)?g6t.Enum:_6n(n.declaration)?g6t.UndiscriminatedUnion:Lc(n.declaration);return vH.named({name:n.name,shape:i})}}}function lZf({union:e,file:t}){return wq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function fZf(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 xTu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new MTu}){let i=Mz(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=P3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=P3(o.typeName)?.arguments;if(gA(o.declaration)){let g=fZf(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>fZf(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=c$({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=OU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(kTe(o.typeName))continue;a.push(...xTu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var MTu=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 dZf({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await F$(t),d=OU({typeName:e,file:r}),c=xTu({typeDeclaration:t,file:r,typeResolver:n}),o={};gA(t)&&(o=wzn(t.properties??{}));let l=await gSw({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await bSw({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:mSw({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:DTu({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 bSw({typeDeclaration:e,file:t,typeResolver:r}){return await Mz(e,{alias:n=>cZf({alias:n,file:t,typeResolver:r}),object:n=>YYf({object:n,file:t}),discriminatedUnion:n=>dXf({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>lZf({union:n,file:t}),enum:async n=>wq.enum(await xMa({_enum:n,file:t}))})}async function gSw({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=uZf({encoding:t.encoding});if(a!=null)return rEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return rEr.proto(oZf({source:i,name:r}))}function mSw({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?OSw(e.encoding):PSw(t)}function OSw(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function PSw(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function pZf(e,t){let r=t[e];if(r==null)throw new _Sr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function _Zf(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,jSw({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>wSw({endpoint:n,ir:e}))}]))}}function wSw({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>hZf(r,t))}}}function jSw({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>hZf(r,t))}}}return e}function hZf(e,t){let r=TTu(e.typeId,t);return yZf({objectTypeDeclaration:r,ir:t})}function TTu(e,t){let r=pZf(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return TTu(r.shape.resolvedType.name.typeId,t)}throw new _Sr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function yZf({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=TTu(n.typeId,t);return yZf({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var NMa=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=s1.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=s1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=s1.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 zMa=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=DSw(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=s1.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=s1.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=s1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&F5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=s1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])F5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])F5(c.valueType,u,d);for(let c of r.queryParameters)F5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=wzn(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&w5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)CTu(o,u,d);for(let o of c.properties)F5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&_6(n.request.body)){let o=wzn(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{F5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)mie._visit(o,{file:cl,bodyProperty:({valueType:l})=>{F5(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&&w3._visit(r.response.body,{fileDownload:cl,json:c=>{F5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>F5(o.payload,u,d),json:o=>F5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>F5(o.payload,u,d),json:o=>F5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&F5(c.nonStreamResponse.value.responseBodyType,u,d)},text:cl,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(s1.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=s1.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&&Sie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)CTu(d,a,u);for(let d of f.properties)F5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!BMa(n.payload)){let d=wzn(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{F5(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 NMa({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:Lc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(s1.generateSubpackageId(n))}}};function DSw(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Lc(e)}}function F5(e,t,r){iT._visit(e,{container:n=>{SSw(n,t,r)},named:n=>{CTu(n,t,r)},primitive:cl,unknown:cl,_other:cl})}function CTu(e,t,r){t.add(s1.generateTypeId(e)),r.add(e.fernFilepath)}function SSw(e,t,r){jq._visit(e,{list:n=>{F5(n,t,r)},map:n=>{F5(n.keyType,t,r),F5(n.valueType,t,r)},optional:n=>{F5(n,t,r)},set:n=>{F5(n,t,r)},literal:cl,_other:cl})}function bZf({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:_N({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Ez.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=_N({filteredIr:e,exampleTypeReference:r});return n!==void 0?Ez.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function _N({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(bA.list({...n,list:n.list.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(bA.set({...n,set:n.set.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?_N({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(bA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(bA.map({...n,map:n.map.map(i=>{let a=_N({filteredIr:e,exampleTypeReference:i.key}),u=_N({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=_N({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:fS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:fS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:_N({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=bZf({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=_N({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:fS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qTu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function ESw({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function vZf({filteredIr:e,headers:t}){return t.map(r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function ASw({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=_N({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=_N({filteredIr:e,exampleTypeReference:r});return n!==void 0?a$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function MSw({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>S4.ok(rN.body(n!=null?_N({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>S4.ok(rN.stream(n.map(i=>_N({filteredIr:e,exampleTypeReference:i})).filter(QM))),sse:n=>S4.ok(rN.sse(n.map(({event:i,data:a})=>{let u=_N({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter(QM))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>S4.error({error:r,body:n!=null?_N({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function ITu({filteredIr:e,example:t}){return{...t,rootPathParameters:qTu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qTu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qTu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:vZf({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:vZf({filteredIr:e,headers:t.endpointHeaders}),queryParameters:ESw({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?ASw({filteredIr:e,requestBody:t.request}):void 0,response:MSw({filteredIr:e,response:t.response})}}function gZf({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=_N({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:fS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:fS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:_N({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=bZf({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:fS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=_N({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:fS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var RMa=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:s1.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(!mZf(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(!mZf(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=s1.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 mZf(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 OZf({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:P5r({referencedIn:t,importPath:f})}}var Din=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 Rz(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:j5r,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 Nrn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:j5r,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 F_i().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=OZf({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(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 Sin=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=gDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(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 ODe=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(cS(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(`\\${RRt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(RRt))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(RRt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(RRt.length),exampleName:i}}};var FMa=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:wie.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:wie.query(await TMa({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:wie.body(u)}}if(_6(n.body)){let u=await PTu({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:wie.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:wie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await OTu({typeResolver:this.typeResolver,file:iOi(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 PZf=require("fs/promises"),LMa=class{async parse({absoluteFilePath:t}){let r=await(0,PZf.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 UMa=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(Oua(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 Oua(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 LMa().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 ZA=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=gDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=Qie(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=P3(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 c$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:iT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:iT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:iT.container(jq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:iT.container(jq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:iT.container(jq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:iT.container(jq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:iT.container(jq.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(p6n(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=AMa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||Qie(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 EIt=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:IAr({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 VMa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function wZf({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:Lc(t.v1)}}function jZf({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return S5r({containerType:t});switch(t.type){case"list":{let u=UF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:bA.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 S5r({containerType:t});let u=UF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=UF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=UF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=UF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?S5r({containerType:t}):{type:"success",example:bA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:Lc(t)}}function S5r({containerType:e}){switch(e.type){case"list":return{type:"success",example:bA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:bA.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:bA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:bA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:bA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Lc(e)}}function jzn({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 SZf({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=UF({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:fS.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:fS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=DZf({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:fS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=UF({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:fS.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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.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=DZf({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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=UF({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:fS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Ez.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 DZf({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=UF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!jzn({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:fS.object({properties:d}),jsonExample:f}}function UF({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=SZf({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=jZf({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=S5r({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}=wZf({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 EZf=ko(umu(),1);function lOi({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:S4.ok(rN.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=UF({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&&jzn({typeDeclarations:n,typeReference:c.valueType}))continue;let o=UF({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?EF.exploded():EF.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&&jzn({typeDeclarations:n,typeReference:o.valueType}))continue;let l=UF({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=UF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!jzn({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:w}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=w}u.request=a$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=UF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=a$.reference(o);break}default:Lc(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=UF({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=S4.ok(rN.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:Lc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=S4.error({body:void 0,error:a.declaration.name});else{let c=UF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=S4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,EZf.default)(u),url:xSw(t,u),...u},jsonExample:void 0}}function xSw(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 GH({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,audiences:u,readme:f,packageName:d,version:c,context:o}){let l=z9t({generationLanguage:r,keywords:n,smartCasing:i}),g=new zMa(u),O=IAr({casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents}),w=(t.definition.rootApiFile.contents.errors??[]).map(Hr=>({error:w5r({errorName:Hr,file:O}),docs:void 0})),j=new ZA(t),M=new Din(t),q=new FMa(j,M),B=new Sin(t),I=new ODe(j),C=new EIt,L=new UMa(o,t),K={fdrApiDefinitionId:e,apiVersion:await ZXf({file:O,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:l.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await jMa(t.definition.rootApiFile.contents.docs),auth:await XXf({rawApiFileSchema:t.definition.rootApiFile.contents,file:O,propertyResolver:q,endpointResolver:M}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Hr,Gt])=>O2e({headerKey:Hr,header:Gt,file:O}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Hr,Gt])=>O2e({headerKey:Hr,header:Gt,file:O}))):[],types:{},errors:{},services:{},constants:LXf(l),environments:ETu({casingsGenerator:l,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:nZf(t.definition.rootApiFile.contents["error-discrimination"],O),basePath:t.definition.rootApiFile.contents["base-path"]!=null?g2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await Pzn({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:O,location:tCe.Root,variableResolver:C}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Hr,Gt])=>({docs:typeof Gt!="string"?Gt.docs:void 0,id:Hr,name:O.casingsGenerator.generateName(Hr),type:O.parseTypeReference(Gt)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},te=new RMa,J=async Hr=>{te.addSubpackage(Hr.fernFilepath),await VP(Hr.definitionFile,{imports:cl,docs:Gt=>{Gt!=null&&te.addDocs(Hr.fernFilepath,Gt)},types:async Gt=>{if(Gt!=null)for(let[wn,An]of Object.entries(Gt)){if(kTe(wn))continue;let Ht=await dZf({typeName:wn,typeDeclaration:An,file:Hr,typeResolver:j,exampleResolver:I,sourceResolver:L,workspace:t}),er=Ht.typeDeclaration;a&&(er.userProvidedExamples=[],er.autogeneratedExamples=[]);let dn=Ht.descendantFilepaths,fn=s1.generateTypeId(er.name);K.types[fn]=er,te.addType(fn,er),g.addType({declaredTypeName:er.name,descendantTypeIds:er.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Ht.propertiesByAudience,descendantFilepaths:dn}),g.markTypeForAudiences(er.name,KYf(An))}},errors:Gt=>{if(Gt==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[An,Ht]of Object.entries(Gt)){let er=tZf({errorName:An,errorDeclaration:Ht,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),dn=s1.generateErrorId(er.name);K.errors[dn]=er,te.addError(dn,er),g.addError(er)}},service:async Gt=>{if(Gt==null)return;let wn=await FXf({rootDefaultUrl:Hr.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:K.pathParameters,serviceDefinition:Gt,file:Hr,errorResolver:B,typeResolver:j,propertyResolver:q,exampleResolver:I,sourceResolver:L,globalErrors:w,variableResolver:C,workspace:t}),An=s1.generateServiceId(wn.name);K.services[An]=wn,te.addService(An,wn);let Ht={};wn.endpoints.forEach(er=>{a&&(er.autogeneratedExamples=[],er.userSpecifiedExamples=[]);let dn=Gt.endpoints[er.name.originalName];g.addEndpoint(wn,er,dn),Ht[er.name.originalName]=er}),Gt.audiences!=null&&g.markEndpointForAudience(wn.name,wn.endpoints,Gt.audiences),Object.entries(Gt.endpoints).map(([er,dn])=>{let fn=Ht[er];fn!=null&&dn.audiences!=null&&g.markEndpointForAudience(wn.name,[fn],dn.audiences)})},webhooks:async Gt=>{if(Gt==null)return;let wn=s1.generateWebhookGroupId(Hr.fernFilepath),An=await aZf({webhooks:Gt,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),Ht={};for(let er of An)Ht[er.name.originalName]=er;Object.entries(Gt).forEach(([er,dn])=>{let fn=Ht[er];fn!=null&&(g.addWebhook(Hr,fn,dn),dn.audiences!=null&&g.markWebhookForAudiences(Hr,fn,dn.audiences))}),K.webhookGroups[wn]=An,te.addWebhookGroup(wn,Hr.fernFilepath)},channel:async Gt=>{if(Gt==null)return;let wn=s1.generateWebSocketChannelId(Hr.fernFilepath),An=await kXf({channel:Gt,file:Hr,variableResolver:C,typeResolver:j,exampleResolver:I,workspace:t});K.websocketChannels!=null&&(K.websocketChannels[wn]=An,te.addWebSocketChannel(wn,Hr.fernFilepath))}})};await Rz(t,async(Hr,Gt,wn)=>{await J(qO({relativeFilepath:Hr,definitionFile:Gt,casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:wn.defaultUrl}))}),await Nrn(t,async(Hr,Gt)=>{if(Gt.navigation!=null)if(typeof Gt.navigation=="string")te.addPackageRedirection({from:oae({relativeFilepath:Hr,casingsGenerator:l}),to:oae({relativeFilepath:yf(cb(Hr),Ms.of(Gt.navigation)),casingsGenerator:l})});else{let wn=Gt.navigation.map(An=>s1.generateSubpackageId(oae({relativeFilepath:yf(cb(Hr),Ms.of(An)),casingsGenerator:l})));Hr===JA?te.sortRootPackage(wn):te.sortSubpackage(s1.generateSubpackageId(oae({relativeFilepath:Hr,casingsGenerator:l})),wn)}}),K.serviceTypeReferenceInfo=CSw(g);let G=a?K:TSw(K,o),re=t.definition.rootApiFile.contents,Xe=ETu({casingsGenerator:l,rawApiFileSchema:re}),Re=Xe?.environments._visit({singleBaseUrl:Hr=>Hr.environments.filter(Gt=>VMa(Gt.id,re.environments)!=null).length===0,multipleBaseUrls:Hr=>Hr.environments.filter(Gt=>VMa(Gt.id,re.environments)!=null).length===0,_other:()=>!1});Xe?.environments.environments.forEach(Hr=>{g.markEnvironmentForAudiences(Hr,VMa(Hr.id,re.environments)??[],Re)});let Dt=g.hasNoAudiences()?void 0:g.build(),Ct=qSw(G,Dt),Wt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Ct.services).every(Hr=>Hr.endpoints.every(Gt=>Gt.auth)),Bt=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="streaming")),or=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.pagination!=null)),jr=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="fileDownload")),Vr=f!=null?iZf({readme:f,services:K.services}):void 0,{types:It,services:cr}=_Zf(Ct);return{...Ct,...te.build(Dt),types:It,services:cr,sdkConfig:{isAuthMandatory:Wt,hasStreamingEndpoints:Bt,hasPaginatedEndpoints:or,hasFileDownloadEndpoints:jr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:c!=null&&d!=null?{header:"User-Agent",value:`${d}/${c}`}:void 0}},readmeConfig:Vr}}function TSw(e,t){for(let[r,n]of Object.entries(e.services))for(let i of n.endpoints){t.logger.debug(`Generating example for ${i.id}`);let a=lOi({ir:e,service:n,endpoint:i,typeDeclarations:e.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(a.type==="failure"){t.logger.debug(`Failed to generate example for ${i.id}. ${a.message}`);continue}let{example:u}=a;i.autogeneratedExamples=[{example:u}]}return e}function CSw(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 qSw(e,t){if(t==null)return e;let r=xZr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>gZf({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:wq.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:xZr(e.errors,u=>t.hasError(u)),services:by(xZr(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:ITu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?ITu({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:ISw(e.serviceTypeReferenceInfo,t)}}function ISw(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 RZf=ko(bMa(),1),FZf=ko(gMa(),1),JMa=require("fs/promises"),LZf=ko(hAa(),1);function L9t(e){return typeof e.subpackageId=="string"}function PDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Ein(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var BTu="__package__",E5r=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 L9t(t)?t.subpackageId:BTu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=LF.SubpackageId(t);return r===BTu?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=LF.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} ${PDe(u.path.parts)}`),d.push(`${o} ${Ein(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,PDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ein(u.path.parts))}`);let g=AZf(l);g!=null&&(d.push(`${o} ${k1(g,PDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ein(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} ${PDe(u.path.parts)}`),d.push(`${o} ${Ein(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,PDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,Ein(u.path.parts))}`);let g=AZf(l);g!=null&&(d.push(`${o} ${k1(g,PDe(u.path.parts))}`),d.push(`${o} ${k1(g,Ein(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.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let n=L9t(t)?[...r,t.name]:r,i=n.length===0?[BTu]: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.#d(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.#d(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 Yc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Yc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Yc.WebhookId(`${r}.${t.id}`)}};function AZf(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 Dzn=ko(bMa(),1),xZf=ko(gMa(),1);function MZf(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{}}Dzn.default.extend(xZf.default);var BSw="Changelog",NSw=["summary","index","overview"],Ain=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}toChangelogNode(t){let r=t.title??BSw,n=[],i;for(let l of this.changelogFiles??[]){let g=vJo(l.split("/"));if(g==null)continue;let O=MZf(g);if(O==null){let j=g.split(".")[0]?.toLowerCase();j!=null&&NSw.includes(j)&&(i=l);continue}let w=this.toRelativeFilepath(l);n.push({date:O,pageId:Yc.PageId(w),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??QW(r)}),u=n.map(l=>{let g=Dzn.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=NTu(u,l=>l.date,"desc"),d=i!=null?Yc.PageId(this.toRelativeFilepath(i)):void 0,c=this.idgen.get(d??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}groupByYear(t,r,n){let i=new Map;for(let a of r){let u=Dzn.default.utc(a.date).year(),f=i.get(u)??[];f.push(a),i.set(u,f)}return NTu(Array.from(i.entries()).map(([a,u])=>{let f=n.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,n),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,n){let i=new Map;for(let a of r){let u=Dzn.default.utc(a.date).month()+1,f=i.get(u)??[];f.push(a),i.set(u,f)}return NTu(Array.from(i.entries()).map(([a,u])=>{let f=(0,Dzn.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.format("MMMM YYYY"),month:a,slug:n.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}};function NTu(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 WMa=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;#s;disableEndpointPairs;constructor(t,r,n,i,a,u,f,d){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Yc.V1.ApiDefinitionId(r.id),this.#e=E5r.create(r,u),this.#s=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Yc.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??QW(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#o=this.#y(this.#o.map(o=>this.#g(o)),this.#j(this.#e.api.rootPackage,this.#c))}get(){let t=Yc.V1.followRedirects(this.#o);return{id:this.#s.get(this.apiDefinitionId),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 Ain(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(r=>r.absoluteFilepath),this.docsWorkspace,this.#s).toChangelogNode({parentSlug:this.#c,viewers:[]}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,n){r=this.#e.resolveSubpackage(r);let i=r!=null?E5r.getSubpackageId(r):void 0;return t.map(a=>NAa(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:Yc.Url(u.url)}),page:u=>this.#d(u,n),package:u=>this.#v(u,n),section:u=>this.#_(u,n),item:({value:u})=>this.#p(u,i,n),endpoint:u=>this.#P(u,i,n)})).filter(QM)}#d(t,r){let n=Yc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??QW(t.title)});return{id:this.#s.get(n),type:"page",pageId:n,title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=E5r.getSubpackageId(a),f=this.#s.get(n??`${this.apiDefinitionId}:${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,[u]);let d=t.slug??(L9t(a)?a.urlSlug:this.apiSection.slug??QW(this.apiSection.title)),c=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(L9t(a)?a.displayName??pin(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??QW(t.package),f=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#u(t.contents,void 0,f);return{id:this.#s.get(n??`${this.apiDefinitionId}:${QW(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:f.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(n??i??r.get()),u=t.referencedSubpackages.map(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?E5r.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(QM);this.#a.set(a,u),u.forEach(o=>{this.#r.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#r.add(o)});let f=t.slug??QW(t.title),d=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,d);return{id:a,type:"apiPackage",children:c,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,n){t=t.trim();let i=this.#e.getSubpackageByIdOrLocator(t);if(i!=null){let a=E5r.getSubpackageId(i),u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#r.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#r.add(a),this.#a.set(u,[a]);let f=L9t(i)?i.urlSlug:"",d=n.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:L9t(i)?i.displayName??pin(i.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}return this.#P({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0},r,n)}#P(t,r,n){let i=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.endpoints.get(LF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(i!=null){let f=this.#e.getEndpointId(i);if(f==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let d=t.slug!=null?n.append(t.slug):n.apply(i);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:i.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:t.title??i.name??PDe(i.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.webSockets.get(LF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??PDe(a.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(LF.SubpackageId(r))?.webhooks.get(LF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Yc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??k1("/",...u.path),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=Yc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,i);return{...t,children:u,pointsTo:Yc.V1.followRedirects(u)}}return t}#j(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??PDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.websockets.forEach(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??PDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned: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:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??pin(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.subpackages.forEach(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=L9t(a)?r.apply(a):r,f=this.#m(i,u);f.length>0&&n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:L9t(a)?a.displayName??pin(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:Yc.V1.followRedirects(f),noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned: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}#m(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.#j(n,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Yc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Yc.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} ${PDe(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:Yc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}};var TZf=ko(require("crypto"),1);function zSw(e){return TZf.default.createHash("sha256").update(e).digest("hex")}var HMa=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#n(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),zSw(r===0?t:`${t}-${r}`)}#i(t){let r=this.#n(t),n=0;for(;this.#t.has(r);)if(r=this.#n(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Yc.V1.NodeId(this.#i(t))}};function CZf(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 QMa=ko(t6t(),1);var DD=ko(t6t(),1);var A5r=ko(t6t(),1);function qZf(e){return e._visit({alias:t=>({type:"alias",value:jx(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:L5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>A5r.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:A5r.FernRegistry.PropertyKey(r.name.wireValue),valueType:jx(r.valueType),availability:L5(r.availability)})),extraProperties:USw(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:A5r.FernRegistry.PropertyKey(n.name.wireValue),valueType:jx(n.valueType),availability:L5(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?L5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[A5r.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:A5r.FernRegistry.PropertyKey(i.name.wireValue),valueType:jx(i.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_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:jx(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jx(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jx(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:jx(r),valueType:jx(n)}),optional:r=>({type:"optional",itemType:jx(r),defaultValue:void 0}),set:r=>({type:"set",itemType:jx(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:A5r.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>FSw(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>LSw(t.v2),string:()=>RSw(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 RSw(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 FSw(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 LSw(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 USw(e){return typeof e=="boolean"?iT.unknown():typeof e=="string"?{type:"id",value:A5r.FernRegistry.TypeId(e),default:void 0}:jx(e)}function RTu(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?WSw(r,t):[],webhooks:n!=null?VSw(n):[],websockets:i!=null?[HSw(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 VSw(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??_fi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jx(r.valueType),availability:L5(r.availability)})),payload:ZSw(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function WSw(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=>zTu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(zTu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=lOi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...zTu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:L5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:$Sw(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?QSw({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??_fi(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:jx(f.valueType),availability:void 0})),parts:[...Szn(n.basePath),...Szn(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:jx(f.valueType),availability:void 0})),parts:[...t.basePath!=null?Szn(t.basePath):[],...Szn(e.basePath),...Szn(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:jx(f.valueType),availability:L5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:jx(f.valueType),availability:L5(f.availability)})),request:n.requestBody!=null?KSw(n.requestBody):void 0,response:n.response!=null?YSw(n.response):void 0,errors:void 0,errorsV2:XSw(n.errors,t),examples:a};r.push(u)}return r}function HSw(e,t){return{auth:e.auth,availability:L5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?JSw({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??_fi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:jx(r.valueType),availability:void 0})),parts:Szn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:jx(r.valueType),description:r.docs,availability:L5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jx(r.valueType),availability:L5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:kSw(r.body),description:r.docs,availability:L5(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 L5(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:Lc(e.status)}}function QSw({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:Lc(r)}}function JSw({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:GSw(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Lc(r)}}function GSw(e,t){return e.replace(/^[^:]+/,t)}function $Sw(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 Szn(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 KSw(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??m4.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:jx(n.valueType),availability:L5(n.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??m4.APPLICATION_JSON,shape:{type:"reference",value:jx(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:jx(i.valueType),contentType:i.contentType,description:i.docs,availability:L5(i.availability)}),_other:()=>{}})).filter(QM)},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 YSw(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:jx(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:jx(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:jx(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 XSw(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:jx(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:jx(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},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 zTu({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(QM),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(cS(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(w=>typeof w=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:Sqt})}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=>Fje._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(QM)}}function ZSw(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:jx(t.valueType),availability:L5(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jx(e.payloadType)},description:e.docs};default:Lc(e)}}function kSw(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:jx(t.valueType),availability:L5(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:jx(e.bodyType)};default:Lc(e)}}var FTu=ko(t6t(),1);function IZf(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:FTu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:FTu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:Lc(n)}}function wDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:RTu(e.rootPackage,e),auth:IZf(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:L5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:jx(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[QMa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:qZf(a.shape),availability:L5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[QMa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:QMa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...RTu(a,e)}}return n}var LTu=ko(t6t(),1);async function UTu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await GH({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=Len({token:n.value}),c=wDe({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:LTu.FernRegistry.OrgId(e),apiId:LTu.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 eEw=new yin({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function BZf(e,t,r){return Fmi(Nmi(wDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),LF.ApiDefinitionId(t),eEw))}function NZf(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 NAr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}RZf.default.extend(FZf.default);var tEw=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),zZf=0,rEw=async({ir:e})=>(zZf++,`${e.apiName.snakeCase.unsafeName}-${zZf}`),zAr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=tEw,f=rEw){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=HMa.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await kxe.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=Oq(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 qAu({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 IAu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=NZf(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=Cmi(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)]=CAu(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=nEw(this.editThisPage,d);a[wIt.PageId(d)]={markdown:c,editThisPageUrl:o?wIt.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=kx(this.docsWorkspace.absoluteFilePath,c);(await(0,JMa.stat)(o)).isDirectory()?(await Bxe(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,JMa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return kx(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Oq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,LZf.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(NAr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?wIt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:wIt.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:wIt.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 toRootNode(){let t=Yc.V1.SlugGenerator.init(Yc.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}async toRootChild(t){return Fxn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??QW(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.version),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:Yc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:n,availability:t.availability!=null?iEw(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(i,f,n))),u=[];return a.forEach(f=>{switch(f.type){case"apiReference":case"section":u.push(f);return;case"changelog":case"link":case"page":{let d=u[u.length-1];d?.type!=="sidebarGroup"&&(d={id:this.#e.get(`${i}/group`),type:"sidebarGroup",children:[]},u.push(d)),d.children.push(f);return}default:Lc(f)}}),{type:"sidebarRoot",id:i,children:u}}async toNavigationChild(t,r,n){return Fxn(r)._visit({page:async i=>this.toPageNode(i,n),apiSection:async i=>this.toApiSectionNode(i,n),section:async i=>this.toSectionNode(t,i,n),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toApiSectionNode(t,r){let n=this.getFernWorkspaceForApiSection(t),i=CZf(t.snippetsConfiguration),a=await GH({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=BZf(a,u,{oauth:t.playground?.oauth});return new WMa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new Ain(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Yc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??QW(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:i.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toSectionNode(t,r,n){let i=this.toRelativeFilepath(r.overviewAbsolutePath),a=i?Yc.PageId(i):void 0,u=this.#e.get(a??`${t}/section`),f=n.apply({urlSlug:r.slug??QW(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}async convertTabbedNavigation(t,r,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return Fxn(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n)})}async toTabChangelogNode(t,r,n){return new Ain(this.markdownFilesToFullSlugs,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Yc.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),u=i.apply({urlSlug:r.slug??QW(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,u)}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):wIt.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(QM),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:wIt.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 Fxn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:wIt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function nEw(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${NAr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function iEw(e){switch(e){case"beta":return Yc.V1.NavigationV1Availability.Beta;case"deprecated":return Yc.V1.NavigationV1Availability.Deprecated;case"ga":return Yc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Yc.V1.NavigationV1Availability.Stable;default:Lc(e)}}var ksd=ko(JZf(),1),Cqu=ko(FCu(),1),ecd=ko(require("http"),1),VTa=ko(require("path"),1);var vnd=require("events"),Exa=ko(require("fs"),1),zin=ko(require("path"),1);var krd=ko(require("os"),1),end=300,I5r=20,COi=1e7,tnd=krd.default.platform();var Uqw=tnd==="darwin",LCu=tnd==="win32",B5r=Uqw||LCu,rnd=3e3,nnd=2e4,UCu=1250;var H9t;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(H9t||(H9t={}));var Nin;(function(e){e.CHANGE="change",e.RENAME="rename"})(Nin||(Nin={}));var qOi;(function(e){e.CHANGE="change",e.ERROR="error"})(qOi||(qOi={}));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 _k;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(_k||(_k={}));var Vqw=(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(),L=C-d,K=C-c,te=L>=t||K>=a;return[C,te]},l=C=>{if(c=C,!u)return;let L=u;u=void 0,e.apply(void 0,L)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},w=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,L]=o();return L?j(C):q(C)},q=C=>{let L=C-d,K=C-c,te=t-L,J=a-K,G=Math.min(te,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[L,K]=o(),te=!!f;if(u=C,d=L,(K||!f)&&B(t),K)return te?l(L):w(L)};return I.cancel=g,I.flush=O,I},wxa=Vqw;var JCu=ko(require("fs"),1),Dxa=ko(require("path"),1);var Dx=ko(require("fs"),1),$H=require("util");var RAr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Q9t=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var VCu=ko(require("process"),1),ind=VCu.default.getuid?!VCu.default.getuid():!1,and=1e4,lae=()=>{};var IOi={isChangeErrorOk:e=>{if(!IOi.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!ind&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!IOi.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(!IOi.isNodeError(e))throw e;if(!IOi.isChangeErrorOk(e))throw e}},Hz=IOi;var WCu=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=and,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()}}}}},ond=new WCu;var FAr=(e,t)=>function(n){return function i(...a){return ond.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)})}},LAr=(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 Wqw={attempt:{chmod:RAr((0,$H.promisify)(Dx.default.chmod),Hz.onChangeError),chown:RAr((0,$H.promisify)(Dx.default.chown),Hz.onChangeError),close:RAr((0,$H.promisify)(Dx.default.close),lae),fsync:RAr((0,$H.promisify)(Dx.default.fsync),lae),mkdir:RAr((0,$H.promisify)(Dx.default.mkdir),lae),realpath:RAr((0,$H.promisify)(Dx.default.realpath),lae),stat:RAr((0,$H.promisify)(Dx.default.stat),lae),unlink:RAr((0,$H.promisify)(Dx.default.unlink),lae),chmodSync:Q9t(Dx.default.chmodSync,Hz.onChangeError),chownSync:Q9t(Dx.default.chownSync,Hz.onChangeError),closeSync:Q9t(Dx.default.closeSync,lae),existsSync:Q9t(Dx.default.existsSync,lae),fsyncSync:Q9t(Dx.default.fsync,lae),mkdirSync:Q9t(Dx.default.mkdirSync,lae),realpathSync:Q9t(Dx.default.realpathSync,lae),statSync:Q9t(Dx.default.statSync,lae),unlinkSync:Q9t(Dx.default.unlinkSync,lae)},retry:{close:FAr((0,$H.promisify)(Dx.default.close),Hz.isRetriableError),fsync:FAr((0,$H.promisify)(Dx.default.fsync),Hz.isRetriableError),open:FAr((0,$H.promisify)(Dx.default.open),Hz.isRetriableError),readFile:FAr((0,$H.promisify)(Dx.default.readFile),Hz.isRetriableError),rename:FAr((0,$H.promisify)(Dx.default.rename),Hz.isRetriableError),stat:FAr((0,$H.promisify)(Dx.default.stat),Hz.isRetriableError),write:FAr((0,$H.promisify)(Dx.default.write),Hz.isRetriableError),writeFile:FAr((0,$H.promisify)(Dx.default.writeFile),Hz.isRetriableError),closeSync:LAr(Dx.default.closeSync,Hz.isRetriableError),fsyncSync:LAr(Dx.default.fsyncSync,Hz.isRetriableError),openSync:LAr(Dx.default.openSync,Hz.isRetriableError),readFileSync:LAr(Dx.default.readFileSync,Hz.isRetriableError),renameSync:LAr(Dx.default.renameSync,Hz.isRetriableError),statSync:LAr(Dx.default.statSync,Hz.isRetriableError),writeSync:LAr(Dx.default.writeSync,Hz.isRetriableError),writeFileSync:LAr(Dx.default.writeFileSync,Hz.isRetriableError)}},und=Wqw;var jxa=ko(require("fs"),1),BOi=ko(require("path"),1);var snd={then:e=>{e()}};var HCu=()=>{};var QCu=()=>{let e=HCu,t=HCu,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}};QCu.wrap=async e=>{let t=QCu();return await e(t),t.promise};var cnd=QCu;var lnd=e=>Array.isArray(e)?e:[e],fnd=e=>typeof e=="function",dnd=()=>{let{promise:e,resolve:t}=cnd(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var Hqw=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=lnd(a).map(It=>fnd(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=[],w=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,L={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:w,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:te,increment:J,decrement:G}=dnd(),re=0,Xe=(It,cr,Hr,Gt)=>{C.has(cr)||re>=i||(re+=1,It.directories.push(cr),It.directoriesNames.add(Hr),o.push(cr),l.add(Hr),g.propertyIsEnumerable(Hr)||(g[Hr]=[]),g[Hr].push(cr),C.add(cr),!(Gt>=n)&&(re>=i||or(cr,Gt+1)))},Re=(It,cr,Hr)=>{C.has(cr)||re>=i||(re+=1,It.files.push(cr),It.filesNames.add(Hr),O.push(cr),w.add(Hr),j.propertyIsEnumerable(Hr)||(j[Hr]=[]),j[Hr].push(cr),C.add(cr))},Dt=(It,cr,Hr,Gt)=>{C.has(cr)||re>=i||(re+=1,It.symlinks.push(cr),It.symlinksNames.add(Hr),M.push(cr),q.add(Hr),B.propertyIsEnumerable(Hr)||(B[Hr]=[]),B[Hr].push(cr),C.add(cr),r&&(Gt>=n||re>=i||jr(cr,Gt+1)))},Ct=(It,cr,Hr,Gt,wn)=>{d.aborted||f(cr)||(Gt.isDirectory()?Xe(It,cr,Hr,wn):Gt.isFile()?Re(It,cr,Hr):Gt.isSymbolicLink()&&Dt(It,cr,Hr,wn))},Wt=(It,cr,Hr,Gt)=>{if(d.aborted)return;let wn=cr===BOi.default.sep?"":BOi.default.sep,An=Hr.name,Ht=`${cr}${wn}${An}`;f(Ht)||(Hr.isDirectory()?Xe(It,Ht,An,Gt):Hr.isFile()?Re(It,Ht,An):Hr.isSymbolicLink()&&Dt(It,Ht,An,Gt))},Bt=(It,cr,Hr,Gt)=>{for(let wn=0,An=Hr.length;wn<An;wn++)Wt(It,cr,Hr[wn],Gt)},or=(It,cr)=>{d.aborted||cr>n||re>=i||(J(),jxa.default.readdir(It,{withFileTypes:!0},(Hr,Gt)=>{if(Hr||d.aborted||!Gt.length)return G();(c(Gt)||snd).then(()=>{let An=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(An,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),jxa.default.realpath(It,(Hr,Gt)=>{if(Hr||d.aborted)return G();jxa.default.stat(Gt,async(wn,An)=>{if(wn||d.aborted)return G();let Ht=BOi.default.basename(Gt),er=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(er,Gt,Ht,An,cr),G()})})};return(async(It,cr=1)=>(It=BOi.default.normalize(It),C.add(It),or(It,cr),await te,d.aborted?L:K))(e)},pnd=Hqw;var J9t={lang:{debounce:wxa,attempt:e=>{try{return e()}catch(t){return J9t.lang.castError(t)}},castArray:e=>J9t.lang.isArray(e)?e:[e],castError:e=>J9t.lang.isError(e)?e:J9t.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(J9t.lang.isNaN(e))return J9t.lang.isNaN(t);if(J9t.lang.isPrimitive(e)||J9t.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(Dxa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?JCu.default.realpathSync.native(e):JCu.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Dxa.default.sep&&t.length-e.length>Dxa.default.sep.length,poll:(e,t=nnd)=>und.retry.stat(t)(e,{bigint:!0}).catch(J9t.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 pnd(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=J9t;var Sxa=ko(require("path"),1);var GCu=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=end){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??I5r:Math.min(1,this.options.depth??I5r),u=this.options.limit??COi,[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&&!B5r&&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(Sxa.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(Sxa.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=Nin.CHANGE,r){if(this.watcher.isClosed())return;let n=Sxa.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){LCu&&t.code==="EPERM"?this.onWatcherChange(Nin.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(qOi.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(qOi.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Nin.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&B5r&&this.options.native!==!1?this.options.depth??I5r:Math.min(1,this.options.depth??I5r),n=this.options.limit??COi,[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(Nin.CHANGE,f,t)}))}}},_nd=GCu;var hk={interval:100,intervalId:void 0,fns:new Map,init:()=>{hk.intervalId||(hk.intervalId=setInterval(hk.resolve,hk.interval))},reset:()=>{hk.intervalId&&(clearInterval(hk.intervalId),delete hk.intervalId)},add:(e,t)=>{hk.fns.set(e,Date.now()+t),hk.init()},remove:e=>{hk.fns.delete(e)},resolve:()=>{if(!hk.fns.size)return hk.reset();let e=Date.now();for(let[t,r]of hk.fns)r>=e||(hk.remove(t),t())}},NOi=hk;var zOi=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=UCu){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),NOi.remove(c)},c=()=>{d(),f()};NOi.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=UCu){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),NOi.remove(c)},c=()=>{d(),f()};NOi.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,H9t.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,H9t.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,H9t.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,H9t.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}}};zOi.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};zOi.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var hnd=zOi;var $Cu=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}},KCu=$Cu;var YCu=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}},ynd=YCu;var XCu=class{constructor(){this.inos={},this.paths=new KCu,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 ynd(n)}reset(){this.inos={},this.paths=new KCu,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()?H9t.FILE:H9t.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)}}},ZCu=XCu;var kCu=class e extends vnd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(_k.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(_k.CLOSE,i)),this._readyWait=new Promise(i=>this.on(_k.READY,i)),this._locker=new hnd(this),this._roots=new Set,this._poller=new ZCu,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(_k.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(_k.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(_k.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(_k.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 _nd(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=zin.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??I5r))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&B5r&&o.options.native!==!1)))return!0;if(!B5r)break;let c=zin.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||B5r&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Exa.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},w=zin.default.dirname(f),j=f;await this.watchDirectories([w],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||B5r&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??I5r,f=r.limit??COi,[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)),w={...r,depth:O};await this.watchDirectories([l],w,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(_k.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(_k.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=zin.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new ZCu,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??rnd},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(_k.CLOSE,f),Exa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(_k.CLOSE,f),Exa.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=zin.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=zin.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(_k.ALL,n),r.readdirMap=void 0,this.ready())}},bnd=kCu;var eIw=ko(Pnd(),1),tIw=ko(l2u(),1),rIw=ko(d2u(),1),nIw=ko(g2u(),1),O2u=ko(gid(),1);var Jsd=ko(wTa(),1),Gsd=require("fs"),kAr=require("fs/promises"),LTa=require("os"),Aqu=ko(require("path"),1),$sd=require("stream/promises"),Ksd=ko(bne(),1),Ysd=ko(Qsd(),1),p3w="etag",Mqu="preview",_3w="bundle",xqu=".fern";function h3w(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu))}function UTa(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu),Ms.of(_3w))}function y3w(){return yf(v_.of((0,LTa.homedir)()),Ms.of(xqu),Ms.of(Mqu),Ms.of(p3w))}async function Xsd({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(await fetch(e)).text(),u=await new Ysd.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=y3w();if(r){let q=await Wh(c),B;if(q&&(t.debug("Reading existing ETag"),B=(await(0,kAr.readFile)(c)).toString()),B!=null&&B===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 Ksd.default.dir({prefix:"fern"}),l=v_.of(o.path);t.debug(`Downloading docs preview bundle from ${Aqu.default.join(e,d)}`);let g=await fetch(`${Aqu.default.join(e,d)}`);if(!g.ok)return t.error(`Failed to download docs preview bundle. ${g.statusText}`),{type:"failure"};let O=yf(l,Ms.of("output.zip")),w=g.body;if(w==null)return{type:"failure"};await(0,$sd.pipeline)(w,(0,Gsd.createWriteStream)(O)),t.debug(`Wrote output.zip to ${O}`);let j=h3w();await Wh(j)&&await(0,kAr.rm)(j,{recursive:!0}),await(0,kAr.mkdir)(j,{recursive:!0}),t.debug(`rm -rf ${j}`);let M=UTa();return await(0,kAr.mkdir)(M,{recursive:!0}),await(0,Jsd.default)(O,M),await(0,kAr.writeFile)(c,f),t.debug(`Downloaded bundle to ${M}`),{type:"success"}}async function Zsd({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 Tqu(r),f={},c=await new zAr(e,n,a,r,void 0,async g=>g.map(O=>{let w=Ozr();return f[w]={type:"url",url:Yc.Url(`/_local${p$o(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:w}}),async g=>u.addReferencedAPI(g)).resolve(),o=zxu({writeShape:c,files:{}}),l=Fxu({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 Tqu=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=Ozr(),a=Nmi(wDe({ir:t,snippetsConfig:r,playgroundConfig:n}),bU.ApiDefinitionId(i),new yin({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=Fmi(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 v3w={pages:{},apis:{},files:{},filesV2:{},config:{navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function qqu({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 Xsd({bucketUrl:I,logger:n.logger,preferCached:!0})}catch{let C=UTa();if(await Wh(C))n.logger.warn("Failed to download latest docs application. Falling back to existing bundle.");else{n.logger.warn("Failed to download docs application. Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,Cqu.default)(),d=ecd.default.createServer(f),c=new O2u.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,ksd.default)());let g=new URL(NAr(e.docsWorkspaces?.config.instances[0]?.url??`localhost:${i}`)),O=e,w,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 Zsd({domain:`${g.host}${g.pathname}`,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return w==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}
|
|
1985
1985
|
${C.stack}`),w}};w=await j();let M=O.apiWorkspaces.flatMap(I=>I.getAbsoluteFilePaths()),q=a?v_.of(VTa.default.resolve(a)):UTa();new bnd([u,...M],{recursive:!0,ignoreInitial:!0,debounce:1e3,renameDetection:!0}).on("all",async(I,C,L)=>{n.logger.info(nl.dim(`[${I}] ${C}`)),l({version:1,type:"startReload"});let K=await j();K!=null&&(w=K),l({version:1,type:"finishReload"})}),f.post("/v2/registry/docs/load-with-url",async(I,C)=>{try{let L=w??v3w,K={baseUrl:{domain:g.host,basePath:g.pathname},definition:L,lightModeEnabled:L.config.colorsV3?.type!=="dark"};C.send(K)}catch(L){n.logger.error("Error loading docs",L.message),C.status(500).send()}}),f.get(/^\/_local\/(.*)/,(I,C)=>C.sendFile(`/${I.params[0]}`)),f.get("/",(I,C,L)=>I.headers.upgrade==="websocket"?c.handleUpgrade(I,I.socket,Buffer.alloc(0),K=>{c.emit("connection",K,I)}):L()),f.use("/_next",Cqu.default.static(VTa.default.join(q,"/_next"))),f.use("*",async(I,C)=>C.sendFile(VTa.default.join(q,"/[[...slug]].html"))),f.listen(i),n.logger.info(`Running server on http://localhost:${i}`),await new Promise(()=>{})}var ZH={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function Y2(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(RRt)&&await t.exampleTypeReference?.(e,r);else if(cS(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 qIt(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 tcd({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":cl,"display-name":cl,availability:cl,headers:async n=>{await rcd({headers:n,visitor:t,nodePath:[...r,"headers"]})},audiences:cl,auth:cl,"path-parameters":async n=>{await WTa({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 b3w({endpointId:i,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:cl,transport:cl,source:cl})}async function b3w({endpointId:e,endpoint:t,service:r,visitor:n,nodePathForEndpoint:i}){let a=qIt(n);await n.httpEndpoint?.({endpointId:e,endpoint:t,service:r},i),await VP(t,{docs:Y2(n,i),"display-name":cl,availability:cl,"base-path":cl,path:cl,idempotent:cl,url:async u=>{await n.endpointBaseUrl?.({baseUrl:u,service:r},[...i,"url"])},"path-parameters":async u=>{await WTa({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:cl,docs:Y2(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:cl,docs:Y2(n,l),availability:cl,type:async g=>{await a(g,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":cl,audiences:cl,encoding:cl,default:cl,validation:cl})}},"content-type":cl,headers:async d=>{await rcd({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"}):_6(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:ZH.InlinedRequestProperty}):await VP(g,{name:cl,docs:Y2(n,O),availability:cl,type:async w=>{await a(w,[...O,"type"],{location:ZH.InlinedRequestProperty,_default:g.default,validation:g.validation})},"content-type":cl,audiences:cl,encoding:cl,default:cl,validation:cl})}},"extra-properties":cl})):(await Y2(n,c)(d.docs),await a(d.type,c))}})},audiences:cl,method:cl,auth:cl,"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:ZH.StreamingResponse}):await a(u.type,[...i,"response-stream"],{location:ZH.StreamingResponse}))},response:async u=>{if(u==null)return;let f=[...i,"response"];typeof u=="string"?await a(u,f,{location:ZH.Response}):await VP(u,{docs:Y2(n,f),type:async d=>{await a(d,[...f,"type"],{location:ZH.Response})},property:cl,"status-code":cl})},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:Y2(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 g3w({nodePathForExample:[...i,{key:"examples",arrayIndex:f}],visitor:n,service:r,endpoint:t,example:d})},pagination:cl})}async function g3w({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 Nen(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 WTa({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let n=qIt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.pathParameter?.({pathParameterKey:i,pathParameter:a},u),d6n(a)?typeof a=="string"?await t.variableReference?.(a,u):await VP(a,{docs:Y2(t,u),variable:async f=>await t.variableReference?.(f,[...u,"variable"]),availability:cl}):typeof a=="string"?await n(a,u):await VP(a,{docs:Y2(t,u),type:async f=>{await n(f,[...u,"type"],{_default:a.default,validation:a.validation})},availability:cl,encoding:cl,default:cl,validation:cl,name:cl,audiences:cl})}}async function rcd({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=qIt(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:cl,availability:cl,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:Y2(t,u),audiences:cl,encoding:cl,env:cl,default:cl,validation:cl})}}async function ncd({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 Iqu({typeName:n,declaration:i,visitor:t,nodePathForType:a})}}async function Iqu({typeName:e,declaration:t,visitor:r,nodePathForType:n}){let i=qIt(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 Mz(t,{alias:async u=>{typeof u=="string"?await i(u,n):await VP(u,{type:async f=>{await i(f,[...n,"type"])},docs:Y2(r,n),availability:cl,audiences:cl,examples:a,validation:cl,encoding:cl,source:cl})},object:async u=>{await VP(u,{docs:Y2(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:cl,docs:Y2(r,o),availability:cl,type:async l=>{await i(l,[...o,"type"],{_default:c.default,validation:c.validation})},audiences:cl,encoding:cl,default:cl,validation:cl})}},"extra-properties":cl,availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},discriminatedUnion:async u=>{await VP(u,{docs:Y2(r,n),discriminant:cl,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:Y2(r,o),name:cl,key:cl,type:async l=>{typeof l=="string"&&await i(l,[...n,"type"])},"display-name":cl,availability:cl})}},"base-properties":cl,availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},undiscriminatedUnion:async u=>{await VP(u,{docs:Y2(r,n),discriminated:cl,union:async f=>{for(let[d,c]of f.entries()){let o=[...n,`union[${d}]`];typeof c!="string"&&await VP(c,{docs:Y2(r,o),type:async l=>{await i(l,[...n,"type"])},"display-name":cl})}},availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},enum:async u=>{await VP(u,{docs:Y2(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:Y2(r,c),name:cl,value:cl,casing:cl})}},availability:cl,audiences:cl,default:cl,encoding:cl,source:cl,examples:a})}})}async function icd({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 m3w({errorName:n,declaration:i,visitor:t,nodePathForError:a})}}async function m3w({errorName:e,declaration:t,visitor:r,nodePathForError:n}){let i=qIt(r);typeof t=="string"?await i(t,n):await VP(t,{docs:Y2(r,n),"status-code":cl,type:async a=>{if(a==null)return;let u=[...n,"type"];typeof a=="string"?await i(a,u):await Iqu({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 acd({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 ocd({webhook:e,visitor:t,nodePathForWebhook:r}){let n=qIt(t);await VP(e,{"display-name":cl,method:cl,examples:cl,headers:async i=>{await O3w({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(P3w(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:cl,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:ZH.InlinedRequestProperty}):await VP(c,{name:cl,docs:Y2(t,o),availability:cl,type:async l=>{await n(l,[...o,"type"],{_default:c.default,validation:c.validation,location:ZH.InlinedRequestProperty})},audiences:cl,encoding:cl,default:cl,validation:cl})}}})},audiences:cl,availability:cl,docs:Y2(t,r)})}async function O3w({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=qIt(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:cl,availability:cl,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:Y2(t,u),audiences:cl,encoding:cl,env:cl,default:cl,validation:cl})}}function P3w(e){return e.type!=null}async function kH(e,t){await VP(e,{docs:Y2(t,[]),imports:async r=>{await acd({imports:r,visitor:t,nodePath:["imports"]})},types:async r=>{await ncd({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:async r=>{r!=null&&await tcd({service:r,visitor:t,nodePath:["service"]})},webhooks:async r=>{for(let[n,i]of Object.entries(r??{}))await ocd({webhook:i,visitor:t,nodePathForWebhook:["webhooks",n]})},channel:cl,errors:async r=>{await icd({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}async function Bqu(e,t){await VP(e,{docs:cl,imports:cl,types:cl,service:cl,webhooks:cl,errors:cl,channel:cl,export:async r=>{await t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:async r=>{await t.navigation?.(r,["navigation"])}})}async function Nqu(e,t){await t.file?.(e,[]),await VP(e,{version:cl,name:cl,"default-url":cl,"display-name":cl,imports:cl,auth:cl,"idempotency-headers":cl,"auth-schemes":async r=>{await Promise.all(Object.entries(r??{}).map(async([n,i])=>{wiu(i)&&await t.oauth?.({name:n,oauth:i},["auth-scheme",n])}))},pagination:cl,"default-environment":async r=>{await t.defaultEnvironment?.(r,["default-environment"])},docs:cl,headers:cl,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:cl,errors:async r=>{if(r!=null)for(let n of r)await t.errorReference?.(n,["errors",n])},"base-path":cl,"path-parameters":async r=>{await WTa({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 HTa=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function ucd({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 scd({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 ccd({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 w3w(e,t,r){if(!Lie(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 j3w(e){return Number(e.replace("v",""))}async function D3w(e){let t=xfa({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 zqu={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=xfa({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=j3w(e["ir-version"]);else{let f=await D3w(e);if(f==null)return[];a=f}if(a<=i)return[];let u=await r.generators.cli.getMinCliForIr(a);return u.ok?w3w(e.name,u.body.version,t)??[]:[]}}})};var Rqu={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(nAr(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 QTa(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(f6n(r))for(let n of Object.keys(r.urls))t.includes(n)||t.push(n);return t},[])}var Fqu={name:"matching-environment-urls",create:({workspace:e})=>{let t=QTa(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 iEr(n,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let f of t)u.urls[f]==null&&a(f)}}),i}}}}};var Lqu={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=S3w(e.definition.namedDefinitionFiles);return{definitionFile:{import:async({importPath:r},{relativeFilepath:n})=>{let i=t[n];if(i==null)return[];let a=P5r({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 S3w(e){let t={};for(let r of yzt(e))t[r]=lcd(r,[r],e);return t}function lcd(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=P5r({referencedIn:e,importPath:Ms.of(a)});t.includes(u)?t[0]===u&&t[0]===E3w(t)&&n.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):n.push(...lcd(u,[...t,u],r))}return n}function E3w(e){return e.reduce((t,r)=>r<t?r:t)}var XM=z9t({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var JTa=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new ZA(t)}isTypeComplex(t,r){let n=qO({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:XM,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:Lc(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:Lc(t)}}isNamedTypeComplex({type:t,file:r,visited:n}){if(n.has(t.rawName))return!1;if(n.add(t.rawName),nNr(t.declaration))return!0;if(w6t(t.declaration))return!1;if(gA(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:n});if(_6n(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}Lc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:n,visited:i}){return SIt({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:Lc(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:Lc(t)}}};var Uqu={name:"no-complex-query-params",create:({workspace:e})=>{let t=new JTa(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 Vqu={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===SMa?[{severity:"error",message:`Path parameter ${nl.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function vPi({service:e,endpoint:t}){return e["base-path"]+t.path}var GTa=class{root=new Wqu;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 vPi({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},Wqu=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 Hqu={name:"no-conflicting-endpoint-paths",create:async({workspace:e})=>{let t=new GTa;return await Rz(e,async(r,n)=>{await kH(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 ${vPi({service:r,endpoint:n})} conflicts with other endpoints:`,...u.map(f=>` - ${f.relativeFilepath} -> ${f.endpointId} ${nl.dim(vPi({service:f.service,endpoint:f.endpoint}))}`)].join(`
|
|
1986
1986
|
`)}]}}}}};var Qqu={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:n,relativeFilepath:i})=>{let a=A3w({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.
|
|
1987
1987
|
`+d.map(c=>` - ${M3w(c)}`).join(`
|