fern-api 0.70.1 → 0.70.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1718,7 +1718,7 @@ ${G$p.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&sfc(th
1718
1718
  `+mtn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?mtn.default.cyan(tGp(t,this.opt.mask)):mtn.default.italic(mtn.default.dim("[hidden]")):this.opt.mask?tGp(t,this.opt.mask):mtn.default.italic(mtn.default.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 oGo=ui(u5(),1),EQp=ui(DQp(),1),MQp=ui(YAe(),1);var o7a=class extends s5{_run(t){this.done=t,this.editorResult=new MQp.Subject;let r=r$(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?oGo.default.dim("Received"):oGo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=oGo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,EQp.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 BQp=require("stream");var TQp=ui(require("readline"),1),CQp=ui(qQp(),1),Mtn=class{constructor(t){this.rl||=TQp.default.createInterface(HQD(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 HQD(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new CQp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var u7a=class extends Mtn{constructor(t={}){super(t),this.log=new BQp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return VNa(this.rl,this.bottomBar.split(`
1719
1719
  `).length),this}updateBottomBar(t){return VNa(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+`
1720
1720
  `}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&&I$o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var CM=ui(YAe(),1),xQp=ui(cNa(),1);var uGo=ui(YAe(),1),IQp=ui(cNa(),1),sGo=function(e,t,r){return typeof e[t]!="function"?(0,uGo.of)(e):(0,uGo.from)((0,IQp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var zQp={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,u)=>{n==="__proto__"||n==="constructor"||(a===u.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((u,c)=>u!=null?u[c]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},OWn=class extends Mtn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,CM.from)(t):(0,CM.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,CM.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,CM.from)([t]),this.process=i.pipe((0,CM.concatMap)(this.processQuestion.bind(this)),(0,CM.publish)()),this.process.connect(),this.process.pipe((0,CM.reduce)((n,a)=>(zQp.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,CM.defer)(()=>(0,CM.of)(t).pipe((0,CM.concatMap)(this.setDefaultType.bind(this)),(0,CM.concatMap)(this.filterIfRunnable.bind(this)),(0,CM.concatMap)(()=>sGo(t,"message",this.answers)),(0,CM.concatMap)(()=>sGo(t,"default",this.answers)),(0,CM.concatMap)(()=>sGo(t,"choices",this.answers)),(0,CM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,CM.defer)(()=>(0,CM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,CM.defer)(()=>(0,CM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&zQp.get(this.answers,t.name)!==void 0)return CM.EMPTY;if(t.when===!1)return CM.EMPTY;if(typeof t.when!="function")return(0,CM.of)(t);let{answers:r}=this;return(0,CM.defer)(()=>(0,CM.from)((0,xQp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,CM.filter)(i=>i!=null)))}};function RQp(e){let t=function(r,i){let n;try{n=new OWn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",HNa),this.registerPrompt("input",Otn),this.registerPrompt("number",$Na),this.registerPrompt("confirm",GNa),this.registerPrompt("rawlist",QNa),this.registerPrompt("expand",JNa),this.registerPrompt("checkbox",KNa),this.registerPrompt("password",YNa),this.registerPrompt("editor",o7a)},t.restoreDefaultPrompts(),t}var tdc=RQp();function GQD(e,t){tdc.registerPrompt(e,t)}function QQD(){tdc.restoreDefaultPrompts()}var JQD={prompt:tdc,ui:{BottomBar:u7a,Prompt:OWn},createPromptModule:RQp,registerPrompt:GQD,restoreDefaultPrompts:QQD,Separator:cue},cGo=JQD;var CWn=require("path"),mKp=require("fs"),PKp=require("readline"),GJp="posthog-node";function xYD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[TGo.POSTHOG_ID_TAG];if(c===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],l=o.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(O=>({...O,platform:"node:javascript"}))}:void 0})),b={$exception_message:o[0]?.value||a.message,$exception_type:o[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:o[0]?.value||a.message,$sentry_exception_type:o[0]?.type,$sentry_tags:a.tags};return t&&r&&(b.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:b}),a}}var TGo=class{constructor(t,r,i,n){this.name=GJp,this.name=GJp,this.setupOnce=function(a,u){let c=u()?.getClient()?.getDsn()?.projectId;a(xYD(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};TGo.POSTHOG_ID_TAG="posthog_distinct_id";var DGo="0123456789abcdef",CGo=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=DGo.charAt(this.bytes[r]>>>4),t+=DGo.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=DGo.charAt(this.bytes[r]>>>4),t+=DGo.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},$dc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??RYD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return CGo.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,CGo.ofInner(t)}},RYD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),QJp,Gdc=()=>NYD().toString(),NYD=()=>(QJp||(QJp=new $dc)).generate();function FYD(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(u=>u.name!=="domainUncaughtExceptionClear"&&u._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function LYD(e,t){global.process.on("uncaughtException",FYD(e,t))}function UYD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var EGo,JJp,MGo;function VYD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return MGo&&r.length===JJp||(JJp=r.length,MGo=r.reduce((i,n)=>{EGo||(EGo={});let a=EGo[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let c=u.length-1;c>=0;c--){let s=u[c]?.filename,o=t[n];if(s&&o){i[s]=o,EGo[n]=[s,o];break}}}return i},{})),MGo}function WYD(e){return typeof Event<"u"&&jKp(e,Event)}function HYD(e){return wKp(e,"Object")}function epc(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return jKp(e,Error)}}function jKp(e,t){try{return e instanceof t}catch{return!1}}function $YD(e){return wKp(e,"ErrorEvent")}function wKp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function GYD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=SKp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await kYD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function SKp(e,t,r){let i=QYD(e,t,r);return i.cause?[i,...SKp(e,i.cause,r)]:[i]}function QYD(e,t,r){if(epc(t))return t;if(e.synthetic=!0,HYD(t)){let n=JYD(t);if(n)return n;let a=KYD(t),u=r?.syntheticException||new Error(a);return u.message=a,u}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function JYD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(epc(r))return r}}function KYD(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message '${e.message}'`),i}else if("message"in e&&typeof e.message=="string")return e.message;let t=XYD(e);if($YD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=YYD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function YYD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function XYD(e,t=40){let r=Object.keys(ZYD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return KJp(i,t);for(let n=r.length;n>0;n--){let a=r.slice(0,n).join(", ");if(!(a.length>t))return n===r.length?a:KJp(a,t)}return""}function KJp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function ZYD(e){return epc(e)?{message:e.message,name:e.name,stack:e.stack,...YJp(e)}:WYD(e)?{type:e.type,target:XJp(e.target),currentTarget:XJp(e.currentTarget),...YJp(e)}:e}function YJp(e){if(typeof e=="object"&&e!==null){let t={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function XJp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function kYD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=eXD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function eXD(e,t){return tXD(e(t.stack||"",1),e)}function tXD(e,t){let r=VYD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var rXD=2e3,AWn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let c=await GYD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||Gdc(),properties:{...c,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(LYD(this.onException.bind(this),this.onFatalError.bind(this)),UYD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(rXD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function iXD(e=process.argv[1]?(0,CWn.dirname)(process.argv[1]):process.cwd(),t=CWn.sep==="\\"){let r=t?ZJp(e):e;return i=>{if(!i)return;let n=t?ZJp(i):i,{dir:a,base:u,ext:c}=CWn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(u=u.slice(0,c.length*-1));let d=decodeURIComponent(u);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let o=a.slice(r.length+1).replace(/\//g,".");return o?`${o}:${d}`:d}return d}}function ZJp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var BGo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}},qGo=new BGo(25),DKp=new BGo(20),tpc=7,nXD=1e3,aXD=1e4;async function oXD(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],u=a?.filename;if(!a||typeof u!="string"||typeof a.lineno!="number"||lXD(u)||fXD(a))continue;t[u]||(t[u]=[]),t[u].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(DKp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=pXD(a);if(u.every(d=>dXD(n,d)))continue;let c=_XD(qGo,n,{});i.push(uXD(n,u,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&sXD(e,qGo),qGo.reduce(),e}function uXD(e,t,r){return new Promise(i=>{let n=(0,mKp.createReadStream)(e),a=(0,PKp.createInterface)({input:n});function u(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],l=s[1];function b(){DKp.set(e,1),a.close(),a.removeAllListeners(),u()}n.on("error",b),a.on("error",b),a.on("close",u),a.on("line",g=>{if(c++,!(c<o)&&(r[c]=hXD(g,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let O=t[d];if(O===void 0){a.close(),a.removeAllListeners();return}o=O[0],l=O[1]}})})}function sXD(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;cXD(r.lineno,r,i)}}function cXD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=EKp(e);n<e;n++){let a=r[n];if(a===void 0){kJp(t);return}t.pre_context.push(a)}if(r[e]===void 0){kJp(t);return}t.context_line=r[e];let i=MKp(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function kJp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function lXD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function fXD(e){return e.lineno!==void 0&&e.lineno>aXD||e.colno!==void 0&&e.colno>nXD}function dXD(e,t){let r=qGo.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function pXD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=eKp(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+tpc:(n.push(i),i=eKp(a)),t++}return n}function eKp(e){return[EKp(e),MKp(e)]}function EKp(e){return Math.max(1,e-tpc)}function MKp(e){return e+tpc}function _XD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function hXD(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}var yXD="4.18.0",hue;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.DecideEndpointWasHit="decide_endpoint_was_hit",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config"})(hue||(hue={}));var tKp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(tKp||(tKp={}));var rKp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(rKp||(rKp={}));var iKp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(iKp||(iKp={}));var nKp;(function(e){e.Html="html",e.Text="text"})(nKp||(nKp={}));var aKp;(function(e){e.Number="number",e.Emoji="emoji"})(aKp||(aKp={}));var oKp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(oKp||(oKp={}));var uKp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(uKp||(uKp={}));var sKp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(sKp||(sKp={}));var cKp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(cKp||(cKp={}));var vXD=e=>{if("flags"in e){let t=gXD(e.flags),r=OXD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,AKp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,bXD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function bXD(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var gXD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,rpc(r)]).filter(([,t])=>t!==void 0)),OXD=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?AKp(i):void 0]}))},rpc=e=>e===void 0?void 0:e.variant??e.enabled,AKp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},mXD=1,PXD=new Set(["61be3dd8","96f6df5f","8cfdba9b","bf027177","e59430a8","7fa5500b","569798e9","04809ff7","0ebc61a5","32de7f98","3beeb69a","12d34ad9","733853ec","0645bb64","5dcbee21","b1f95fa3","2189e408","82b460c2","3a8cc979","29ef8843","2cdbf767","38084b54","50f9f8de","41d0df91","5c236689","c11aedd3","ada46672","f4331ee1","42fed62a","c957462c","d62f705a","e0162666","01b3e5cf","441cef7f","bb9cafee","8f348eb0","b2553f3a","97469d7d","39f21a76","03706dcc","27d50569","307584a7","6433e92e","150c7fbb","49f57f22","3772f65b","01eb8256","3c9e9234","f853c7f7","c0ac4b67","cd609d40","10ca9b1a","8a87f11b","8e8e5216","1f6b63b3","db7943dd","79b7164c","07f78e33","2d21b6fd","952db5ee","a7d3b43f","1924dd9c","84e1b8f6","dff631b6","c5aa8a79","fa133a95","498a4508","24748755","98f3d658","21bbda67","7dbfed69","be3ec24c","fc80b8e2","75cc0998"]),jXD="utf8";function wXD(e,t){if(!e||typeof e!="string"||SXD(e))throw new Error(t)}function SXD(e){return e.trim().length===0}function DXD(e){return e?.replace(/\/+$/,"")}async function EXD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function lKp(){return new Date().getTime()}function Wdc(){return new Date().toISOString()}function IGo(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function MXD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function AXD(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return(t>>>0).toString(16).padStart(8,"0")}function qXD(e,t=0,r){let i=AXD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function fKp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var g7a=String.fromCharCode,dKp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",AGo={};function TXD(e,t){if(!AGo[e]){AGo[e]={};for(let r=0;r<e.length;r++)AGo[e][e.charAt(r)]=r}return AGo[e][t]}var EWn={compressToBase64:function(e){if(e==null)return"";let t=EWn._compress(e,6,function(r){return dKp.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:EWn._decompress(e.length,32,function(t){return TXD(dKp,e.charAt(t))})},compress:function(e){return EWn._compress(e,16,function(t){return g7a(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,c,d="",s="",o="",l=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++)}for(c=2,u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:EWn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,c=4,d=3,s="",o,l,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=g7a(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=g7a(b);break;case 2:return""}for(i[3]=P,l=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[c++]=g7a(b),P=c-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[c++]=g7a(b),P=c-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),u--,l=s,u==0&&(u=Math.pow(2,d),d++)}}},Qdc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}},qWn=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},O7a=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function pKp(e){if(e instanceof qWn){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Hdc(e){return typeof e=="object"&&(e instanceof qWn||e instanceof O7a)}function _Kp(e){return typeof e=="object"&&e instanceof qWn&&e.status===413}var Jdc;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Jdc||(Jdc={}));var Kdc=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new Qdc,this._isInitialized=!1,wXD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=DXD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.preloadFeatureFlags=r?.preloadFeatureFlags??!0,this.defaultOptIn=r?.defaultOptIn??!0,this.disableSurveys=r?.disableSurveys??!1,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:Hdc},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r?.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(hue.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(hue.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(hue.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=Gdc();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let c=qXD(this.apiKey,mXD,PXD)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>vXD(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(c===void 0)return{response:void 0,requestId:void 0};let d=rpc(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,u){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,u){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,u){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),u&&(c.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes(Jdc.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let u=`Surveys API could not be loaded: ${a.status}`,c=new Error(u);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(u));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(hue.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(hue.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(hue.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(hue.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:n}),this.setPersistedProperty(hue.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=IGo(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:Wdc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${lKp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(EWn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,c)}catch(d){this._events.emit("error",d)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:Wdc(),uuid:i?.uuid?i.uuid:Gdc()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await pKp(t)})}async flush(){let t=fKp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),fKp([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(hue.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(b=>b.message),u=()=>{let g=(this.getPersistedProperty(hue.Queue)||[]).slice(n.length);this.setPersistedProperty(hue.Queue,g),t=g},c={api_key:this.apiKey,batch:a,sent_at:Wdc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${lKp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,o=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(EWn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},l={retryCheck:b=>_Kp(b)?!1:Hdc(b)};try{await this.fetchWithRetry(s,o,l)}catch(b){if(_Kp(b)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw b instanceof O7a||u(),this._events.emit("error",b),b}u(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let o=new AbortController;return setTimeout(()=>o.abort(),s),o.signal});let u=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(u,jXD)}catch{c=new TextEncoder().encode(u).length}return await EXD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new O7a(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new qWn(d,c);return d},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(hue.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Hdc(n))throw n;await pKp(n)}};return Promise.race([new Promise((n,a)=>{IGo(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}},Ydc=MXD();if(!Ydc){let e=$Jp();Ydc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var qKp=Ydc,zGo=class{constructor(t){this.factory=t}async getValue(){return this.value!==void 0?this.value:(this.initializationPromise===void 0&&(this.initializationPromise=(async()=>{try{let t=await this.factory();return this.value=t,t}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return this.value!==void 0}async waitForInitialization(){this.isInitialized()||await this.getValue()}},TKp=new zGo(async()=>{try{return await import("crypto")}catch{return}});async function CXD(){return await TKp.getValue()}var BXD=new zGo(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await TKp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function IXD(){return await BXD.getValue()}async function zXD(e){let t=await CXD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await IXD();if(r){let i=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var xXD=60*1e3,RXD=1152921504606847e3,NXD=["is_not"],MWn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},c5=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Xdc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||qKp,this.onError=c.onError,this.customHeaders=u,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,c;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){c=d;break}if(c!==void 0)try{u=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof c5?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async d=>{try{let s=await this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof c5||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),c=!0}})),{response:a,payloads:u,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new c5("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let d=this.groupTypeMapping[String(c)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new c5("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return await this.matchFeatureFlagProperties(t,i[d],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,c,d=[...a].sort((s,o)=>{let l=!!s.variant,b=!!o.variant;return l&&b?0:l?-1:b?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,l=n.multivariate?.variants||[];o&&l.some(b=>b.key===o)?c=o:c=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof c5)u=!0;else throw o}if(c!==void 0)return c;if(u)throw new c5("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let d=c.type,s=!1;if(d==="cohort"?s=BKp(c,n,this.cohorts,this.debugMode):s=CKp(c,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await hKp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await hKp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(xXD,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof MWn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=IGo(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,i=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;n=IGo(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function hKp(e,t,r=""){let i=await zXD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/RXD}function CKp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new c5("Operator is_not_set is not supported")}else throw new c5(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!NXD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,o){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,l){if(l==="gt")return s>o;if(l==="gte")return s>=o;if(l==="lt")return s<o;if(l==="lte")return s<=o;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,u);case"is_not":return!c(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return yKp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return yKp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=FXD(String(n));if(s==null&&(s=vKp(n)),s==null)throw new c5(`Invalid date: ${n}`);let o=vKp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new c5(`Unknown operator: ${a}`)}}function BKp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new c5("can't match cohort without a given cohort property value");let a=r[n];return IKp(a,t,r,i)}function IKp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let c of a)try{let d=IKp(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let d;c.type==="cohort"?d=BKp(c,t,r,i):d=CKp(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("can't match cohort without a given cohort property value");return n==="AND"}}function yKp(e){try{return new RegExp(e),!0}catch{return!1}}function vKp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new c5(`${e} is in an invalid date format`)}else throw new c5(`The date provided ${e} must be a string, number, or date object`)}function FXD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var Zdc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},LXD=100,bKp=30*1e3,UXD=50*1e3,kdc=class extends Kdc{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Zdc,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,LXD):bKp,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');this.featureFlagsPoller=new Xdc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new AWn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||UXD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):qKp(t,r)}getLibraryVersion(){return yXD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:c,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:c,disableGeoip:d,uuid:s})},l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,b=Promise.resolve().then(async()=>{if(u)return await l(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})});this.addPendingPromise(b)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:c,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:c,disableGeoip:d,uuid:s}),l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await l(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:n},{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=bKp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=l!==void 0,g,O;if(!b&&!u){let P=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(P===void 0)return;O=P.response,l=rpc(O),g=P?.requestId}let m=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(m))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(m):this.distinctIdHasSentFlagCalls[r]=[m],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:O?.metadata?.id,$feature_flag_version:O?.metadata?.version,$feature_flag_reason:O?.reason?.description??O?.reason?.code,locally_evaluated:b,[`$feature/${t}`]:l,$feature_flag_request_id:g},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,o);s=l.allPersonProperties,o=l.allGroupProperties;let b;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),d==null&&(d=!0),c==null&&(c=!1),!(b!==void 0)&&!c&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:c}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,c);u=d.allPersonProperties,c=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,c),o={},l={},b=!0;if(s&&(o=s.response,l=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,c,n);o={...o,...g.flags||{}},l={...l,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let c of Object.keys(r))u[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");AWn.captureException(this,t,{syntheticException:n},r,i)}},gKp=/\(error: (.*)\)/,zKp=50,xKp="?";function VXD(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,c,d,s;if(n[1]){c=n[1];let b=c.lastIndexOf(".");if(c[b-1]==="."&&b--,b>0){a=c.slice(0,b),u=c.slice(b+1);let g=a.indexOf(".Module");g>0&&(c=c.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||xKp,c=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!l&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:c,lineno:OKp(n[3]),colno:OKp(n[4]),in_app:WXD(o||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function WXD(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function OKp(e){return parseInt(e||"",10)||void 0}function HXD(e){return[90,VXD(e)]}function $XD(e){let r=[HXD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
1721
- `);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=gKp.test(d)?d.replace(gKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=zKp)break}}return GXD(a)}}function GXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,zKp).map(r=>({...r,filename:r.filename||QXD(t).filename,function:r.function||xKp}))}function QXD(e){return e[e.length-1]||{}}AWn.stackParser=$XD(iXD());AWn.frameModifiers=[oXD];var TWn=class extends kdc{getLibraryId(){return"posthog-node"}};var xGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new TWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.70.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var m7a=class{async sendEvent(){}async identify(){}async flush(){}};var BWn=require("fs/promises"),LKp=require("os"),UKp=require("path");var RKp=ui(require("crypto")),NGo=new Uint8Array(256),RGo=NGo.length;function ipc(){return RGo>NGo.length-16&&(RKp.default.randomFillSync(NGo),RGo=0),NGo.slice(RGo,RGo+=16)}var a$=[];for(let e=0;e<256;++e)a$.push((e+256).toString(16).slice(1));function NKp(e,t=0){return a$[e[t+0]]+a$[e[t+1]]+a$[e[t+2]]+a$[e[t+3]]+"-"+a$[e[t+4]]+a$[e[t+5]]+"-"+a$[e[t+6]]+a$[e[t+7]]+"-"+a$[e[t+8]]+a$[e[t+9]]+"-"+a$[e[t+10]]+a$[e[t+11]]+a$[e[t+12]]+a$[e[t+13]]+a$[e[t+14]]+a$[e[t+15]]}var FKp=ui(require("crypto")),npc={randomUUID:FKp.default.randomUUID};function JXD(e,t,r){if(npc.randomUUID&&!t&&!e)return npc.randomUUID();e=e||{};let i=e.random||(e.rng||ipc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return NKp(i)}var yue=JXD;var KXD="id",YXD=".fern",P7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new TWn(r),this.userId=t==null?void 0:Wac(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.70.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,LKp.homedir)()),za.of(YXD),za.of(KXD));await Cf(t)||(await(0,BWn.mkdir)((0,UKp.dirname)(t),{recursive:!0}),await(0,BWn.writeFile)(t,yue())),this.persistedDistinctId=(await(0,BWn.readFile)(t)).toString()}return this.persistedDistinctId}};var apc;async function IWn(){return apc==null&&(apc=await XXD()),apc}async function XXD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new m7a;let r=await eLo();return r!=null?new P7a({token:r,posthogApiKey:e}):await qUn()!=null?new xGo({posthogApiKey:e}):new P7a({token:void 0,posthogApiKey:e})}catch{return new m7a}}function j7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:ZXD}=Object.prototype,{getPrototypeOf:upc}=Object,{iterator:LGo,toStringTag:WKp}=Symbol,UGo=(e=>t=>{let r=ZXD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),UGt=e=>(e=e.toLowerCase(),t=>UGo(t)===e),VGo=e=>t=>typeof t===e,{isArray:zWn}=Array,w7a=VGo("undefined");function S7a(e){return e!==null&&!w7a(e)&&e.constructor!==null&&!w7a(e.constructor)&&vue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var HKp=UGt("ArrayBuffer");function kXD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&HKp(e.buffer),t}var eZD=VGo("string"),vue=VGo("function"),$Kp=VGo("number"),D7a=e=>e!==null&&typeof e=="object",tZD=e=>e===!0||e===!1,FGo=e=>{if(UGo(e)!=="object")return!1;let t=upc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(WKp in e)&&!(LGo in e)},rZD=e=>{if(!D7a(e)||S7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},iZD=UGt("Date"),nZD=UGt("File"),aZD=UGt("Blob"),oZD=UGt("FileList"),uZD=e=>D7a(e)&&vue(e.pipe),sZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||vue(e.append)&&((t=UGo(e))==="formdata"||t==="object"&&vue(e.toString)&&e.toString()==="[object FormData]"))},cZD=UGt("URLSearchParams"),[lZD,fZD,dZD,pZD]=["ReadableStream","Request","Response","Headers"].map(UGt),_ZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function E7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(S7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function GKp(e,t){if(S7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var Itn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,QKp=e=>!w7a(e)&&e!==Itn;function opc(){let{caseless:e}=QKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&GKp(t,n)||n;FGo(t[a])&&FGo(i)?t[a]=opc(t[a],i):FGo(i)?t[a]=opc({},i):zWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&E7a(arguments[i],r);return t}var hZD=(e,t,r,{allOwnKeys:i}={})=>(E7a(t,(n,a)=>{r&&vue(n)?e[a]=j7a(n,r):e[a]=n},{allOwnKeys:i}),e),yZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),vZD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},bZD=(e,t,r,i)=>{let n,a,u,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&upc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},gZD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},OZD=e=>{if(!e)return null;if(zWn(e))return e;let t=e.length;if(!$Kp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},mZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&upc(Uint8Array)),PZD=(e,t)=>{let i=(e&&e[LGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},jZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},wZD=UGt("HTMLFormElement"),SZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),VKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),DZD=UGt("RegExp"),JKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};E7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},EZD=e=>{JKp(e,(t,r)=>{if(vue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(vue(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},MZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zWn(e)?i(e):i(String(e).split(t)),r},AZD=()=>{},qZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function TZD(e){return!!(e&&vue(e.append)&&e[WKp]==="FormData"&&e[LGo])}var CZD=e=>{let t=new Array(10),r=(i,n)=>{if(D7a(i)){if(t.indexOf(i)>=0)return;if(S7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zWn(i)?[]:{};return E7a(i,(u,c)=>{let d=r(u,n+1);!w7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},BZD=UGt("AsyncFunction"),IZD=e=>e&&(D7a(e)||vue(e))&&vue(e.then)&&vue(e.catch),KKp=((e,t)=>e?setImmediate:t?((r,i)=>(Itn.addEventListener("message",({source:n,data:a})=>{n===Itn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),Itn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",vue(Itn.postMessage)),zZD=typeof queueMicrotask<"u"?queueMicrotask.bind(Itn):typeof process<"u"&&process.nextTick||KKp,xZD=e=>e!=null&&vue(e[LGo]),hs={isArray:zWn,isArrayBuffer:HKp,isBuffer:S7a,isFormData:sZD,isArrayBufferView:kXD,isString:eZD,isNumber:$Kp,isBoolean:tZD,isObject:D7a,isPlainObject:FGo,isEmptyObject:rZD,isReadableStream:lZD,isRequest:fZD,isResponse:dZD,isHeaders:pZD,isUndefined:w7a,isDate:iZD,isFile:nZD,isBlob:aZD,isRegExp:DZD,isFunction:vue,isStream:uZD,isURLSearchParams:cZD,isTypedArray:mZD,isFileList:oZD,forEach:E7a,merge:opc,extend:hZD,trim:_ZD,stripBOM:yZD,inherits:vZD,toFlatObject:bZD,kindOf:UGo,kindOfTest:UGt,endsWith:gZD,toArray:OZD,forEachEntry:PZD,matchAll:jZD,isHTMLForm:wZD,hasOwnProperty:VKp,hasOwnProp:VKp,reduceDescriptors:JKp,freezeMethods:EZD,toObjectSet:MZD,toCamelCase:SZD,noop:AZD,toFiniteNumber:qZD,findKey:GKp,global:Itn,isContextDefined:QKp,isSpecCompliantForm:TZD,toJSONObject:CZD,isAsyncFn:BZD,isThenable:IZD,setImmediate:KKp,asap:zZD,isIterable:xZD};function xWn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}hs.inherits(xWn,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:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var YKp=xWn.prototype,XKp={};["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=>{XKp[e]={value:e}});Object.defineProperties(xWn,XKp);Object.defineProperty(YKp,"isAxiosError",{value:!0});xWn.from=(e,t,r,i,n,a)=>{let u=Object.create(YKp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),xWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=xWn;var ZKp=ui(odc(),1),WGo=ZKp.default;function spc(e){return hs.isPlainObject(e)||hs.isArray(e)}function eYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function kKp(e,t,r){return e?e.concat(t).map(function(n,a){return n=eYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function RZD(e){return hs.isArray(e)&&!e.some(spc)}var NZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function FZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new(WGo||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&RZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=eYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?kKp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return spc(O)?!0:(t.append(kKp(P,m,a),s(O)),!1)}let l=[],b=Object.assign(NZD,{defaultVisitor:o,convertValue:s,isVisitable:spc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,b))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var wxi=FZD;function tYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function rYp(e,t){this._pairs=[],e&&wxi(e,this,t)}var iYp=rYp.prototype;iYp.append=function(t,r){this._pairs.push([t,r])};iYp.toString=function(t){let r=t?function(i){return t.call(this,i,tYp)}:tYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var nYp=rYp;function LZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ztn(e,t,r){if(!t)return e;let i=r&&r.encode||LZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new nYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var cpc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},lpc=cpc;var RWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var sYp=ui(require("crypto"),1);var aYp=ui(require("url"),1),oYp=aYp.default.URLSearchParams;var fpc="abcdefghijklmnopqrstuvwxyz",uYp="0123456789",cYp={DIGIT:uYp,ALPHA:fpc,ALPHA_DIGIT:fpc+fpc.toUpperCase()+uYp},UZD=(e=16,t=cYp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);sYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},lYp={isNode:!0,classes:{URLSearchParams:oYp,FormData:WGo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:cYp,generateString:UZD,protocols:["http","https","file","data"]};var _pc={};Na(_pc,{hasBrowserEnv:()=>ppc,hasStandardBrowserEnv:()=>VZD,hasStandardBrowserWebWorkerEnv:()=>WZD,navigator:()=>dpc,origin:()=>HZD});var ppc=typeof window<"u"&&typeof document<"u",dpc=typeof navigator=="object"&&navigator||void 0,VZD=ppc&&(!dpc||["ReactNative","NativeScript","NS"].indexOf(dpc.product)<0),WZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",HZD=ppc&&window.location.href||"http://localhost";var iq={..._pc,...lYp};function hpc(e,t){return wxi(e,new iq.classes.URLSearchParams,{visitor:function(r,i,n,a){return iq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function $ZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function GZD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function QZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=GZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t($ZD(i),n,r,0)}),r}return null}var HGo=QZD;function JZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ypc={transitional:RWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(HGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return hpc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return wxi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),JZD(t)):t}],transformResponse:[function(t){let r=this.transitional||ypc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:iq.classes.FormData,Blob:iq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{ypc.headers[e]={}});var NWn=ypc;var KZD=hs.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"]),fYp=e=>{let t={},r,i,n;return e&&e.split(`
1721
+ `);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=gKp.test(d)?d.replace(gKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=zKp)break}}return GXD(a)}}function GXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,zKp).map(r=>({...r,filename:r.filename||QXD(t).filename,function:r.function||xKp}))}function QXD(e){return e[e.length-1]||{}}AWn.stackParser=$XD(iXD());AWn.frameModifiers=[oXD];var TWn=class extends kdc{getLibraryId(){return"posthog-node"}};var xGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new TWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.70.2",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var m7a=class{async sendEvent(){}async identify(){}async flush(){}};var BWn=require("fs/promises"),LKp=require("os"),UKp=require("path");var RKp=ui(require("crypto")),NGo=new Uint8Array(256),RGo=NGo.length;function ipc(){return RGo>NGo.length-16&&(RKp.default.randomFillSync(NGo),RGo=0),NGo.slice(RGo,RGo+=16)}var a$=[];for(let e=0;e<256;++e)a$.push((e+256).toString(16).slice(1));function NKp(e,t=0){return a$[e[t+0]]+a$[e[t+1]]+a$[e[t+2]]+a$[e[t+3]]+"-"+a$[e[t+4]]+a$[e[t+5]]+"-"+a$[e[t+6]]+a$[e[t+7]]+"-"+a$[e[t+8]]+a$[e[t+9]]+"-"+a$[e[t+10]]+a$[e[t+11]]+a$[e[t+12]]+a$[e[t+13]]+a$[e[t+14]]+a$[e[t+15]]}var FKp=ui(require("crypto")),npc={randomUUID:FKp.default.randomUUID};function JXD(e,t,r){if(npc.randomUUID&&!t&&!e)return npc.randomUUID();e=e||{};let i=e.random||(e.rng||ipc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return NKp(i)}var yue=JXD;var KXD="id",YXD=".fern",P7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new TWn(r),this.userId=t==null?void 0:Wac(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.70.2",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,LKp.homedir)()),za.of(YXD),za.of(KXD));await Cf(t)||(await(0,BWn.mkdir)((0,UKp.dirname)(t),{recursive:!0}),await(0,BWn.writeFile)(t,yue())),this.persistedDistinctId=(await(0,BWn.readFile)(t)).toString()}return this.persistedDistinctId}};var apc;async function IWn(){return apc==null&&(apc=await XXD()),apc}async function XXD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new m7a;let r=await eLo();return r!=null?new P7a({token:r,posthogApiKey:e}):await qUn()!=null?new xGo({posthogApiKey:e}):new P7a({token:void 0,posthogApiKey:e})}catch{return new m7a}}function j7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:ZXD}=Object.prototype,{getPrototypeOf:upc}=Object,{iterator:LGo,toStringTag:WKp}=Symbol,UGo=(e=>t=>{let r=ZXD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),UGt=e=>(e=e.toLowerCase(),t=>UGo(t)===e),VGo=e=>t=>typeof t===e,{isArray:zWn}=Array,w7a=VGo("undefined");function S7a(e){return e!==null&&!w7a(e)&&e.constructor!==null&&!w7a(e.constructor)&&vue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var HKp=UGt("ArrayBuffer");function kXD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&HKp(e.buffer),t}var eZD=VGo("string"),vue=VGo("function"),$Kp=VGo("number"),D7a=e=>e!==null&&typeof e=="object",tZD=e=>e===!0||e===!1,FGo=e=>{if(UGo(e)!=="object")return!1;let t=upc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(WKp in e)&&!(LGo in e)},rZD=e=>{if(!D7a(e)||S7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},iZD=UGt("Date"),nZD=UGt("File"),aZD=UGt("Blob"),oZD=UGt("FileList"),uZD=e=>D7a(e)&&vue(e.pipe),sZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||vue(e.append)&&((t=UGo(e))==="formdata"||t==="object"&&vue(e.toString)&&e.toString()==="[object FormData]"))},cZD=UGt("URLSearchParams"),[lZD,fZD,dZD,pZD]=["ReadableStream","Request","Response","Headers"].map(UGt),_ZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function E7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(S7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function GKp(e,t){if(S7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var Itn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,QKp=e=>!w7a(e)&&e!==Itn;function opc(){let{caseless:e}=QKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&GKp(t,n)||n;FGo(t[a])&&FGo(i)?t[a]=opc(t[a],i):FGo(i)?t[a]=opc({},i):zWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&E7a(arguments[i],r);return t}var hZD=(e,t,r,{allOwnKeys:i}={})=>(E7a(t,(n,a)=>{r&&vue(n)?e[a]=j7a(n,r):e[a]=n},{allOwnKeys:i}),e),yZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),vZD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},bZD=(e,t,r,i)=>{let n,a,u,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&upc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},gZD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},OZD=e=>{if(!e)return null;if(zWn(e))return e;let t=e.length;if(!$Kp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},mZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&upc(Uint8Array)),PZD=(e,t)=>{let i=(e&&e[LGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},jZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},wZD=UGt("HTMLFormElement"),SZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),VKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),DZD=UGt("RegExp"),JKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};E7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},EZD=e=>{JKp(e,(t,r)=>{if(vue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(vue(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},MZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zWn(e)?i(e):i(String(e).split(t)),r},AZD=()=>{},qZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function TZD(e){return!!(e&&vue(e.append)&&e[WKp]==="FormData"&&e[LGo])}var CZD=e=>{let t=new Array(10),r=(i,n)=>{if(D7a(i)){if(t.indexOf(i)>=0)return;if(S7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zWn(i)?[]:{};return E7a(i,(u,c)=>{let d=r(u,n+1);!w7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},BZD=UGt("AsyncFunction"),IZD=e=>e&&(D7a(e)||vue(e))&&vue(e.then)&&vue(e.catch),KKp=((e,t)=>e?setImmediate:t?((r,i)=>(Itn.addEventListener("message",({source:n,data:a})=>{n===Itn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),Itn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",vue(Itn.postMessage)),zZD=typeof queueMicrotask<"u"?queueMicrotask.bind(Itn):typeof process<"u"&&process.nextTick||KKp,xZD=e=>e!=null&&vue(e[LGo]),hs={isArray:zWn,isArrayBuffer:HKp,isBuffer:S7a,isFormData:sZD,isArrayBufferView:kXD,isString:eZD,isNumber:$Kp,isBoolean:tZD,isObject:D7a,isPlainObject:FGo,isEmptyObject:rZD,isReadableStream:lZD,isRequest:fZD,isResponse:dZD,isHeaders:pZD,isUndefined:w7a,isDate:iZD,isFile:nZD,isBlob:aZD,isRegExp:DZD,isFunction:vue,isStream:uZD,isURLSearchParams:cZD,isTypedArray:mZD,isFileList:oZD,forEach:E7a,merge:opc,extend:hZD,trim:_ZD,stripBOM:yZD,inherits:vZD,toFlatObject:bZD,kindOf:UGo,kindOfTest:UGt,endsWith:gZD,toArray:OZD,forEachEntry:PZD,matchAll:jZD,isHTMLForm:wZD,hasOwnProperty:VKp,hasOwnProp:VKp,reduceDescriptors:JKp,freezeMethods:EZD,toObjectSet:MZD,toCamelCase:SZD,noop:AZD,toFiniteNumber:qZD,findKey:GKp,global:Itn,isContextDefined:QKp,isSpecCompliantForm:TZD,toJSONObject:CZD,isAsyncFn:BZD,isThenable:IZD,setImmediate:KKp,asap:zZD,isIterable:xZD};function xWn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}hs.inherits(xWn,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:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var YKp=xWn.prototype,XKp={};["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=>{XKp[e]={value:e}});Object.defineProperties(xWn,XKp);Object.defineProperty(YKp,"isAxiosError",{value:!0});xWn.from=(e,t,r,i,n,a)=>{let u=Object.create(YKp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),xWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=xWn;var ZKp=ui(odc(),1),WGo=ZKp.default;function spc(e){return hs.isPlainObject(e)||hs.isArray(e)}function eYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function kKp(e,t,r){return e?e.concat(t).map(function(n,a){return n=eYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function RZD(e){return hs.isArray(e)&&!e.some(spc)}var NZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function FZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new(WGo||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&RZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=eYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?kKp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return spc(O)?!0:(t.append(kKp(P,m,a),s(O)),!1)}let l=[],b=Object.assign(NZD,{defaultVisitor:o,convertValue:s,isVisitable:spc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,b))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var wxi=FZD;function tYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function rYp(e,t){this._pairs=[],e&&wxi(e,this,t)}var iYp=rYp.prototype;iYp.append=function(t,r){this._pairs.push([t,r])};iYp.toString=function(t){let r=t?function(i){return t.call(this,i,tYp)}:tYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var nYp=rYp;function LZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ztn(e,t,r){if(!t)return e;let i=r&&r.encode||LZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new nYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var cpc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},lpc=cpc;var RWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var sYp=ui(require("crypto"),1);var aYp=ui(require("url"),1),oYp=aYp.default.URLSearchParams;var fpc="abcdefghijklmnopqrstuvwxyz",uYp="0123456789",cYp={DIGIT:uYp,ALPHA:fpc,ALPHA_DIGIT:fpc+fpc.toUpperCase()+uYp},UZD=(e=16,t=cYp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);sYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},lYp={isNode:!0,classes:{URLSearchParams:oYp,FormData:WGo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:cYp,generateString:UZD,protocols:["http","https","file","data"]};var _pc={};Na(_pc,{hasBrowserEnv:()=>ppc,hasStandardBrowserEnv:()=>VZD,hasStandardBrowserWebWorkerEnv:()=>WZD,navigator:()=>dpc,origin:()=>HZD});var ppc=typeof window<"u"&&typeof document<"u",dpc=typeof navigator=="object"&&navigator||void 0,VZD=ppc&&(!dpc||["ReactNative","NativeScript","NS"].indexOf(dpc.product)<0),WZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",HZD=ppc&&window.location.href||"http://localhost";var iq={..._pc,...lYp};function hpc(e,t){return wxi(e,new iq.classes.URLSearchParams,{visitor:function(r,i,n,a){return iq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function $ZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function GZD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function QZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=GZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t($ZD(i),n,r,0)}),r}return null}var HGo=QZD;function JZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ypc={transitional:RWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(HGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return hpc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return wxi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),JZD(t)):t}],transformResponse:[function(t){let r=this.transitional||ypc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:iq.classes.FormData,Blob:iq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{ypc.headers[e]={}});var NWn=ypc;var KZD=hs.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"]),fYp=e=>{let t={},r,i,n;return e&&e.split(`
1722
1722
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&KZD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var dYp=Symbol("internals");function M7a(e){return e&&String(e).trim().toLowerCase()}function $Go(e){return e===!1||e==null?e:hs.isArray(e)?e.map($Go):String(e)}function YZD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var XZD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function vpc(e,t,r,i,n){if(hs.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!hs.isString(t)){if(hs.isString(i))return t.indexOf(i)!==-1;if(hs.isRegExp(i))return i.test(t)}}function ZZD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function kZD(e,t){let r=hs.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var FWn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let o=M7a(d);if(!o)throw new Error("header name must be a non-empty string");let l=hs.findKey(n,o);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=$Go(c))}let u=(c,d)=>hs.forEach(c,(s,o)=>a(s,o,d));if(hs.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(hs.isString(t)&&(t=t.trim())&&!XZD(t))u(fYp(t),r);else if(hs.isObject(t)&&hs.isIterable(t)){let c={},d,s;for(let o of t){if(!hs.isArray(o))throw TypeError("Object iterator must return a key-value pair");c[s=o[0]]=(d=c[s])?hs.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=M7a(t),t){let i=hs.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return YZD(n);if(hs.isFunction(r))return r.call(this,n,i);if(hs.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=M7a(t),t){let i=hs.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||vpc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=M7a(u),u){let c=hs.findKey(i,u);c&&(!r||vpc(i,i[c],c,r))&&(delete i[c],n=!0)}}return hs.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||vpc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return hs.forEach(this,(n,a)=>{let u=hs.findKey(i,a);if(u){r[u]=$Go(n),delete r[a];return}let c=t?ZZD(a):String(a).trim();c!==a&&delete r[a],r[c]=$Go(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return hs.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&hs.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1723
1723
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[dYp]=this[dYp]={accessors:{}}).accessors,n=this.prototype;function a(u){let c=M7a(u);i[c]||(kZD(n,u),i[c]=!0)}return hs.isArray(t)?t.forEach(a):a(t),this}};FWn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);hs.reduceDescriptors(FWn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});hs.freezeMethods(FWn);var y3=FWn;function A7a(e,t){let r=this||NWn,i=t||r,n=y3.from(i.headers),a=i.data;return hs.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function q7a(e){return!!(e&&e.__CANCEL__)}function pYp(e,t,r){n_.call(this,e??"canceled",n_.ERR_CANCELED,t,r),this.name="CanceledError"}hs.inherits(pYp,n_,{__CANCEL__:!0});var ZAe=pYp;function tar(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new n_("Request failed with status code "+r.status,[n_.ERR_BAD_REQUEST,n_.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function bpc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function gpc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function xtn(e,t,r){let i=!bpc(t);return e&&(i||r==!1)?gpc(e,t):t}var AYp=ui(s7a(),1),qYp=ui(require("http"),1),TYp=ui(require("https"),1),CYp=ui(require("util"),1),BYp=ui(gdc(),1),AOi=ui(require("zlib"),1);var Rtn="1.11.0";function T7a(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var ekD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Opc(e,t,r){let i=r&&r.Blob||iq.classes.Blob,n=T7a(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=ekD.exec(e);if(!a)throw new n_("Invalid URL",n_.ERR_INVALID_URL);let u=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new n_("Blob is not supported",n_.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new n_("Unsupported protocol "+n,n_.ERR_NOT_SUPPORT)}var Ftn=ui(require("stream"),1);var _Yp=ui(require("stream"),1);var mpc=Symbol("internals"),Ppc=class extends _Yp.default.Transform{constructor(t){t=hs.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!hs.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[mpc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[mpc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[mpc],a=n.maxRate,u=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,D=u,A,M=0;if(a){let E=Date.now();(!n.ts||(M=E-n.ts)>=c)&&(n.ts=E,A=s-n.bytes,n.bytes=A<0?-A:0,M=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},c-M);A<D&&(D=A)}D&&m>D&&m-D>o&&(P=g.subarray(D),g=g.subarray(0,D)),l(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},jpc=Ppc;var IYp=require("events");var yYp=ui(require("util"),1),vYp=require("stream");var{asyncIterator:hYp}=Symbol,tkD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[hYp]?yield*e[hYp]():yield e},GGo=tkD;var rkD=iq.ALPHABET.ALPHA_DIGIT+"-_",C7a=typeof TextEncoder=="function"?new TextEncoder:new yYp.default.TextEncoder,Ntn=`\r
1724
1724
  `,ikD=C7a.encode(Ntn),nkD=2,wpc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=hs.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Ntn}`;n?r=C7a.encode(String(r).replace(/\r?\n|\r\n?/g,Ntn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Ntn}`,this.headers=C7a.encode(a+Ntn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+nkD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;hs.isTypedArray(t)?yield t:yield*GGo(t),yield ikD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},akD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+iq.generateString(n,rkD)}=r||{};if(!hs.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=C7a.encode("--"+a+Ntn),c=C7a.encode("--"+a+"--"+Ntn),d=c.byteLength,s=Array.from(e.entries()).map(([l,b])=>{let g=new wpc(l,b);return d+=g.size,g});d+=u.byteLength*s.length,d=hs.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),vYp.Readable.from((async function*(){for(let l of s)yield u,yield*l.encode();yield c})())},bYp=akD;var gYp=ui(require("stream"),1),Spc=class extends gYp.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},OYp=Spc;var okD=(e,t)=>hs.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,mYp=okD;function ukD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let l=a,b=0;for(;l!==n;)b+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var PYp=ukD;function skD(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let o=Date.now(),l=o-r;l>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-l)))},()=>n&&u(n)]}var jYp=skD;var MOi=(e,t,r=3)=>{let i=0,n=PYp(50,250);return jYp(a=>{let u=a.loaded,c=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=c;i=u;let l={loaded:u,total:c,progress:c?u/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&o?(c-u)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},LWn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},UWn=e=>(...t)=>hs.asap(()=>e(...t));var wYp={flush:AOi.default.constants.Z_SYNC_FLUSH,finishFlush:AOi.default.constants.Z_SYNC_FLUSH},ckD={flush:AOi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:AOi.default.constants.BROTLI_OPERATION_FLUSH},SYp=hs.isFunction(AOi.default.createBrotliDecompress),{http:lkD,https:fkD}=BYp.default,dkD=/https:?/,DYp=iq.protocols.map(e=>e+":"),EYp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function pkD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function zYp(e,t,r){let i=t;if(!i&&i!==!1){let n=AYp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){zYp(a,t,a.href)}}var _kD=typeof process<"u"&&hs.kindOf(process)==="process",hkD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(u,c,d=>i=d).catch(c)}),ykD=({address:e,family:t})=>{if(!hs.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},MYp=(e,t)=>ykD(hs.isObject(e)?e:{address:e,family:t}),xYp=_kD&&function(t){return hkD(async function(i,n,a){let{data:u,lookup:c,family:d}=t,{responseType:s,responseEncoding:o}=t,l=t.method.toUpperCase(),b,g=!1,O;if(c){let me=mYp(c,Le=>hs.isArray(Le)?Le:[Le]);c=(Le,yt,De)=>{me(Le,yt,(Ae,Ct,Pe)=>{if(Ae)return De(Ae);let St=hs.isArray(Ct)?Ct.map(at=>MYp(at)):[MYp(Ct,Pe)];yt.all?De(Ae,St):De(Ae,St[0].address,St[0].family)})}}let m=new IYp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(D),t.signal&&t.signal.removeEventListener("abort",D),m.removeAllListeners()};a((me,Le)=>{b=!0,Le&&(g=!0,P())});function D(me){m.emit("abort",!me||me.type?new ZAe(null,t,O):me)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(D),t.signal&&(t.signal.aborted?D():t.signal.addEventListener("abort",D)));let A=xtn(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(A,iq.hasBrowserEnv?iq.origin:void 0),E=M.protocol||DYp[0];if(E==="data:"){let me;if(l!=="GET")return tar(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{me=Opc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Le){throw n_.from(Le,n_.ERR_BAD_REQUEST,t)}return s==="text"?(me=me.toString(o),(!o||o==="utf8")&&(me=hs.stripBOM(me))):s==="stream"&&(me=Ftn.default.Readable.from(me)),tar(i,n,{data:me,status:200,statusText:"OK",headers:new y3,config:t})}if(DYp.indexOf(E)===-1)return n(new n_("Unsupported protocol "+E,n_.ERR_BAD_REQUEST,t));let C=y3.from(t.headers).normalize();C.set("User-Agent","axios/"+Rtn,!1);let{onUploadProgress:z,onDownloadProgress:G}=t,I=t.maxRate,N,U;if(hs.isSpecCompliantForm(u)){let me=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=bYp(u,Le=>{C.set(Le)},{tag:`axios-${Rtn}-boundary`,boundary:me&&me[1]||void 0})}else if(hs.isFormData(u)&&hs.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let me=await CYp.default.promisify(u.getLength).call(u);Number.isFinite(me)&&me>=0&&C.setContentLength(me)}catch{}}else if(hs.isBlob(u)||hs.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=Ftn.default.Readable.from(GGo(u));else if(u&&!hs.isStream(u)){if(!Buffer.isBuffer(u))if(hs.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(hs.isString(u))u=Buffer.from(u,"utf-8");else return n(new n_("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",n_.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new n_("Request body larger than maxBodyLength limit",n_.ERR_BAD_REQUEST,t))}let Y=hs.toFiniteNumber(C.getContentLength());hs.isArray(I)?(N=I[0],U=I[1]):N=U=I,u&&(z||N)&&(hs.isStream(u)||(u=Ftn.default.Readable.from(u,{objectMode:!1})),u=Ftn.default.pipeline([u,new jpc({maxRate:hs.toFiniteNumber(N)})],hs.noop),z&&u.on("progress",EYp(u,LWn(Y,MOi(UWn(z),!1,3)))));let J;if(t.auth){let me=t.auth.username||"",Le=t.auth.password||"";J=me+":"+Le}if(!J&&M.username){let me=M.username,Le=M.password;J=me+":"+Le}J&&C.delete("authorization");let X;try{X=ztn(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(me){let Le=new Error(me.message);return Le.config=t,Le.url=t.url,Le.exists=!0,n(Le)}C.set("Accept-Encoding","gzip, compress, deflate"+(SYp?", br":""),!1);let oe={path:X,method:l,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:E,family:d,beforeRedirect:pkD,beforeRedirects:{}};!hs.isUndefined(c)&&(oe.lookup=c),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,oe.port=M.port,zYp(oe,t.proxy,E+"//"+M.hostname+(M.port?":"+M.port:"")+oe.path));let pe,de=dkD.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?TYp.default:qYp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?fkD:lkD),t.maxBodyLength>-1?oe.maxBodyLength=t.maxBodyLength:oe.maxBodyLength=1/0,t.insecureHTTPParser&&(oe.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(oe,function(Le){if(O.destroyed)return;let yt=[Le],De=+Le.headers["content-length"];if(G||U){let at=new jpc({maxRate:hs.toFiniteNumber(U)});G&&at.on("progress",EYp(at,LWn(De,MOi(UWn(G),!0,3)))),yt.push(at)}let Ae=Le,Ct=Le.req||O;if(t.decompress!==!1&&Le.headers["content-encoding"])switch((l==="HEAD"||Le.statusCode===204)&&delete Le.headers["content-encoding"],(Le.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":yt.push(AOi.default.createUnzip(wYp)),delete Le.headers["content-encoding"];break;case"deflate":yt.push(new OYp),yt.push(AOi.default.createUnzip(wYp)),delete Le.headers["content-encoding"];break;case"br":SYp&&(yt.push(AOi.default.createBrotliDecompress(ckD)),delete Le.headers["content-encoding"])}Ae=yt.length>1?Ftn.default.pipeline(yt,hs.noop):yt[0];let Pe=Ftn.default.finished(Ae,()=>{Pe(),P()}),St={status:Le.statusCode,statusText:Le.statusMessage,headers:new y3(Le.headers),config:t,request:Ct};if(s==="stream")St.data=Ae,tar(i,n,St);else{let at=[],Oe=0;Ae.on("data",function(bt){at.push(bt),Oe+=bt.length,t.maxContentLength>-1&&Oe>t.maxContentLength&&(g=!0,Ae.destroy(),n(new n_("maxContentLength size of "+t.maxContentLength+" exceeded",n_.ERR_BAD_RESPONSE,t,Ct)))}),Ae.on("aborted",function(){if(g)return;let bt=new n_("stream has been aborted",n_.ERR_BAD_RESPONSE,t,Ct);Ae.destroy(bt),n(bt)}),Ae.on("error",function(bt){O.destroyed||n(n_.from(bt,null,t,Ct))}),Ae.on("end",function(){try{let bt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=hs.stripBOM(bt))),St.data=bt}catch(bt){return n(n_.from(bt,null,t,St.request,St))}tar(i,n,St)})}m.once("abort",at=>{Ae.destroyed||(Ae.emit("error",at),Ae.destroy())})}),m.once("abort",me=>{n(me),O.destroy(me)}),O.on("error",function(Le){n(n_.from(Le,null,t,O))}),O.on("socket",function(Le){Le.setKeepAlive(!0,1e3*60)}),t.timeout){let me=parseInt(t.timeout,10);if(Number.isNaN(me)){n(new n_("error trying to parse `config.timeout` to int",n_.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(me,function(){if(b)return;let yt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||RWn;t.timeoutErrorMessage&&(yt=t.timeoutErrorMessage),n(new n_(yt,De.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,t,O)),D()})}if(hs.isStream(u)){let me=!1,Le=!1;u.on("end",()=>{me=!0}),u.once("error",yt=>{Le=!0,O.destroy(yt)}),u.on("close",()=>{!me&&!Le&&D(new ZAe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var RYp=iq.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,iq.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(iq.origin),iq.navigator&&/(msie|trident)/i.test(iq.navigator.userAgent)):()=>!0;var NYp=iq.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];hs.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),hs.isString(i)&&u.push("path="+i),hs.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var FYp=e=>e instanceof y3?{...e}:e;function VGt(e,t){t=t||{};let r={};function i(s,o,l,b){return hs.isPlainObject(s)&&hs.isPlainObject(o)?hs.merge.call({caseless:b},s,o):hs.isPlainObject(o)?hs.merge({},o):hs.isArray(o)?o.slice():o}function n(s,o,l,b){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s,l,b)}else return i(s,o,l,b)}function a(s,o){if(!hs.isUndefined(o))return i(void 0,o)}function u(s,o){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function c(s,o,l){if(l in t)return i(s,o);if(l in e)return i(void 0,s)}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:c,headers:(s,o,l)=>n(FYp(s),FYp(o),l,!0)};return hs.forEach(Object.keys({...e,...t}),function(o){let l=d[o]||n,b=l(e[o],t[o],o);hs.isUndefined(b)&&l!==c||(r[o]=b)}),r}var QGo=e=>{let t=VGt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:c}=t;t.headers=u=y3.from(u),t.url=ztn(xtn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&u.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let d;if(hs.isFormData(r)){if(iq.hasStandardBrowserEnv||iq.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(iq.hasStandardBrowserEnv&&(i&&hs.isFunction(i)&&(i=i(t)),i||i!==!1&&RYp(t.url))){let s=n&&a&&NYp.read(a);s&&u.set(n,s)}return t};var vkD=typeof XMLHttpRequest<"u",LYp=vkD&&function(e){return new Promise(function(r,i){let n=QGo(e),a=n.data,u=y3.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,o,l,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function D(){if(!P)return;let M=y3.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),C={data:!c||c==="text"||c==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};tar(function(G){r(G),m()},function(G){i(G),m()},C),P=null}"onloadend"in P?P.onloadend=D:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(D)},P.onabort=function(){P&&(i(new n_("Request aborted",n_.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new n_("Network Error",n_.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let E=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||RWn;n.timeoutErrorMessage&&(E=n.timeoutErrorMessage),i(new n_(E,C.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&hs.forEach(u.toJSON(),function(E,C){P.setRequestHeader(C,E)}),hs.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),c&&c!=="json"&&(P.responseType=n.responseType),s&&([b,O]=MOi(s,!0),P.addEventListener("progress",b)),d&&P.upload&&([l,g]=MOi(d),P.upload.addEventListener("progress",l),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new ZAe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=T7a(n.url);if(A&&iq.protocols.indexOf(A)===-1){i(new n_("Unsupported protocol "+A+":",n_.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var bkD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let o=s instanceof Error?s:this.reason;i.abort(o instanceof n_?o:new ZAe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new n_(`timeout ${t} of ms exceeded`,n_.ETIMEDOUT))},t),c=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>hs.asap(c),d}},UYp=bkD;var gkD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},OkD=async function*(e,t){for await(let r of mkD(e))yield*gkD(r,t)},mkD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},Dpc=(e,t,r,i)=>{let n=OkD(e,t),a=0,u,c=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){c(),d.close();return}let l=o.byteLength;if(r){let b=a+=l;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var KGo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",WYp=KGo&&typeof ReadableStream=="function",PkD=KGo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),HYp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},jkD=WYp&&HYp(()=>{let e=!1,t=new Request(iq.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),VYp=64*1024,Epc=WYp&&HYp(()=>hs.isReadableStream(new Response("").body)),JGo={stream:Epc&&(e=>e.body)};KGo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!JGo[t]&&(JGo[t]=hs.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new n_(`Response type '${t}' is not supported`,n_.ERR_NOT_SUPPORT,i)})})})(new Response);var wkD=async e=>{if(e==null)return 0;if(hs.isBlob(e))return e.size;if(hs.isSpecCompliantForm(e))return(await new Request(iq.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(hs.isArrayBufferView(e)||hs.isArrayBuffer(e))return e.byteLength;if(hs.isURLSearchParams(e)&&(e=e+""),hs.isString(e))return(await PkD(e)).byteLength},SkD=async(e,t)=>{let r=hs.toFiniteNumber(e.getContentLength());return r??wkD(t)},$Yp=KGo&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:c,onUploadProgress:d,responseType:s,headers:o,withCredentials:l="same-origin",fetchOptions:b}=QGo(e);s=s?(s+"").toLowerCase():"text";let g=UYp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&jkD&&r!=="get"&&r!=="head"&&(P=await SkD(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),z;if(hs.isFormData(i)&&(z=C.headers.get("content-type"))&&o.setContentType(z),C.body){let[G,I]=LWn(P,MOi(UWn(d)));i=Dpc(C.body,VYp,G,I)}}hs.isString(l)||(l=l?"include":"omit");let D="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:D?l:void 0});let A=await fetch(O,b),M=Epc&&(s==="stream"||s==="response");if(Epc&&(c||M&&m)){let C={};["status","statusText","headers"].forEach(N=>{C[N]=A[N]});let z=hs.toFiniteNumber(A.headers.get("content-length")),[G,I]=c&&LWn(z,MOi(UWn(c),!0))||[];A=new Response(Dpc(A.body,VYp,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let E=await JGo[hs.findKey(JGo,s)||"text"](A,e);return!M&&m&&m(),await new Promise((C,z)=>{tar(C,z,{data:E,headers:y3.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(D){throw m&&m(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new n_("Network Error",n_.ERR_NETWORK,e,O),{cause:D.cause||D}):n_.from(D,D&&D.code,e,O)}});var Mpc={http:xYp,xhr:LYp,fetch:$Yp};hs.forEach(Mpc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var GYp=e=>`- ${e}`,DkD=e=>hs.isFunction(e)||e===null||e===!1,YGo={getAdapter:e=>{e=hs.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!DkD(r)&&(i=Mpc[(u=String(r)).toLowerCase()],i===void 0))throw new n_(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1920,7 +1920,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
1920
1920
  2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
1921
1921
  For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n.executablePath}};U2a=new WeakMap;var weu=class extends cQn{constructor(t){super(t,"chrome")}launch(t={}){var r;return((r=t.headless)!==null&&r!==void 0?r:!0)===!0&&(!this.puppeteer.configuration.logLevel||this.puppeteer.configuration.logLevel==="warn")&&!process.env.PUPPETEER_DISABLE_HEADLESS_WARNING&&console.warn(["\x1B[1m\x1B[43m\x1B[30m","Puppeteer old Headless deprecation warning:\x1B[0m\x1B[33m"," In the near feature `headless: true` will default to the new Headless mode"," for Chrome instead of the old Headless implementation. For more"," information, please see https://developer.chrome.com/articles/new-headless/.",' Consider opting in early by passing `headless: "new"` to `puppeteer.launch()`',` If you encounter any bugs, please report them to https://github.com/puppeteer/puppeteer/issues/new/choose.\x1B[0m
1922
1922
  `].join(`
1923
- `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:c}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(ul(!a,"Browser should be launched with either pipe or debugging port - not both."),d.push("--remote-debugging-pipe")):d.push(`--remote-debugging-port=${a||0}`));let s=!1,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,Dy_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let l=d[o].split("=",2)[1];ul(typeof l=="string","`--user-data-dir` is malformed");let b=c;return b||(ul(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}}defaultArgs(t={}){let r=["--allow-pre-commit-input","--disable-background-networking","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-breakpad","--disable-client-side-phishing-detection","--disable-component-extensions-with-background-pages","--disable-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${Ey_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(c=>c.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?hko({browser:Lq.CHROME,channel:sSE(t)}):this.resolveExecutablePath()}};function sSE(e){switch(e){case"chrome":return T6.STABLE;case"chrome-dev":return T6.DEV;case"chrome-beta":return T6.BETA;case"chrome-canary":return T6.CANARY}}var pPc=ui(require("fs"),1),Min=require("fs/promises"),My_=ui(require("os"),1),Seu=ui(require("path"),1);vB();nq();var Deu=class extends cQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:c=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&ul(c===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${c||0}`));let s,o=!0,l=d.findIndex(g=>["-profile","--profile"].includes(g));if(l!==-1){if(s=d[l+1],!s||!pPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,Min.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await _Oc(Lq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(ul(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}else try{await(0,Min.unlink)(Seu.default.join(t,"user.js"));let i=Seu.default.join(t,"prefs.js.puppeteer");if(pPc.default.existsSync(i)){let n=Seu.default.join(t,"prefs.js");await(0,Min.unlink)(n),await(0,Min.rename)(i,n)}}catch(i){fg(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(My_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(c=>c.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var Ay_=require("path");var W2a=Object.freeze({chromium:"1108766",firefox:"latest"});var _Pc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},OQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},lQn,ymi,$2a,H2a,fQn=class extends x4a{constructor(t){let{configuration:r,...i}=t;switch(super(i),lQn.add(this),ymi.set(this,void 0),$2a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=W2a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=W2a.chromium;break}this.connect=this.connect.bind(this),this.launch=this.launch.bind(this),this.executablePath=this.executablePath.bind(this),this.defaultArgs=this.defaultArgs.bind(this),this.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return _Pc(this,$2a,r,"f"),OQt(this,lQn,"a",H2a).launch(t)}executablePath(t){return OQt(this,lQn,"a",H2a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=OQt(this,ymi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,Ay_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=OQt(this,$2a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return OQt(this,lQn,"a",H2a).product}defaultArgs(t={}){return OQt(this,lQn,"a",H2a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new nko(t)}};ymi=new WeakMap,$2a=new WeakMap,lQn=new WeakSet,H2a=function(){if(OQt(this,ymi,"f")&&OQt(this,ymi,"f").product===this.lastLaunchedProduct)return OQt(this,ymi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=W2a.chromium,_Pc(this,ymi,new weu(this),"f");break;case"firefox":this.defaultBrowserRevision=W2a.firefox,_Pc(this,ymi,new Deu(this),"f");break;default:throw new Error(`Unknown product: ${OQt(this,$2a,"f")}`)}return OQt(this,ymi,"f")};Wbc();k6a();var cSE=new fQn({isPuppeteerCore:!0}),{connect:b55,createBrowserFetcher:g55,defaultArgs:O55,executablePath:m55,launch:P55}=cSE;var i0_=require("os"),n0_=require("path"),a0_=ui(r0_(),1);function zME(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var o0_=()=>{var e,t,r,i,n,a,u,c,d,s,o,l,b,g,O,m,P,D,A,M,E,C,z,G,I,N,U,Y,J,X,oe,pe,de,me,Le,yt,De;let Ae=(0,a0_.cosmiconfigSync)("puppeteer").search(),Ct=Ae?Ae.config:{};if(Ct.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Ct.defaultProduct)!==null&&i!==void 0?i:"chrome",Ct.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Ct.executablePath,Ct.executablePath&&(Ct.skipDownload=!0),Ct.skipDownload=!!((b=(l=(o=(s=(d=(c=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&c!==void 0?c:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&l!==void 0?l:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Ct.skipDownload),Ct.skipDownload||(Ct.browserRevision=(P=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&P!==void 0?P:Ct.browserRevision,Ct.downloadHost=(M=(A=(D=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_host)!==null&&A!==void 0?A:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Ct.downloadHost,Ct.downloadPath=(z=(C=(E=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_path)!==null&&C!==void 0?C:process.env.npm_package_config_puppeteer_download_path)!==null&&z!==void 0?z:Ct.downloadPath),Ct.cacheDirectory=(U=(N=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&N!==void 0?N:Ct.cacheDirectory)!==null&&U!==void 0?U:(0,n0_.join)((0,i0_.homedir)(),".cache","puppeteer"),Ct.temporaryDirectory=(X=(J=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&J!==void 0?J:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Ct.temporaryDirectory,(oe=Ct.experiments)!==null&&oe!==void 0||(Ct.experiments={}),Ct.experiments.macArmChromiumEnabled=!!((me=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&me!==void 0?me:Ct.experiments.macArmChromiumEnabled),Ct.logLevel=(De=(yt=(Le=process.env.PUPPETEER_LOGLEVEL)!==null&&Le!==void 0?Le:process.env.npm_config_LOGLEVEL)!==null&&yt!==void 0?yt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Ct.logLevel,!zME(Ct.defaultProduct))throw new Error(`Unsupported product ${Ct.defaultProduct}`);return Ct};var xME=o0_(),RME=new fQn({isPuppeteerCore:!1,configuration:xME}),{connect:T95,createBrowserFetcher:C95,defaultArgs:B95,executablePath:I95,launch:u0_}=RME;var NME="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",FME={"Accept-Language":"en-US,en;q=0.9",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36","Accept-Encoding":"gzip, deflate, br, zstd",Connection:"keep-alive"};async function o8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),o8a(e,t-1,r*i,i);throw n}}async function s0_(){try{return await u0_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function LME(e,t){try{let r=await e.newPage();await r.setViewport({width:3072,height:2048,deviceScaleFactor:2,isMobile:!1,hasTouch:!1,isLandscape:!0}),await r.setExtraHTTPHeaders(FME),await r.setUserAgent(NME),await r.setJavaScriptEnabled(!0),await o8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await o8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function UME(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return await t.text()}catch{throw new Error("Failed to fetch page from source")}}async function Pjc({url:e,browser:t}){try{let r;if(t?r=await LME(t,e):r=await o8a(()=>UME(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function c0_(e){try{let t=await o8a(()=>fetch(e));if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);let r=await t.arrayBuffer();return new Uint8Array(r)}catch{throw new Error(`Failed to retrieve image from source url ${e}`)}}var VME=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function l0_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,gQn.join)(process.cwd(),"fern");try{let r=await WME(e,(0,gQn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function WME(e,t){let r=$ME(e),i=(0,gQn.join)(t,r);if(!HME(r))throw new Error(`${r} - file extension not supported`);if((0,Keu.existsSync)(i))return i;try{(0,Keu.mkdirSync)((0,gQn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await c0_(e);return Eu_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function HME(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let i=r.toLowerCase();return!(i&&!VME.includes(i))}function $ME(e){e.startsWith("http")&&(e=new URL(e).pathname);let t=e.split("#");if(t.length===0)return"image";let r=t[0];if(!r)return"image";let i=r.split("?");if(i.length===0)return"image";let n=i[0];return n&&decodeURIComponent(n.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function GME(e){let t=[];return If(e,"element",r=>{r.tagName==="img"&&Array.isArray(r.properties.className)&&r.properties.className.includes("rm-Logo-img")&&t.push(r)}),t.length>0?t:void 0}async function f0_(e,t){let r=NHn(e),i=GME(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await l0_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var d0_=28;async function p0_(e,t){e=new URL(e);let r=[];if(t){let n=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),n.push(await a.content()),await a.click(".rm-ThemeToggle"),n.push(await a.content())}catch{}await Promise.all(n.map(async a=>await f0_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=za.of(BJ(i[0]));return{light:n,dark:n,height:d0_}}if(i[0]!=null&&i[1]!=null){let n=za.of(BJ(i[0])),a=za.of(BJ(i[1]));return{light:n,dark:a,height:d0_}}}}var Yeu=class extends Gtn{url;logger;absolutePathToFernDirectory;constructor(t){super({context:t.context}),this.url=typeof t.url=="string"?new URL(t.url):t.url,this.logger=t.context.logger,this.absolutePathToFernDirectory=t.absolutePathToFernDirectory}async import({args:t,builder:r}){r.setLayout({layout:X7a});let i=await this.getHastForUrl(this.url),n=Fs_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let l=await this.scrapeTab({name:o.name,url:o.url});if(!l)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Bu(this.absolutePathToFernDirectory,za.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:l});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:l});for(let m of O)b.addItem({item:m})}let a=await s0_(),u=await p0_(this.url,a);u!=null&&r.setLogo({logo:u});let c=await ci_(i);r.setTitle({title:c});let d=await ai_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),l=await fetch(d);if(l.ok){let b=Buffer.from(await l.arrayBuffer()),g=Bu(o,za.of("favicon"));await(0,URi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:Gae(this.absolutePathToFernDirectory,g)})}}let s=await Us_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Bu(this.absolutePathToFernDirectory,za.of("assets"));return await(0,URi.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let i=new URL(r,this.url),n=await this.getHastForUrl(i),a=xs_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=Rs_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}catch(i){this.logger.error(`Failed to scrape tab ${t}: ${i instanceof Error?i.message:String(i)}`),i instanceof Error&&i.stack&&this.logger.error(`Stack trace: ${i.stack}`)}}async getHastForUrl(t){let r=await Pjc({url:t});return NHn(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let i of r){this.logger.debug(`Processing section: ${i.group}`);let n=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i});await(0,URi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let c=await Pjc({url:u}),d=await zs_({logger:this.logger,html:c,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,URi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,l])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Bu(n,za.of(l)),m=zd(O);await(0,URi.mkdir)(m,{recursive:!0}),await(0,URi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.toString()}, skipping`)})),await Promise.all(i.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:n,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let i=[];for(let n of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let c of n.pages)if(c.type==="page")u.contents.push({page:c.page,path:Gae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Bu(t,za.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Bu(t,za.of(this.kebabCaseWithoutEmojis(r.group)))}kebabCaseWithoutEmojis(t){return t.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}};var _0_=require("fs/promises");async function jjc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new Qtn;a.setInstance({companyName:n}),await new Yeu({url:e,context:r,builder:a,absolutePathToFernDirectory:Bu($c.of(process.cwd()),za.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,_0_.writeFile)(Bu($c.of(t),za.of(PH),za.of(Uae)),JSON.stringify({version:i,organization:n},void 0,4))}var wjc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!WZi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=$c.of(CI());await jjc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var h0_="0.0.0";var y0_={[$h.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,QB(e)])),[$h.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[$h.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[$h.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[$h.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[$h.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[$h.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[$h.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[$h.GenerationLanguage.SWIFT]:new Set([])};var JME=["go","ruby"];function Aee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=l=>({unsafeName:l,safeName:KME({name:l,keywords:YME({generationLanguage:e,keywords:t})})}),c=R_(n),d=QB(c),s=sZi(n),o=nZi(c);return r&&(!kME(o)&&(e==null||JME.includes(e))&&(c=o.map((l,b)=>{if(b>0){let g=Xeu(l);if(g!=null)return g;if(Zeu(l))return l.toUpperCase()}return l}).join(""),d=QB(o.map((l,b)=>{let g=Xeu(l);return g??(Zeu(l)?l.toUpperCase():b===0?QB(l):l)}).join(""))),s=n.split(" ").map(l=>l.split(/(\d+)/).map(sZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??c),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function KME({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":ZME(e)?"_"+e:e}function YME({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return y0_[e]}var XME=/^[0-9]/;function ZME(e){return XME.test(e)}function kME(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Xeu(i)!=null||Zeu(i),a=Xeu(t)!=null||Zeu(t);return n&&a})}function Xeu(e){return tAE.get(e.toUpperCase())}function Zeu(e){return eAE.has(e.toUpperCase())}var eAE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),tAE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Sjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Toe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return _en(e.auth,{single:i=>{let n=v0_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Toe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:Toe.Any,schemes:i.map(n=>v0_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function v0_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return URa(c,{header:d=>YA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>b0_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>keu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return keu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>keu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return keu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return b0_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function keu({casingsGenerator:e,docs:t,rawScheme:r}){return YA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function b0_({casingsGenerator:e,docs:t,rawScheme:r}){return YA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function d7(e){let t=iAE(e),{value:r,done:i}=Djc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...rAE(t)]}}function*rAE(e){let t;do{let{value:r}=Djc(e,"}"),i=Djc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*iAE(e){for(let t of e)yield t}function Djc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function u8a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:sir(i,{singleBaseUrl:()=>lR.singleBaseUrl(nAE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>lR.multipleBaseUrls(aAE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,sir(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function nAE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>sir(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:g0_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function aAE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>sir(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Sd(a.urls,u=>g0_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function g0_(e){return e.endsWith("/")?e.slice(0,-1):e}function s8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Var({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 O0_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return War({containerType:t});switch(t.type){case"list":{let u=NT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:iP.literal({literal:t.literal._visit({boolean:u=>kd.boolean(u),string:u=>kd.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 War({containerType:t});let u=NT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=NT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=NT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=NT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||c.type==="failure"?War({containerType:t}):{type:"success",example:iP.map({map:[{key:u.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:c.jsonExample}}}default:Ao(t)}}function War({containerType:e}){switch(e.type){case"list":return{type:"success",example:iP.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:iP.literal({literal:e.literal._visit({boolean:t=>kd.boolean(t),string:t=>kd.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:iP.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:iP.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:iP.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:iP.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ao(e)}}function P0_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return lAE({fieldName:e,default_:oAE(t.v2),validation:uAE(t.v2)});case"BASE_64":return{type:"success",example:kd.base64(Hh.BASE64),jsonExample:Hh.BASE64};case"BOOLEAN":return{type:"success",example:kd.boolean(Hh.BOOLEAN),jsonExample:Hh.BOOLEAN};case"DATE":return{type:"success",example:kd.date(Hh.DATE),jsonExample:Hh.DATE};case"DATE_TIME":return{type:"success",example:kd.datetime({datetime:new Date(Hh.DATE_TIME),raw:Hh.DATE_TIME}),jsonExample:Hh.DATE_TIME};case"DOUBLE":return fAE({fieldName:e,validation:sAE(t.v2)});case"FLOAT":return{type:"success",example:kd.float(Hh.FLOAT),jsonExample:Hh.FLOAT};case"INTEGER":return dAE({fieldName:e,validation:cAE(t.v2)});case"UINT_64":return{type:"success",example:kd.uint64(Hh.INT64),jsonExample:Hh.INT64};case"UINT":return{type:"success",example:kd.uint(Hh.UINT),jsonExample:Hh.UINT};case"BIG_INTEGER":return{type:"success",example:kd.bigInteger(Hh.INT64.toString()),jsonExample:`${Hh.INT64}`};case"LONG":return{type:"success",example:kd.long(Hh.INT64),jsonExample:Hh.INT64};case"UUID":return{type:"success",example:kd.uuid(Hh.UUID),jsonExample:Hh.UUID};default:Ao(t.v1)}}function oAE(e){if(e?.type==="string")return e.default}function uAE(e){if(e?.type==="string")return e.validation}function sAE(e){if(e?.type==="double")return e.validation}function cAE(e){if(e?.type==="integer")return e.validation}function m0_(e){if(e<=Hh.SAMPLE_STRINGS.length){let t=Hh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Hh.SAMPLE_STRINGS[Hh.SAMPLE_STRINGS.length-1]+".".repeat(e-Hh.SAMPLE_STRINGS.length)}function lAE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:kd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=m0_(n);return{type:"success",example:kd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=m0_(a);return{type:"success",example:kd.string({original:u}),jsonExample:u}}}let i=e??Hh.STRING;return{type:"success",example:kd.string({original:i}),jsonExample:i}}function fAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.double(r),jsonExample:r};if(i)return{type:"success",example:kd.double(i),jsonExample:i}}return{type:"success",example:kd.double(Hh.DOUBLE),jsonExample:Hh.DOUBLE}}function dAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.integer(r),jsonExample:r};if(i)return{type:"success",example:kd.integer(i),jsonExample:i}}return{type:"success",example:kd.integer(Hh.INT),jsonExample:Hh.INT}}function OQn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=NT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:c,jsonExample:d}=u;return{type:"success",example:w1.alias({value:c}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:w1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let b=t[l.typeId];if(b==null)continue;let g=OQn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),c.push(...g.example.properties))}let d=pAE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:w1.object({properties:[...c,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let c of r.shape.members){let d=NT({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:w1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=NT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(c[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...c}}),samePropertiesAsObject:o=>{let l=t[o.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=OQn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.samePropertiesAsObject({typeId:l.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...c}}},singleProperty:o=>{let l=NT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:b,jsonExample:g}=l;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function pAE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=NT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Var({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:l}),c[s.name.wireValue]=b}return{type:"success",example:w1.object({properties:d}),jsonExample:c}}function NT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=OQn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:by.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=O0_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=War({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:by.container(s)},jsonExample:o}}let{example:c,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:by.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:c}=P0_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:by.primitive(c)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:by.unknown(u)},jsonExample:u}}}}function zin(e,t){let r=[];for(let i of e){let n=NT({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function mQn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function etu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?t5.exploded():t5.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var Ejc=ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});function PQn({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RC.ok(tI.body(void 0)),docs:void 0},c=zin(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointPathParameters=c.example;let d=zin(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=zin(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=etu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let l=mQn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointHeaders=l.example;let b=mQn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,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 g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let D=OQn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});D!=null&&D.type==="success"&&Object.assign(g,D.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=NT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Var({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:D,jsonExample:A}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:D}),g[m.name.wireValue]=A}u.request=rK.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=rK.reference(O);break}default:Ao(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 g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1});break;default:Ao(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}case"text":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}default:Ao(t.response.body.value)}break}case"text":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ao(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RC.error({body:void 0,error:a.declaration.name});else{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:s8a(u),url:_AE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function _AE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function Mjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=zin(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=zin(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let c=etu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=mQn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=mQn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(O=>O.origin==="client")[0];if(l!=null){let O=j0_({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:l.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=j0_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:hAE(t,n)},jsonExample:void 0}}function j0_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=NT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return VAe.reference(i.example)}function hAE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function jQn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function VRi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function w0_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);c!==void 0?n.pathParameters[u.name.originalName]=c:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.queryParameters[u.name.name.originalName]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.headers[u.name.wireValue]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function S0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=w0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},c={},d={endpoint:{method:e.method,path:yAE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}default:Ao(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:c,baseExample:d}}function yAE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=jQn(i.v2Examples),u=n??a,c;u==null?c=i.name.originalName:c=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function ttu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:V4.json(c8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?c8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?c8a(o):o;n[s]={...a,body:V4.json(l)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?c8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?c8a(o):o;n[s]={...a,body:V4.json(l)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c))i[s]={...a,body:V4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:V4.stream([o])}}break}case"streamParameter":break;default:Ao(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function c8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var wQn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},vAE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function rtu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,vAE({exampleStore:n,key:e,example:u}),!0}return!1}function D0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:c,baseExample:d}=S0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],l=Object.keys(c)[0],b=Object.values(c)[0],g=bAE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:l,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(gAE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=ttu({endpoint:e}),m=wQn(l??"base","base",void 0);rtu({key:m,displayName:l??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function bAE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:c,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],l=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:P}=ttu({endpoint:e,responseObject:b}),D=Object.keys(m)[0],A=Object.values(m)[0];for(let[M,E]of Object.entries(O)){let C,z;t[M]?(z=t[M],l.add(M),C=wQn(M,M,b?.statusCode)):u&&a?(z=u,C=wQn(a,M,b?.statusCode)):(z=r,C=wQn("base",M,b?.statusCode)),rtu({key:C,displayName:M,request:z,response:E,exampleStore:s,userOrAutoStore:c})&&(g=!0)}if(!g){let M=R_(`${e.name.originalName}_example`);i&&n&&l.add(i);let E=wQn(i??a??"base",D??"base",b?.statusCode);rtu({key:E,displayName:i??a??M,request:n??u??r,response:A??P,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return l}function gAE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:c}=ttu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],l=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=wQn(g,s??o??"base",d?d.statusCode:l?l.statusCode:c.statusCode);rtu({key:m,displayName:g,request:O,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function l8a({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){let a=[];if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let u=PQn({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});u.type==="success"&&a.push({example:u.example});for(let c of n.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=PQn({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&a.push({example:s.example})}n.autogeneratedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=Mjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function Ajc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=D0_({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let c=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:c};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:c}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=Mjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function M0_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y6.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?y6.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function P3({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:by.container(iP.list({...i,list:i.list.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:by.container(iP.set({...i,set:i.set.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?P3({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:by.container(iP.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?P3({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:by.container(iP.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:by.container(iP.map({...i,map:i.map.map(n=>{let a=P3({filteredIr:e,exampleTypeReference:n.key}),u=P3({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:by.named({...r,shape:w1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:by.named({...r,shape:w1.enum(i)})}),object:i=>({...t,shape:by.named({...r,shape:w1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=M0_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:by.named({...r,shape:w1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:by.named({...r,shape:w1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qjc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function OAE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function E0_({filteredIr:e,headers:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function mAE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?rK.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function PAE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RC.ok(tI.body(i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RC.ok(tI.stream(i.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(yy))),sse:i=>RC.ok(tI.sse(i.map(({event:n,data:a})=>{let u=P3({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yy))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RC.error({error:r,body:i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Tjc({filteredIr:e,example:t}){return{...t,rootPathParameters:qjc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qjc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qjc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:E0_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:E0_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:OAE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?mAE({filteredIr:e,requestBody:t.request}):void 0,response:PAE({filteredIr:e,response:t.response})}}function A0_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:w1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:w1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:P3({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=M0_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:w1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:w1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function Cjc(e,t){if(t==null)return e;let r=uZi(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>A0_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(c,o.name.wireValue)&&s.push(o);return[c,{...d,shape:t0.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let l=o.id;return o.payload.type==="inlinedPayload"&&l!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(l,b.name.wireValue))}),o});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:uZi(e.errors,c=>t.hasError(c)),services:Sd(uZi(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:Tjc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?Tjc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:jAE(e.serviceTypeReferenceInfo,t)}}function jAE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function xin(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function gqe(e){return e.allParts.map(t=>t.originalName).join("/")}var aP={generateTypeId:e=>`type_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${gqe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${gqe(e)}`,generateSubpackageId:e=>`subpackage_${gqe(e)}`,generateEndpointId:(e,t)=>{let r=gqe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${gqe(e)}`,generateWebhookId:(e,t)=>`webhooks_${gqe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${gqe(e)}`};function SQn(e){return e.type!=null}var itu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:c,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:l,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=aP.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=aP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=aP.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Rin=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=wAE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=aP.generateTypeId(t),c={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=c,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=aP.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=aP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&gR(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=aP.generateServiceId(t.name),a=r.id,u=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])gR(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])gR(s.valueType,u,d);for(let s of r.queryParameters)gR(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=xin(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&XA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)ntu(o,u,d);for(let o of s.properties)gR(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&kB(i.request.body)){let o=xin(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{gR(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)W4._visit(o,{file:Ko,bodyProperty:({valueType:l})=>{gR(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&&j1._visit(r.response.body,{fileDownload:Ko,json:s=>{gR(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&gR(s.nonStreamResponse.value.responseBodyType,u,d)},text:Ko,bytes:Ko,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(aP.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=aP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&HH._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)ntu(d,a,u);for(let d of c.properties)gR(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!SQn(i.payload)){let d=xin(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{gR(c,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let c of i.messages)YL._visit(c.body,{reference:({bodyType:d})=>{gR(d,a,u)},inlinedBody:d=>{for(let s of d.extends)ntu(s,a,u);for(let s of d.properties)gR(s.valueType,a,u)},_other:()=>{}});for(let c of i.queryParameters)gR(c.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(b=>{s.add(b)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}u[c]=s.size>0?s:void 0}}return new itu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Ao(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(aP.generateSubpackageId(i))}}};function wAE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ao(e)}}function gR(e,t,r){ol._visit(e,{container:i=>{SAE(i,t,r)},named:i=>{ntu(i,t,r)},primitive:Ko,unknown:Ko,_other:Ko})}function ntu(e,t,r){t.add(aP.generateTypeId(e)),r.add(e.fernFilepath)}function SAE(e,t,r){Ky._visit(e,{list:i=>{gR(i,t,r)},map:i=>{gR(i.keyType,t,r),gR(i.valueType,t,r)},optional:i=>{gR(i,t,r)},nullable:i=>{gR(i,t,r)},set:i=>{gR(i,t,r)},literal:Ko,_other:Ko})}var DAE=[Hs.AvailabilityStatus.GeneralAvailability];function bmi(e){return e!==void 0&&!DAE.includes(e.status)}var Bjc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},f8a=class{errors;constructor(){this.errors=new Bjc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability)||(n.endpoints?.every(u=>bmi(u.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,c]of Object.entries(n)){if(bmi(c.availability))continue;let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}if(bmi(d.availability)){this.errors.add(`Endpoint "${u}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:u,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:Ao(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:u,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:Ao(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ao(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bmi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ao(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ao(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ao(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ao(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ao(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:Ao(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Nin(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=MAE(e.environments,t.environments,r),{services:u,websocketChannels:c}=AAE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:EAE(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function EAE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function MAE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=q0_(e),n=q0_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:lR.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,c=t.environments;if(u.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:u,s=i?u:c,o={},{deconflictedEnvironments2:l,changedBaseUrlIds2:b}=qAE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[{id:g,name:O},...l.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(l.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:c,s=u.type==="multipleBaseUrls"?u:c,{deconflictedEnvironments1:o,changedBaseUrlIds1:l}=TAE(d,s,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:l}}if(u.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=CAE(u,c,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(l=>({...o,urls:{...o.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function AAE(e,t,r,i){if(r!=null)for(let[u,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}if(i!=null)for(let[u,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}let n=e.services;for(let[u,c]of Object.entries(t.services))n[u]==null?n[u]=c:n[u]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[u].endpoints??[],...c.endpoints],pathParameters:[...n[u].pathParameters??[],...c.pathParameters??[]],headers:[...n[u].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[u].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function qAE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Ijc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:lR.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function TAE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=Ijc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:lR.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function CAE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Ijc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,l])=>[i[o]??o,l]))}));return{deconflictedEnvironments:lR.multipleBaseUrls({baseUrls:u,environments:c}),changedBaseUrlIds:i}}function q0_(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function Ijc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var f_=class e{breadcrumbs=[];context;static STRING=Hs.TypeReference.primitive({v1:"STRING",v2:Hs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Hs.TypeReference.container(Hs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var C0_=require("fs/promises");var zjc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:c,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},T0_=zjc;var gmi;(function(e){e.WARNING="warning",e.ERROR="error"})(gmi||(gmi={}));var WRi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new xjc({logger:t,relativePathToFile:za.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||gmi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===gmi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gmi.WARNING&&!t))switch(r.level){case gmi.ERROR:if(this.logger.log(Sb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Sb.Error,` - at location (${n})`)}break}}},xjc=class{logger;relativePathToFile;map=new T0_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,C0_.readFile)(this.relativePathToFile,"utf-8");xd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Sb.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var I6=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Aee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=R_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let l=await fetch(o);if(!l.ok)return{resolved:!1};try{let b=await l.text();try{a=JSON.parse(b),r=a}catch{a=xd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let c of t)u.push(await this.resolveNestedExternalReferences(c,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let c=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),c.resolved)return c.value}else{let c=`${n}${u}`;if(i.has(c))return t;i.add(c);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,c]of Object.entries(t))typeof c=="object"&&c!==null?a[u]=await this.resolveNestedExternalReferences(c,r,i,n):a[u]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return eir.ReadOnly;if(n)return eir.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new h$.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new h$.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:$L.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var lO=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var h$={};Na(h$,{AudienceExtension:()=>atu,FernAvailabilityExtension:()=>otu,FernEnumExtension:()=>utu,FernIgnoreExtension:()=>Fin,FernOptionalExtension:()=>stu,FernTypeExtension:()=>ftu,FernTypeNameExtension:()=>dtu,SdkGroupNameExtension:()=>ctu,SdkMethodNameExtension:()=>ltu});var atu=class extends lO{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var otu=class extends lO{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return $L.InDevelopment;case"PRE_RELEASE":case"BETA":return $L.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return $L.GeneralAvailability;case"DEPRECATED":return $L.Deprecated;default:return}}};var BAE=Yo.object({snake:Yo.string().optional(),camel:Yo.string().optional(),screamingSnake:Yo.string().optional(),pascal:Yo.string().optional()}),IAE=Yo.object({description:Yo.string().optional(),name:Yo.string().optional(),casing:BAE.optional()}),B0_=Yo.record(IAE);var utu=class extends lO{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=B0_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Fin=class extends lO{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var stu=class extends lO{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ctu=class extends lO{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var ltu=class extends lO{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ftu=class extends lO{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var dtu=class extends lO{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var mQt=class extends f_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Rin(i),this.ir={auth:{docs:void 0,requirement:Hs.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Hs.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Fin({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Fin({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=Ajc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=l8a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let c of a.endpoints)r.has(c.id)&&u.push(c);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=R_(n?.join(".")),u=R_(r),c=this.context.namespace?`${R_(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:d7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>R_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var vA={};Na(vA,{AbstractConverters:()=>Njc,ExampleConverter:()=>s6e,SchemaConverters:()=>Rjc,ServersConverter:()=>Oqe});var Njc={};Na(Njc,{AbstractMediaTypeObjectConverter:()=>ytu,AbstractParameterConverter:()=>vtu});var s6e=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING=Hh.STRING;EXAMPLE_NUMBER=Hh.DOUBLE;EXAMPLE_BOOLEAN=Hh.BOOLEAN;EXAMPLE_INTEGER=Hh.INT;EXAMPLE_DATE=Hh.DATE;EXAMPLE_DATE_TIME=Hh.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(c=>c?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(c=>c.validExample),errors:u?[]:a.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,l=!t.required?.includes(d);if(o&&l){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(l=>!s.has(l)).forEach(l=>{let g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:g})})}for(let{key:d,result:s}of c)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${c}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${c}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var Rjc={};Na(Rjc,{ArraySchemaConverter:()=>qQn,EnumSchemaConverter:()=>DQn,ObjectSchemaConverter:()=>EQn,OneOfSchemaConverter:()=>MQn,PrimitiveSchemaConverter:()=>AQn,SchemaConverter:()=>HRi,SchemaOrReferenceConverter:()=>EK});function I0_(e){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ol.primitive({v1:"BASE_64",v2:Wd.base64({})});case"BOOLEAN":return ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:void 0})});case"DATE":return ol.primitive({v1:"DATE",v2:Wd.date({})});case"DATE_TIME":return ol.primitive({v1:"DATE_TIME",v2:Wd.dateTime({})});case"FLOAT":return ol.primitive({v1:"FLOAT",v2:Wd.float({})});case"DOUBLE":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:void 0,validation:void 0})});case"UINT":return ol.primitive({v1:"UINT",v2:Wd.uint({})});case"UINT_64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({})});case"INTEGER":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:void 0,validation:void 0})});case"LONG":return ol.primitive({v1:"LONG",v2:Wd.long({default:void 0})});case"STRING":return ol.primitive({v1:"STRING",v2:Wd.string({default:void 0,validation:void 0})});case"UUID":return ol.primitive({v1:"UUID",v2:Wd.uuid({})});case"BIG_INTEGER":return ol.primitive({v1:"BIG_INTEGER",v2:Wd.bigInteger({default:void 0})});default:return}},unknown:()=>ol.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ol.container(Ky.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ol.container(Ky.list(t))},optional:t=>{if(t!=null)return ol.container(Ky.optional(t))},nullable:t=>{if(t!=null)return ol.container(Ky.nullable(t))},set:t=>{if(t!=null)return ol.container(Ky.set(t))},literal:t=>ol.container(Ky.literal(t._visit({string:r=>KL.string(r),boolean:r=>KL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var DQn=class extends f_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],c=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:t0.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var ptu=class extends f_{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()}));return{type:t0.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ol.container(Ky.map({keyType:f_.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function d8a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},c={},d=new Set;for(let[s,o]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let b=zAE(r,o,i)??i.convertBreadcrumbsToName(l),g="nullable"in o?o.nullable:!1,m=new EK({context:i,breadcrumbs:l,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])c[P]==null&&(c[P]=new Set),c[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:u,referencedTypes:d}}function zAE(e,t,r){return r.isReferenceObject(t)?void 0:new h$.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var EQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:t0.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=d8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[l,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",l.toString()],O;if(this.context.isReferenceObject(b)){let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(b)}`);continue}if(O=M,typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0),!d||Object.keys(O.properties??{}).every(E=>!this.schema.required?.includes(E))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:c});continue}}else O=b;typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0);let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:D,propertiesByAudience:A}=d8a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...A},D.forEach(M=>{c.add(M)})}for(let l of Object.keys(s))c.add(l);return{type:t0.object({properties:r,extends:u.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(yy),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var _tu=class extends lO{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var htu;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let l=i(s.description);if(l)return l}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let l=a(s,o);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!l.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):l.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let l=s.properties;if(!l)return;let b=Object.keys(l);if(b.length===0)return;let g=u(s,o);if(g.length>0){let P=c(g).slice(0,1).map(D=>d(D));if(P.length>0)return P.join("")}let O=c(b);if(O.length>0)return O.slice(0,1).map(P=>d(P)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let l=s.properties;if(!l)return[];let b=new Set(Object.keys(l)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(P=>{g.add(P)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function c(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),P=0;for(let D of o)m===D?P+=15:m.includes(D)&&(P+=10);for(let D of l)m===D?P+=8:m.includes(D)&&(P+=5);for(let D of b)m===D?P+=3:m.includes(D)&&(P+=2);return P+=Math.max(0,5-O.length),{prop:O,score:P}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=c;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(htu||(htu={}));var MQn=class extends f_{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new _tu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new EK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let b=o.convert();if(b?.type!=null&&l!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:JL.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=d8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(l.ok){let g=this.context.typeReferenceToDeclaredTypeName(l.reference);g!=null&&c.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:t0.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let c=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=htu.generateDisplayNameForInlinedObject({...u,typeName:d},n),l=new HRi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??u}).convert();if(l!=null){let b=l.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:t0.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ol.container(Ky.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var AQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ol.container(Ky.literal(KL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ol.primitive({v1:vy.Date,v2:Wd.date({})});if(this.schema.format==="date-time")return ol.primitive({v1:vy.DateTime,v2:Wd.dateTime({})})}return ol.primitive({v1:"STRING",v2:Wd.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ol.container(Ky.literal(KL.boolean(t))):ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var xAE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],HRi=class e extends f_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new h$.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new DQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=K2n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new AQn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new qQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new MQn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new ptu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new EQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:ol.unknown(),resolvedType:ol.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new h$.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=I0_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...xAE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var EK=class extends f_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new HRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ol.container(Ky.optional(t))}wrapInNullable(t){return ol.container(Ky.nullable(t))}};var qQn=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var ytu=class extends f_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=R_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let c=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var vtu=class extends f_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??f_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var btu=class extends lO{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var z0_="Base",Oqe=class e extends f_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(o=>o.id===c.id)===d),a=[i,...n],u=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:u[0]?.id,environments:lR.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(yy);return{value:{defaultEnvironment:t[0]?.id,environments:lR.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new btu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,b]of Object.entries(r.variables??{}))l!==a&&(s[l]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(yy)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?z0_:e.getServerExtensionName({server:this.servers[0],context:this.context})??z0_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var p8a={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},RAE=new Set(Object.values(p8a));var TQn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1923
+ `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:c}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(ul(!a,"Browser should be launched with either pipe or debugging port - not both."),d.push("--remote-debugging-pipe")):d.push(`--remote-debugging-port=${a||0}`));let s=!1,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,Dy_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let l=d[o].split("=",2)[1];ul(typeof l=="string","`--user-data-dir` is malformed");let b=c;return b||(ul(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}}defaultArgs(t={}){let r=["--allow-pre-commit-input","--disable-background-networking","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-breakpad","--disable-client-side-phishing-detection","--disable-component-extensions-with-background-pages","--disable-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${Ey_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(c=>c.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?hko({browser:Lq.CHROME,channel:sSE(t)}):this.resolveExecutablePath()}};function sSE(e){switch(e){case"chrome":return T6.STABLE;case"chrome-dev":return T6.DEV;case"chrome-beta":return T6.BETA;case"chrome-canary":return T6.CANARY}}var pPc=ui(require("fs"),1),Min=require("fs/promises"),My_=ui(require("os"),1),Seu=ui(require("path"),1);vB();nq();var Deu=class extends cQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:c=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&ul(c===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${c||0}`));let s,o=!0,l=d.findIndex(g=>["-profile","--profile"].includes(g));if(l!==-1){if(s=d[l+1],!s||!pPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,Min.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await _Oc(Lq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(ul(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}else try{await(0,Min.unlink)(Seu.default.join(t,"user.js"));let i=Seu.default.join(t,"prefs.js.puppeteer");if(pPc.default.existsSync(i)){let n=Seu.default.join(t,"prefs.js");await(0,Min.unlink)(n),await(0,Min.rename)(i,n)}}catch(i){fg(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(My_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(c=>c.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var Ay_=require("path");var W2a=Object.freeze({chromium:"1108766",firefox:"latest"});var _Pc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},OQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},lQn,ymi,$2a,H2a,fQn=class extends x4a{constructor(t){let{configuration:r,...i}=t;switch(super(i),lQn.add(this),ymi.set(this,void 0),$2a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=W2a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=W2a.chromium;break}this.connect=this.connect.bind(this),this.launch=this.launch.bind(this),this.executablePath=this.executablePath.bind(this),this.defaultArgs=this.defaultArgs.bind(this),this.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return _Pc(this,$2a,r,"f"),OQt(this,lQn,"a",H2a).launch(t)}executablePath(t){return OQt(this,lQn,"a",H2a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=OQt(this,ymi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,Ay_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=OQt(this,$2a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return OQt(this,lQn,"a",H2a).product}defaultArgs(t={}){return OQt(this,lQn,"a",H2a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new nko(t)}};ymi=new WeakMap,$2a=new WeakMap,lQn=new WeakSet,H2a=function(){if(OQt(this,ymi,"f")&&OQt(this,ymi,"f").product===this.lastLaunchedProduct)return OQt(this,ymi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=W2a.chromium,_Pc(this,ymi,new weu(this),"f");break;case"firefox":this.defaultBrowserRevision=W2a.firefox,_Pc(this,ymi,new Deu(this),"f");break;default:throw new Error(`Unknown product: ${OQt(this,$2a,"f")}`)}return OQt(this,ymi,"f")};Wbc();k6a();var cSE=new fQn({isPuppeteerCore:!0}),{connect:b55,createBrowserFetcher:g55,defaultArgs:O55,executablePath:m55,launch:P55}=cSE;var i0_=require("os"),n0_=require("path"),a0_=ui(r0_(),1);function zME(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var o0_=()=>{var e,t,r,i,n,a,u,c,d,s,o,l,b,g,O,m,P,D,A,M,E,C,z,G,I,N,U,Y,J,X,oe,pe,de,me,Le,yt,De;let Ae=(0,a0_.cosmiconfigSync)("puppeteer").search(),Ct=Ae?Ae.config:{};if(Ct.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Ct.defaultProduct)!==null&&i!==void 0?i:"chrome",Ct.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Ct.executablePath,Ct.executablePath&&(Ct.skipDownload=!0),Ct.skipDownload=!!((b=(l=(o=(s=(d=(c=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&c!==void 0?c:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&l!==void 0?l:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Ct.skipDownload),Ct.skipDownload||(Ct.browserRevision=(P=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&P!==void 0?P:Ct.browserRevision,Ct.downloadHost=(M=(A=(D=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_host)!==null&&A!==void 0?A:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Ct.downloadHost,Ct.downloadPath=(z=(C=(E=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_path)!==null&&C!==void 0?C:process.env.npm_package_config_puppeteer_download_path)!==null&&z!==void 0?z:Ct.downloadPath),Ct.cacheDirectory=(U=(N=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&N!==void 0?N:Ct.cacheDirectory)!==null&&U!==void 0?U:(0,n0_.join)((0,i0_.homedir)(),".cache","puppeteer"),Ct.temporaryDirectory=(X=(J=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&J!==void 0?J:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Ct.temporaryDirectory,(oe=Ct.experiments)!==null&&oe!==void 0||(Ct.experiments={}),Ct.experiments.macArmChromiumEnabled=!!((me=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&me!==void 0?me:Ct.experiments.macArmChromiumEnabled),Ct.logLevel=(De=(yt=(Le=process.env.PUPPETEER_LOGLEVEL)!==null&&Le!==void 0?Le:process.env.npm_config_LOGLEVEL)!==null&&yt!==void 0?yt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Ct.logLevel,!zME(Ct.defaultProduct))throw new Error(`Unsupported product ${Ct.defaultProduct}`);return Ct};var xME=o0_(),RME=new fQn({isPuppeteerCore:!1,configuration:xME}),{connect:T95,createBrowserFetcher:C95,defaultArgs:B95,executablePath:I95,launch:u0_}=RME;var NME="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",FME={"Accept-Language":"en-US,en;q=0.9",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36","Accept-Encoding":"gzip, deflate, br, zstd",Connection:"keep-alive"};async function o8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),o8a(e,t-1,r*i,i);throw n}}async function s0_(){try{return await u0_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function LME(e,t){try{let r=await e.newPage();await r.setViewport({width:3072,height:2048,deviceScaleFactor:2,isMobile:!1,hasTouch:!1,isLandscape:!0}),await r.setExtraHTTPHeaders(FME),await r.setUserAgent(NME),await r.setJavaScriptEnabled(!0),await o8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await o8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function UME(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return await t.text()}catch{throw new Error("Failed to fetch page from source")}}async function Pjc({url:e,browser:t}){try{let r;if(t?r=await LME(t,e):r=await o8a(()=>UME(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function c0_(e){try{let t=await o8a(()=>fetch(e));if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);let r=await t.arrayBuffer();return new Uint8Array(r)}catch{throw new Error(`Failed to retrieve image from source url ${e}`)}}var VME=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function l0_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,gQn.join)(process.cwd(),"fern");try{let r=await WME(e,(0,gQn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function WME(e,t){let r=$ME(e),i=(0,gQn.join)(t,r);if(!HME(r))throw new Error(`${r} - file extension not supported`);if((0,Keu.existsSync)(i))return i;try{(0,Keu.mkdirSync)((0,gQn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await c0_(e);return Eu_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function HME(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let i=r.toLowerCase();return!(i&&!VME.includes(i))}function $ME(e){e.startsWith("http")&&(e=new URL(e).pathname);let t=e.split("#");if(t.length===0)return"image";let r=t[0];if(!r)return"image";let i=r.split("?");if(i.length===0)return"image";let n=i[0];return n&&decodeURIComponent(n.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function GME(e){let t=[];return If(e,"element",r=>{r.tagName==="img"&&Array.isArray(r.properties.className)&&r.properties.className.includes("rm-Logo-img")&&t.push(r)}),t.length>0?t:void 0}async function f0_(e,t){let r=NHn(e),i=GME(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await l0_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var d0_=28;async function p0_(e,t){e=new URL(e);let r=[];if(t){let n=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),n.push(await a.content()),await a.click(".rm-ThemeToggle"),n.push(await a.content())}catch{}await Promise.all(n.map(async a=>await f0_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=za.of(BJ(i[0]));return{light:n,dark:n,height:d0_}}if(i[0]!=null&&i[1]!=null){let n=za.of(BJ(i[0])),a=za.of(BJ(i[1]));return{light:n,dark:a,height:d0_}}}}var Yeu=class extends Gtn{url;logger;absolutePathToFernDirectory;constructor(t){super({context:t.context}),this.url=typeof t.url=="string"?new URL(t.url):t.url,this.logger=t.context.logger,this.absolutePathToFernDirectory=t.absolutePathToFernDirectory}async import({args:t,builder:r}){r.setLayout({layout:X7a});let i=await this.getHastForUrl(this.url),n=Fs_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let l=await this.scrapeTab({name:o.name,url:o.url});if(!l)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Bu(this.absolutePathToFernDirectory,za.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:l});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:l});for(let m of O)b.addItem({item:m})}let a=await s0_(),u=await p0_(this.url,a);u!=null&&r.setLogo({logo:u});let c=await ci_(i);r.setTitle({title:c});let d=await ai_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),l=await fetch(d);if(l.ok){let b=Buffer.from(await l.arrayBuffer()),g=Bu(o,za.of("favicon"));await(0,URi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:Gae(this.absolutePathToFernDirectory,g)})}}let s=await Us_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Bu(this.absolutePathToFernDirectory,za.of("assets"));return await(0,URi.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let i=new URL(r,this.url),n=await this.getHastForUrl(i),a=xs_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=Rs_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}catch(i){this.logger.error(`Failed to scrape tab ${t}: ${i instanceof Error?i.message:String(i)}`),i instanceof Error&&i.stack&&this.logger.error(`Stack trace: ${i.stack}`)}}async getHastForUrl(t){let r=await Pjc({url:t});return NHn(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let i of r){this.logger.debug(`Processing section: ${i.group}`);let n=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i});await(0,URi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let c=await Pjc({url:u}),d=await zs_({logger:this.logger,html:c,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,URi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,l])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Bu(n,za.of(l)),m=zd(O);await(0,URi.mkdir)(m,{recursive:!0}),await(0,URi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.toString()}, skipping`)})),await Promise.all(i.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:n,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let i=[];for(let n of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let c of n.pages)if(c.type==="page")u.contents.push({page:c.page,path:Gae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Bu(t,za.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Bu(t,za.of(this.kebabCaseWithoutEmojis(r.group)))}kebabCaseWithoutEmojis(t){return t.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}};var _0_=require("fs/promises");async function jjc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new Qtn;a.setInstance({companyName:n}),await new Yeu({url:e,context:r,builder:a,absolutePathToFernDirectory:Bu($c.of(process.cwd()),za.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,_0_.writeFile)(Bu($c.of(t),za.of(PH),za.of(Uae)),JSON.stringify({version:i,organization:n},void 0,4))}var wjc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!WZi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=$c.of(CI());await jjc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var h0_="0.0.0";var y0_={[$h.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,QB(e)])),[$h.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[$h.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[$h.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[$h.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[$h.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[$h.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[$h.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[$h.GenerationLanguage.SWIFT]:new Set([])};var JME=["go","ruby"];function Aee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=l=>({unsafeName:l,safeName:KME({name:l,keywords:YME({generationLanguage:e,keywords:t})})}),c=R_(n),d=QB(c),s=sZi(n),o=nZi(c);return r&&(!kME(o)&&(e==null||JME.includes(e))&&(c=o.map((l,b)=>{if(b>0){let g=Xeu(l);if(g!=null)return g;if(Zeu(l))return l.toUpperCase()}return l}).join(""),d=QB(o.map((l,b)=>{let g=Xeu(l);return g??(Zeu(l)?l.toUpperCase():b===0?QB(l):l)}).join(""))),s=n.split(" ").map(l=>l.split(/(\d+)/).map(sZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??c),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function KME({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":ZME(e)?"_"+e:e}function YME({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return y0_[e]}var XME=/^[0-9]/;function ZME(e){return XME.test(e)}function kME(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Xeu(i)!=null||Zeu(i),a=Xeu(t)!=null||Zeu(t);return n&&a})}function Xeu(e){return tAE.get(e.toUpperCase())}function Zeu(e){return eAE.has(e.toUpperCase())}var eAE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),tAE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Sjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Toe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return _en(e.auth,{single:i=>{let n=v0_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Toe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:Toe.Any,schemes:i.map(n=>v0_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function v0_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return URa(c,{header:d=>YA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>b0_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>keu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return keu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>keu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return keu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return b0_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function keu({casingsGenerator:e,docs:t,rawScheme:r}){return YA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function b0_({casingsGenerator:e,docs:t,rawScheme:r}){return YA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function d7(e){let t=iAE(e),{value:r,done:i}=Djc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...rAE(t)]}}function*rAE(e){let t;do{let{value:r}=Djc(e,"}"),i=Djc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*iAE(e){for(let t of e)yield t}function Djc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function u8a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:sir(i,{singleBaseUrl:()=>lR.singleBaseUrl(nAE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>lR.multipleBaseUrls(aAE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,sir(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function nAE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>sir(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:g0_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function aAE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>sir(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Sd(a.urls,u=>g0_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function g0_(e){return e.endsWith("/")?e.slice(0,-1):e}function s8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Var({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 O0_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return War({containerType:t});switch(t.type){case"list":{let u=NT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:iP.literal({literal:t.literal._visit({boolean:u=>kd.boolean(u),string:u=>kd.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 War({containerType:t});let u=NT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=NT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=NT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=NT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||c.type==="failure"?War({containerType:t}):{type:"success",example:iP.map({map:[{key:u.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:c.jsonExample}}}default:Ao(t)}}function War({containerType:e}){switch(e.type){case"list":return{type:"success",example:iP.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:iP.literal({literal:e.literal._visit({boolean:t=>kd.boolean(t),string:t=>kd.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:iP.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:iP.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:iP.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:iP.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ao(e)}}function P0_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return lAE({fieldName:e,default_:oAE(t.v2),validation:uAE(t.v2)});case"BASE_64":return{type:"success",example:kd.base64(Hh.BASE64),jsonExample:Hh.BASE64};case"BOOLEAN":return{type:"success",example:kd.boolean(Hh.BOOLEAN),jsonExample:Hh.BOOLEAN};case"DATE":return{type:"success",example:kd.date(Hh.DATE),jsonExample:Hh.DATE};case"DATE_TIME":return{type:"success",example:kd.datetime({datetime:new Date(Hh.DATE_TIME),raw:Hh.DATE_TIME}),jsonExample:Hh.DATE_TIME};case"DOUBLE":return fAE({fieldName:e,validation:sAE(t.v2)});case"FLOAT":return{type:"success",example:kd.float(Hh.FLOAT),jsonExample:Hh.FLOAT};case"INTEGER":return dAE({fieldName:e,validation:cAE(t.v2)});case"UINT_64":return{type:"success",example:kd.uint64(Hh.INT64),jsonExample:Hh.INT64};case"UINT":return{type:"success",example:kd.uint(Hh.UINT),jsonExample:Hh.UINT};case"BIG_INTEGER":return{type:"success",example:kd.bigInteger(Hh.INT64.toString()),jsonExample:`${Hh.INT64}`};case"LONG":return{type:"success",example:kd.long(Hh.INT64),jsonExample:Hh.INT64};case"UUID":return{type:"success",example:kd.uuid(Hh.UUID),jsonExample:Hh.UUID};default:Ao(t.v1)}}function oAE(e){if(e?.type==="string")return e.default}function uAE(e){if(e?.type==="string")return e.validation}function sAE(e){if(e?.type==="double")return e.validation}function cAE(e){if(e?.type==="integer")return e.validation}function m0_(e){if(e<=Hh.SAMPLE_STRINGS.length){let t=Hh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Hh.SAMPLE_STRINGS[Hh.SAMPLE_STRINGS.length-1]+".".repeat(e-Hh.SAMPLE_STRINGS.length)}function lAE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:kd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=m0_(n);return{type:"success",example:kd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=m0_(a);return{type:"success",example:kd.string({original:u}),jsonExample:u}}}let i=e??Hh.STRING;return{type:"success",example:kd.string({original:i}),jsonExample:i}}function fAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.double(r),jsonExample:r};if(i)return{type:"success",example:kd.double(i),jsonExample:i}}return{type:"success",example:kd.double(Hh.DOUBLE),jsonExample:Hh.DOUBLE}}function dAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.integer(r),jsonExample:r};if(i)return{type:"success",example:kd.integer(i),jsonExample:i}}return{type:"success",example:kd.integer(Hh.INT),jsonExample:Hh.INT}}function OQn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=NT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:c,jsonExample:d}=u;return{type:"success",example:w1.alias({value:c}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:w1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let b=t[l.typeId];if(b==null)continue;let g=OQn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),c.push(...g.example.properties))}let d=pAE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:w1.object({properties:[...c,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let c of r.shape.members){let d=NT({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:w1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=NT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(c[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...c}}),samePropertiesAsObject:o=>{let l=t[o.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=OQn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.samePropertiesAsObject({typeId:l.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...c}}},singleProperty:o=>{let l=NT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:b,jsonExample:g}=l;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function pAE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=NT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Var({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:l}),c[s.name.wireValue]=b}return{type:"success",example:w1.object({properties:d}),jsonExample:c}}function NT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=OQn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:by.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=O0_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=War({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:by.container(s)},jsonExample:o}}let{example:c,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:by.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:c}=P0_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:by.primitive(c)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:by.unknown(u)},jsonExample:u}}}}function zin(e,t){let r=[];for(let i of e){let n=NT({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function mQn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function etu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?t5.exploded():t5.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var Ejc=ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});function PQn({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RC.ok(tI.body(void 0)),docs:void 0},c=zin(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointPathParameters=c.example;let d=zin(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=zin(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=etu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let l=mQn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointHeaders=l.example;let b=mQn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,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 g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let D=OQn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});D!=null&&D.type==="success"&&Object.assign(g,D.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=NT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Var({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:D,jsonExample:A}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:D}),g[m.name.wireValue]=A}u.request=rK.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=rK.reference(O);break}default:Ao(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 g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1});break;default:Ao(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}case"text":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}default:Ao(t.response.body.value)}break}case"text":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Ejc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ao(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RC.error({body:void 0,error:a.declaration.name});else{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:s8a(u),url:_AE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function _AE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function Mjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=zin(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=zin(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let c=etu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=mQn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=mQn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(O=>O.origin==="client")[0];if(l!=null){let O=j0_({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:l.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=j0_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:hAE(t,n)},jsonExample:void 0}}function j0_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=NT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return VAe.reference(i.example)}function hAE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function jQn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function VRi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function w0_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);c!==void 0?n.pathParameters[u.name.originalName]=c:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.queryParameters[u.name.name.originalName]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.headers[u.name.wireValue]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function S0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=w0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},c={},d={endpoint:{method:e.method,path:yAE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=VRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}default:Ao(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:c,baseExample:d}}function yAE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=jQn(i.v2Examples),u=n??a,c;u==null?c=i.name.originalName:c=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function ttu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:V4.json(c8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?c8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?c8a(o):o;n[s]={...a,body:V4.json(l)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?c8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?c8a(o):o;n[s]={...a,body:V4.json(l)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:c,autoExamples:d}=VRi(u.v2Examples);for(let[s,o]of Object.entries(c))i[s]={...a,body:V4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:V4.stream([o])}}break}case"streamParameter":break;default:Ao(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function c8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var wQn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},vAE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function rtu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,vAE({exampleStore:n,key:e,example:u}),!0}return!1}function D0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:c,baseExample:d}=S0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],l=Object.keys(c)[0],b=Object.values(c)[0],g=bAE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:l,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(gAE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=ttu({endpoint:e}),m=wQn(l??"base","base",void 0);rtu({key:m,displayName:l??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function bAE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:c,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],l=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:P}=ttu({endpoint:e,responseObject:b}),D=Object.keys(m)[0],A=Object.values(m)[0];for(let[M,E]of Object.entries(O)){let C,z;t[M]?(z=t[M],l.add(M),C=wQn(M,M,b?.statusCode)):u&&a?(z=u,C=wQn(a,M,b?.statusCode)):(z=r,C=wQn("base",M,b?.statusCode)),rtu({key:C,displayName:M,request:z,response:E,exampleStore:s,userOrAutoStore:c})&&(g=!0)}if(!g){let M=R_(`${e.name.originalName}_example`);i&&n&&l.add(i);let E=wQn(i??a??"base",D??"base",b?.statusCode);rtu({key:E,displayName:i??a??M,request:n??u??r,response:A??P,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return l}function gAE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:c}=ttu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],l=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=wQn(g,s??o??"base",d?d.statusCode:l?l.statusCode:c.statusCode);rtu({key:m,displayName:g,request:O,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function l8a({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){let u=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&u.push({example:c.example})}if(a.userSpecifiedExamples.filter(c=>c.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let c of a.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&u.push({example:s.example})}a.autogeneratedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Mjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function Ajc({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:u,autoFullExamples:c}=D0_({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(s=>s.request!=null||s.response!=null))continue;let d=Object.values(a.v2Examples.userSpecifiedExamples).filter(s=>s!=null).flatMap(s=>s.codeSamples??[]);for(let[s,o]of Object.entries(c))c[s]={...o,codeSamples:d};for(let[s,o]of Object.entries(u))u[s]={...o,codeSamples:d}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Mjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function M0_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y6.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?y6.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function P3({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:by.container(iP.list({...i,list:i.list.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:by.container(iP.set({...i,set:i.set.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?P3({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:by.container(iP.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?P3({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:by.container(iP.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:by.container(iP.map({...i,map:i.map.map(n=>{let a=P3({filteredIr:e,exampleTypeReference:n.key}),u=P3({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:by.named({...r,shape:w1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:by.named({...r,shape:w1.enum(i)})}),object:i=>({...t,shape:by.named({...r,shape:w1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=M0_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:by.named({...r,shape:w1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:by.named({...r,shape:w1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qjc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function OAE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function E0_({filteredIr:e,headers:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function mAE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?rK.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function PAE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RC.ok(tI.body(i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RC.ok(tI.stream(i.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(yy))),sse:i=>RC.ok(tI.sse(i.map(({event:n,data:a})=>{let u=P3({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yy))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RC.error({error:r,body:i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Tjc({filteredIr:e,example:t}){return{...t,rootPathParameters:qjc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qjc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qjc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:E0_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:E0_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:OAE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?mAE({filteredIr:e,requestBody:t.request}):void 0,response:PAE({filteredIr:e,response:t.response})}}function A0_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:w1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:w1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:P3({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=M0_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:w1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:w1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function Cjc(e,t){if(t==null)return e;let r=uZi(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>A0_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(c,o.name.wireValue)&&s.push(o);return[c,{...d,shape:t0.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let l=o.id;return o.payload.type==="inlinedPayload"&&l!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(l,b.name.wireValue))}),o});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:uZi(e.errors,c=>t.hasError(c)),services:Sd(uZi(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:Tjc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?Tjc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:jAE(e.serviceTypeReferenceInfo,t)}}function jAE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function xin(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function gqe(e){return e.allParts.map(t=>t.originalName).join("/")}var aP={generateTypeId:e=>`type_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${gqe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${gqe(e)}`,generateSubpackageId:e=>`subpackage_${gqe(e)}`,generateEndpointId:(e,t)=>{let r=gqe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${gqe(e)}`,generateWebhookId:(e,t)=>`webhooks_${gqe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${gqe(e)}`};function SQn(e){return e.type!=null}var itu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:c,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:l,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=aP.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=aP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=aP.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Rin=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=wAE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=aP.generateTypeId(t),c={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=c,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=aP.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=aP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&gR(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=aP.generateServiceId(t.name),a=r.id,u=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])gR(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])gR(s.valueType,u,d);for(let s of r.queryParameters)gR(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=xin(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&XA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)ntu(o,u,d);for(let o of s.properties)gR(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&kB(i.request.body)){let o=xin(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{gR(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)W4._visit(o,{file:Ko,bodyProperty:({valueType:l})=>{gR(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&&j1._visit(r.response.body,{fileDownload:Ko,json:s=>{gR(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&gR(s.nonStreamResponse.value.responseBodyType,u,d)},text:Ko,bytes:Ko,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(aP.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=aP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&HH._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)ntu(d,a,u);for(let d of c.properties)gR(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!SQn(i.payload)){let d=xin(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{gR(c,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let c of i.messages)YL._visit(c.body,{reference:({bodyType:d})=>{gR(d,a,u)},inlinedBody:d=>{for(let s of d.extends)ntu(s,a,u);for(let s of d.properties)gR(s.valueType,a,u)},_other:()=>{}});for(let c of i.queryParameters)gR(c.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(b=>{s.add(b)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}u[c]=s.size>0?s:void 0}}return new itu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Ao(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(aP.generateSubpackageId(i))}}};function wAE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ao(e)}}function gR(e,t,r){ol._visit(e,{container:i=>{SAE(i,t,r)},named:i=>{ntu(i,t,r)},primitive:Ko,unknown:Ko,_other:Ko})}function ntu(e,t,r){t.add(aP.generateTypeId(e)),r.add(e.fernFilepath)}function SAE(e,t,r){Ky._visit(e,{list:i=>{gR(i,t,r)},map:i=>{gR(i.keyType,t,r),gR(i.valueType,t,r)},optional:i=>{gR(i,t,r)},nullable:i=>{gR(i,t,r)},set:i=>{gR(i,t,r)},literal:Ko,_other:Ko})}var DAE=[Hs.AvailabilityStatus.GeneralAvailability];function bmi(e){return e!==void 0&&!DAE.includes(e.status)}var Bjc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},f8a=class{errors;constructor(){this.errors=new Bjc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability)||(n.endpoints?.every(u=>bmi(u.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,c]of Object.entries(n)){if(bmi(c.availability))continue;let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}if(bmi(d.availability)){this.errors.add(`Endpoint "${u}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:u,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:Ao(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:u,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:Ao(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ao(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bmi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ao(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ao(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ao(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ao(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ao(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:Ao(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Nin(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=MAE(e.environments,t.environments,r),{services:u,websocketChannels:c}=AAE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:EAE(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function EAE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function MAE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=q0_(e),n=q0_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:lR.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,c=t.environments;if(u.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:u,s=i?u:c,o={},{deconflictedEnvironments2:l,changedBaseUrlIds2:b}=qAE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[{id:g,name:O},...l.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(l.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:c,s=u.type==="multipleBaseUrls"?u:c,{deconflictedEnvironments1:o,changedBaseUrlIds1:l}=TAE(d,s,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:l}}if(u.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=CAE(u,c,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(l=>({...o,urls:{...o.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function AAE(e,t,r,i){if(r!=null)for(let[u,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}if(i!=null)for(let[u,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}let n=e.services;for(let[u,c]of Object.entries(t.services))n[u]==null?n[u]=c:n[u]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[u].endpoints??[],...c.endpoints],pathParameters:[...n[u].pathParameters??[],...c.pathParameters??[]],headers:[...n[u].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[u].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function qAE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Ijc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:lR.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function TAE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=Ijc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:lR.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function CAE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Ijc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,l])=>[i[o]??o,l]))}));return{deconflictedEnvironments:lR.multipleBaseUrls({baseUrls:u,environments:c}),changedBaseUrlIds:i}}function q0_(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function Ijc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var f_=class e{breadcrumbs=[];context;static STRING=Hs.TypeReference.primitive({v1:"STRING",v2:Hs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Hs.TypeReference.container(Hs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var C0_=require("fs/promises");var zjc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:c,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},T0_=zjc;var gmi;(function(e){e.WARNING="warning",e.ERROR="error"})(gmi||(gmi={}));var WRi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new xjc({logger:t,relativePathToFile:za.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||gmi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===gmi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gmi.WARNING&&!t))switch(r.level){case gmi.ERROR:if(this.logger.log(Sb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Sb.Error,` - at location (${n})`)}break}}},xjc=class{logger;relativePathToFile;map=new T0_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,C0_.readFile)(this.relativePathToFile,"utf-8");xd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Sb.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var I6=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Aee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=R_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let l=await fetch(o);if(!l.ok)return{resolved:!1};try{let b=await l.text();try{a=JSON.parse(b),r=a}catch{a=xd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let c of t)u.push(await this.resolveNestedExternalReferences(c,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let c=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),c.resolved)return c.value}else{let c=`${n}${u}`;if(i.has(c))return t;i.add(c);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,c]of Object.entries(t))typeof c=="object"&&c!==null?a[u]=await this.resolveNestedExternalReferences(c,r,i,n):a[u]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return eir.ReadOnly;if(n)return eir.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new h$.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new h$.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:$L.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var lO=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var h$={};Na(h$,{AudienceExtension:()=>atu,FernAvailabilityExtension:()=>otu,FernEnumExtension:()=>utu,FernIgnoreExtension:()=>Fin,FernOptionalExtension:()=>stu,FernTypeExtension:()=>ftu,FernTypeNameExtension:()=>dtu,SdkGroupNameExtension:()=>ctu,SdkMethodNameExtension:()=>ltu});var atu=class extends lO{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var otu=class extends lO{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return $L.InDevelopment;case"PRE_RELEASE":case"BETA":return $L.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return $L.GeneralAvailability;case"DEPRECATED":return $L.Deprecated;default:return}}};var BAE=Yo.object({snake:Yo.string().optional(),camel:Yo.string().optional(),screamingSnake:Yo.string().optional(),pascal:Yo.string().optional()}),IAE=Yo.object({description:Yo.string().optional(),name:Yo.string().optional(),casing:BAE.optional()}),B0_=Yo.record(IAE);var utu=class extends lO{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=B0_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Fin=class extends lO{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var stu=class extends lO{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ctu=class extends lO{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var ltu=class extends lO{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ftu=class extends lO{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var dtu=class extends lO{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var mQt=class extends f_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Rin(i),this.ir={auth:{docs:void 0,requirement:Hs.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Hs.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Fin({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Fin({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=Ajc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=l8a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let c of a.endpoints)r.has(c.id)&&u.push(c);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=R_(n?.join(".")),u=R_(r),c=this.context.namespace?`${R_(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:d7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>R_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var vA={};Na(vA,{AbstractConverters:()=>Njc,ExampleConverter:()=>s6e,SchemaConverters:()=>Rjc,ServersConverter:()=>Oqe});var Njc={};Na(Njc,{AbstractMediaTypeObjectConverter:()=>ytu,AbstractParameterConverter:()=>vtu});var s6e=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING=Hh.STRING;EXAMPLE_NUMBER=Hh.DOUBLE;EXAMPLE_BOOLEAN=Hh.BOOLEAN;EXAMPLE_INTEGER=Hh.INT;EXAMPLE_DATE=Hh.DATE;EXAMPLE_DATE_TIME=Hh.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(c=>c?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(c=>c.validExample),errors:u?[]:a.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,l=!t.required?.includes(d);if(o&&l){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(l=>!s.has(l)).forEach(l=>{let g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:g})})}for(let{key:d,result:s}of c)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${c}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${c}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var Rjc={};Na(Rjc,{ArraySchemaConverter:()=>qQn,EnumSchemaConverter:()=>DQn,ObjectSchemaConverter:()=>EQn,OneOfSchemaConverter:()=>MQn,PrimitiveSchemaConverter:()=>AQn,SchemaConverter:()=>HRi,SchemaOrReferenceConverter:()=>EK});function I0_(e){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ol.primitive({v1:"BASE_64",v2:Wd.base64({})});case"BOOLEAN":return ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:void 0})});case"DATE":return ol.primitive({v1:"DATE",v2:Wd.date({})});case"DATE_TIME":return ol.primitive({v1:"DATE_TIME",v2:Wd.dateTime({})});case"FLOAT":return ol.primitive({v1:"FLOAT",v2:Wd.float({})});case"DOUBLE":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:void 0,validation:void 0})});case"UINT":return ol.primitive({v1:"UINT",v2:Wd.uint({})});case"UINT_64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({})});case"INTEGER":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:void 0,validation:void 0})});case"LONG":return ol.primitive({v1:"LONG",v2:Wd.long({default:void 0})});case"STRING":return ol.primitive({v1:"STRING",v2:Wd.string({default:void 0,validation:void 0})});case"UUID":return ol.primitive({v1:"UUID",v2:Wd.uuid({})});case"BIG_INTEGER":return ol.primitive({v1:"BIG_INTEGER",v2:Wd.bigInteger({default:void 0})});default:return}},unknown:()=>ol.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ol.container(Ky.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ol.container(Ky.list(t))},optional:t=>{if(t!=null)return ol.container(Ky.optional(t))},nullable:t=>{if(t!=null)return ol.container(Ky.nullable(t))},set:t=>{if(t!=null)return ol.container(Ky.set(t))},literal:t=>ol.container(Ky.literal(t._visit({string:r=>KL.string(r),boolean:r=>KL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var DQn=class extends f_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],c=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:t0.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var ptu=class extends f_{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()}));return{type:t0.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ol.container(Ky.map({keyType:f_.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function d8a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},c={},d=new Set;for(let[s,o]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let b=zAE(r,o,i)??i.convertBreadcrumbsToName(l),g="nullable"in o?o.nullable:!1,m=new EK({context:i,breadcrumbs:l,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])c[P]==null&&(c[P]=new Set),c[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:u,referencedTypes:d}}function zAE(e,t,r){return r.isReferenceObject(t)?void 0:new h$.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var EQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:t0.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=d8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[l,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",l.toString()],O;if(this.context.isReferenceObject(b)){let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(b)}`);continue}if(O=M,typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0),!d||Object.keys(O.properties??{}).every(E=>!this.schema.required?.includes(E))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:c});continue}}else O=b;typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0);let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:D,propertiesByAudience:A}=d8a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...A},D.forEach(M=>{c.add(M)})}for(let l of Object.keys(s))c.add(l);return{type:t0.object({properties:r,extends:u.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(yy),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var _tu=class extends lO{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var htu;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let l=i(s.description);if(l)return l}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let l=a(s,o);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!l.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):l.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let l=s.properties;if(!l)return;let b=Object.keys(l);if(b.length===0)return;let g=u(s,o);if(g.length>0){let P=c(g).slice(0,1).map(D=>d(D));if(P.length>0)return P.join("")}let O=c(b);if(O.length>0)return O.slice(0,1).map(P=>d(P)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let l=s.properties;if(!l)return[];let b=new Set(Object.keys(l)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(P=>{g.add(P)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function c(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),P=0;for(let D of o)m===D?P+=15:m.includes(D)&&(P+=10);for(let D of l)m===D?P+=8:m.includes(D)&&(P+=5);for(let D of b)m===D?P+=3:m.includes(D)&&(P+=2);return P+=Math.max(0,5-O.length),{prop:O,score:P}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=c;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(htu||(htu={}));var MQn=class extends f_{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new _tu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new EK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let b=o.convert();if(b?.type!=null&&l!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:JL.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=d8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(l.ok){let g=this.context.typeReferenceToDeclaredTypeName(l.reference);g!=null&&c.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:t0.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let c=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=htu.generateDisplayNameForInlinedObject({...u,typeName:d},n),l=new HRi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??u}).convert();if(l!=null){let b=l.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:t0.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ol.container(Ky.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var AQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ol.container(Ky.literal(KL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ol.primitive({v1:vy.Date,v2:Wd.date({})});if(this.schema.format==="date-time")return ol.primitive({v1:vy.DateTime,v2:Wd.dateTime({})})}return ol.primitive({v1:"STRING",v2:Wd.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ol.container(Ky.literal(KL.boolean(t))):ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var xAE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],HRi=class e extends f_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new h$.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new DQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=K2n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new AQn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new qQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new MQn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new ptu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new EQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:ol.unknown(),resolvedType:ol.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new h$.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=I0_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...xAE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var EK=class extends f_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new HRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ol.container(Ky.optional(t))}wrapInNullable(t){return ol.container(Ky.nullable(t))}};var qQn=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var ytu=class extends f_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=R_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let c=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var vtu=class extends f_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??f_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var btu=class extends lO{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var z0_="Base",Oqe=class e extends f_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(o=>o.id===c.id)===d),a=[i,...n],u=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:u[0]?.id,environments:lR.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(yy);return{value:{defaultEnvironment:t[0]?.id,environments:lR.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new btu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,b]of Object.entries(r.variables??{}))l!==a&&(s[l]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(yy)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?z0_:e.getServerExtensionName({server:this.servers[0],context:this.context})??z0_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var p8a={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},RAE=new Set(Object.values(p8a));var TQn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1924
1924
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Sb.Trace,...t)}debug(...t){this.write(Sb.Debug,...t)}info(...t){this.write(Sb.Info,...t)}warn(...t){this.write(Sb.Warn,...t)}error(...t){this.write(Sb.Error,...t)}log(t,...r){this.write(t,...r)}};var PQt={FILE:{NAME:1,PACKAGE:2,DEPENDENCY:3,MESSAGE_TYPE:4,ENUM_TYPE:5,SERVICE:6,EXTENSION:7,OPTIONS:8,SOURCE_CODE_INFO:9,PUBLIC_DEPENDENCY:10,WEAK_DEPENDENCY:11,SYNTAX:12},MESSAGE:{NAME:1,FIELD:2,NESTED_TYPE:3,ENUM_TYPE:4,EXTENSION_RANGE:5,EXTENSION:6,OPTIONS:7,ONEOF_DECL:8,RESERVED_RANGE:9,RESERVED_NAME:10},ENUM:{NAME:1,VALUE:2,OPTIONS:3,RESERVED_RANGE:4,RESERVED_NAME:5},SERVICE:{NAME:1,METHOD:2,OPTIONS:3},METHOD:{NAME:1,INPUT_TYPE:2,OUTPUT_TYPE:3,OPTIONS:4,CLIENT_STREAMING:5,SERVER_STREAMING:6}},gtu={MESSAGE:4,ENUM:5,SERVICE:6};var Otu=class extends f_{enum;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,enum:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.enum=i,this.sourceCodeInfoPath=n}convert(){let t=this.enum.value.map((r,i)=>{let n=r.name;return{name:{name:this.context.casingsGenerator.generateName(n),wireValue:n},docs:this.context.getCommentForPath([...this.sourceCodeInfoPath,PQt.ENUM.VALUE,i]),availability:void 0}});return{type:t0.enum({default:void 0,values:t})}}};function x0_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var R0_=new Set([Gg.DOUBLE,Gg.FLOAT,Gg.INT64,Gg.UINT64,Gg.INT32,Gg.FIXED64,Gg.FIXED32,Gg.BOOL,Gg.STRING,Gg.BYTES,Gg.UINT32,Gg.SFIXED32,Gg.SFIXED64,Gg.SINT32,Gg.SINT64]);var mtu=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){if(this.field.label===3){let r=new $Ri({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:E2n.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Ptu=class extends f_{field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){switch(this.field.type){case Gg.STRING:return ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});case Gg.DOUBLE:return ol.primitive({v1:vy.Double,v2:Wd.double({default:void 0,validation:void 0})});case Gg.FLOAT:return ol.primitive({v1:vy.Float,v2:Wd.float({})});case Gg.INT32:return ol.primitive({v1:vy.Integer,v2:Wd.integer({default:void 0,validation:void 0})});case Gg.INT64:return ol.primitive({v1:vy.Long,v2:Wd.long({default:void 0})});case Gg.UINT32:return ol.primitive({v1:vy.Uint,v2:Wd.uint({default:void 0})});case Gg.UINT64:return ol.primitive({v1:vy.Uint64,v2:Wd.uint64({default:void 0})});case Gg.BOOL:return ol.primitive({v1:vy.Boolean,v2:Wd.boolean({default:void 0})});default:return ol.unknown()}}};var $Ri=class extends f_{field;wrapAsOptional;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,wrapAsOptional:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.field=i,this.wrapAsOptional=n??!0,this.sourceCodeInfoPath=a}convert(){if(this.field.label===3){let i=new mtu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i.typeReference):i.typeReference,inlinedTypes:i.inlinedTypes}}if(R0_.has(this.field.type)){let i=new Ptu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i):i,inlinedTypes:{}}}if((this.field.type===Gg.MESSAGE||this.field.type===Gg.ENUM)&&this.field.typeName!=null){let r=this.context.convertGrpcReferenceToTypeReference({typeName:this.field.typeName,displayNameOverride:this.field.name});if(r.ok)return{type:this.wrapAsOptional?this.wrapInOptional(r.reference):r.reference,inlinedTypes:{}}}}wrapInOptional(t){return ol.container(Ky.optional(t))}};function N0_({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},u=new Set,c={};for(let[d,s]of e.entries()){let l=new $Ri({context:r,breadcrumbs:[...t,"fields",s.name],field:s,sourceCodeInfoPath:[...i,PQt.MESSAGE.FIELD,d]}).convert();if(l!=null){let b={name:r.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:l.type,docs:r.getCommentForPath([...i,PQt.MESSAGE.FIELD,d]),availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null){c[s.oneofIndex]==null&&(c[s.oneofIndex]=[]),c[s.oneofIndex].push(s);continue}n.push(b)}}return{convertedFields:n,referencedTypes:u,propertiesByAudience:a,oneOfFields:c}}var jtu=class extends f_{oneOfFields;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,oneOfFields:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.oneOfFields=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let r of this.oneOfFields){let n=new $Ri({context:this.context,breadcrumbs:this.breadcrumbs,field:r,wrapAsOptional:!1,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();n!=null&&t.push({type:n.type,docs:void 0})}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var wtu=class extends f_{message;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,message:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.message=i,this.sourceCodeInfoPath=n}convert(){let t={},r=new Set,{convertedFields:i,referencedTypes:n,propertiesByAudience:a,oneOfFields:u}=N0_({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let c of n)r.add(c);for(let[c,d]of this.message.nestedType.entries()){let o=new GRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.NESTED_TYPE,c],schemaIndex:c}).convert();if(o!=null){for(let l of o.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([l,b])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.enumType.entries()){let o=new GRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.ENUM_TYPE,c],schemaIndex:c}).convert();if(o!=null){for(let l of o.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([l,b])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.oneofDecl.entries()){let o=new jtu({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[c]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.ONEOF_DECL,c]}).convert();if(o!=null){for(let g of o.referencedTypes)r.add(g);let l={typeDeclaration:this.createTypeDeclaration({shape:o.type,referencedTypes:o.referencedTypes,typeName:this.prependParentMessageName(x0_(d.name))}),audiences:[],propertiesByAudience:{}},b=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(l.typeDeclaration.name.typeId)});b.ok===!0&&(i.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:b.reference,docs:void 0,availability:void 0,propertyAccess:void 0,v2Examples:void 0}),t={...t,[l.typeDeclaration.name.typeId]:l})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.object({properties:i,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath)}),audiences:[],propertiesByAudience:a},inlinedTypes:t}}createTypeDeclaration({shape:t,referencedTypes:r,typeName:i,docs:n}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:n,referencedTypes:r,source:void 0,inline:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}convertDeclaredTypeName(t){let r=this.context.maybePrependPackageName(t);return{typeId:r,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(r),displayName:t}}prependDelimitedParentMessageName(t,r="."){return`${this.message.name}${r}${t}`}prependParentMessageName(t){return`${this.message.name}${t}`}};var GRi=class extends f_{schema;audiences;sourceCodeInfoPath;schemaIndex;constructor({context:t,breadcrumbs:r,schema:i,sourceCodeInfoPath:n,schemaIndex:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.sourceCodeInfoPath=n,this.schemaIndex=a,this.audiences=[]}convert(){let t=this.tryConvertGrpcEnum();if(t!=null)return t;let r=this.tryConvertGrpcMessage();if(r!=null)return r}tryConvertGrpcEnum(){if(this.schema.$typeName==="google.protobuf.EnumDescriptorProto"){let r=new Otu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],enum:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:new Set,docs:this.context.getCommentForPath(this.sourceCodeInfoPath)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new wtu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],message:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:r.convertedSchema,inlinedTypes:r.inlinedTypes}}}createTypeDeclaration({shape:t,referencedTypes:r,docs:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:i,referencedTypes:r,source:void 0,inline:void 0,v2Examples:void 0}}convertDeclaredTypeName(){let t=this.context.maybePrependPackageName(this.schema.name);return{typeId:t,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.schema.name}}};var CQn=class extends I6{comments;codeGeneratorRequest;constructor({comments:t,codeGeneratorRequest:r,...i}){super(i),this.comments=t,this.codeGeneratorRequest=r}resolveTypeIdToProtoFile(t){if(t.startsWith(this.spec.package)){for(let r of this.spec.messageType)if(`${this.spec.package}.${r.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:r,protoFileName:this.spec.name}}for(let r of this.codeGeneratorRequest.protoFile.filter(i=>i.name!==this.spec.name))if(t.startsWith(r.package)){for(let i of r.messageType)if(`${r.package}.${i.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:i,protoFileName:r.name}}return{ok:!1}}getCodeGeneratorRequest(){return this.codeGeneratorRequest}maybePrependPackageName(t){return this.maybeRemoveLeadingPeriod(t).startsWith(this.spec.package)?t:this.spec.package+"."+t}convertReferenceToTypeReference({reference:t}){return{ok:!1}}convertGrpcReferenceToTypeReference({typeName:t,displayNameOverride:r}){return{ok:!0,reference:ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(this.maybeRemoveLeadingPeriod(t)),typeId:this.maybeRemoveLeadingPeriod(t),default:void 0,inline:!1,displayName:r})}}maybeRemoveLeadingPeriod(t){return t.startsWith(".")?t.slice(1):t}maybeRemoveGrpcPackagePrefix(t){let r=t.split(".").filter(n=>n!==""),i=this.spec.package.split(".").filter(n=>n!=="");for(;r.length>0&&i.length>0;){if(r[0]!==i[0])return t;r.shift(),i.shift()}return r.length===0?t:r.join(".")}updateTypeId(t,r){return{...t,typeDeclaration:{...t.typeDeclaration,name:{...t.typeDeclaration.name,typeId:r}}}}getCommentForPath(t){if(!t||t.length===0)return;let r=t[0];if(!(r in this.comments))return;let i=this.comments[r];for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0||!i)return;i=i[a]}return i?._comment}};function Fjc(){return{4:{},5:{},6:{}}}function F0_(e){let t=Fjc();return e.package?.startsWith("google.protobuf")||e.sourceCodeInfo?.location.forEach(r=>{let i=r.path;if(!i||i.length===0)return;let n=i[0];if(!(n in t))return;let a=r.leadingComments||r.trailingComments||"";if(!a)return;let u=t[n];for(let c=1;c<i.length;c++){let d=i[c];d!=null&&(d in u||(u[d]={}),u=u[d])}u._comment=a.trim()}),t}var _8a=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING="example";EXAMPLE_NUMBER=42;EXAMPLE_BOOL=!0;EXAMPLE_BYTES="bytes";message;type;depth;seenMessages;constructor({breadcrumbs:t,context:r,message:i,type:n,depth:a=0,seenMessages:u=new Set}){super({context:r,breadcrumbs:t}),this.message=i,this.type=n,this.depth=a,this.seenMessages=u}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:{},errors:[]};let t=this.getFullyQualifiedMessageName(this.message);if(this.seenMessages.has(t))return{isValid:!0,coerced:!1,validExample:{},errors:[]};let r=new Set(this.seenMessages);r.add(t);try{return this.convertMessage(r)}catch(i){return{isValid:!1,coerced:!1,validExample:{},errors:[`Failed to convert message ${t}: ${i}`]}}}getFullyQualifiedMessageName(t){let r=this.context.spec.package||"",i=t.name||"";return r?`${r}.${i}`:i}convertMessage(t){let r=new Map,i=new Map,n=new Map;this.message.oneofDecl&&this.message.oneofDecl.forEach((o,l)=>{o.name&&n.set(l,o.name)});for(let o of this.message.field)Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&(i.has(o.oneofIndex)||i.set(o.oneofIndex,o));for(let o of this.message.field){let l=o.name??"";if(!(!l||Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&i.get(o.oneofIndex)!==o))try{let g=this.convertField({field:o,seenMessages:t,fieldName:l});r.set(l,{field:o,result:g})}catch(g){r.set(l,{field:o,result:{isValid:!1,coerced:!1,validExample:null,errors:[`Error converting field ${l}: ${g}`]}})}}let a=Array.from(r.values()),u=a.every(({result:o})=>o.isValid),c=a.flatMap(({result:o})=>o.errors),d={},s=new Map;for(let[o,{field:l,result:b}]of r.entries()){if(!b.isValid||b.validExample===null||b.validExample===void 0)continue;if(Object.hasOwn(l,"oneofIndex")&&l.oneofIndex!=null&&n.has(l.oneofIndex)){let O=n.get(l.oneofIndex)??void 0;O!=null&&s.set(O,{fieldName:o,value:b.validExample})}else d[o]=b.validExample}for(let[o,{fieldName:l,value:b}]of s.entries())d[o]={[l]:b};return{isValid:u,coerced:!1,validExample:d,errors:c}}convertField({field:t,seenMessages:r,fieldName:i}){return t.label===E2n.REPEATED?this.convertRepeatedField({field:t,seenMessages:r,fieldName:i}):this.convertSingleField({field:t,seenMessages:r,fieldName:i})}convertRepeatedField({field:t,seenMessages:r,fieldName:i}){let n=this.convertSingleField({field:t,seenMessages:r,fieldName:i});return{isValid:n.isValid,coerced:!1,validExample:n.isValid?[n.validExample]:[],errors:n.errors}}convertSingleField({field:t,seenMessages:r,fieldName:i}){switch(t.type){case Gg.DOUBLE:case Gg.FLOAT:case Gg.INT64:case Gg.UINT64:case Gg.INT32:case Gg.FIXED64:case Gg.FIXED32:case Gg.UINT32:case Gg.SFIXED32:case Gg.SFIXED64:case Gg.SINT32:case Gg.SINT64:return this.convertNumber();case Gg.BOOL:return this.convertBoolean();case Gg.STRING:return this.convertString(this.EXAMPLE_STRING);case Gg.BYTES:return this.convertBytes();case Gg.ENUM:return this.convertEnum(t);case Gg.MESSAGE:return this.convertMessage_Field(t,r,i);default:return{isValid:!1,coerced:!1,validExample:null,errors:[`Unsupported field type: ${t.type}`]}}}convertNumber(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_NUMBER,errors:[]}}convertBoolean(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BOOL,errors:[]}}convertString(t){return{isValid:!0,coerced:!1,validExample:t,errors:[]}}convertBytes(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BYTES,errors:[]}}convertEnum(t){let r=t.typeName??"",i=this.context.maybeRemoveLeadingPeriod(r),n=this.findEnumType(i);return n?n.value.length===0?{isValid:!0,coerced:!1,validExample:0,errors:[]}:{isValid:!0,coerced:!1,validExample:n.value[0]?.number??0,errors:[]}:{isValid:!1,coerced:!1,validExample:0,errors:[`Enum type ${t.typeName} not found`]}}convertMessage_Field(t,r,i){let n=t.typeName;if(!n)return{isValid:!1,coerced:!1,validExample:null,errors:[`Missing type name for message field ${i}`]};let a=this.context.maybeRemoveLeadingPeriod(n),u,c;if(this.context.getCodeGeneratorRequest())for(let s of this.context.getCodeGeneratorRequest().protoFile){let o=this.context.resolveTypeIdToProtoFile(a);if(o.ok){u=o.message,o.protoFileName!==this.context.spec.name?c=new CQn({...this.context,comments:Fjc(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:s,logger:new TQn}):c=this.context;break}}return!u||!c?{isValid:!0,coerced:!1,validExample:null,errors:[`Could not find message type ${a}`]}:new e({context:c,breadcrumbs:[...this.breadcrumbs,i],message:u,type:this.type,depth:this.depth+1,seenMessages:r}).convert()}findEnumType(t){let r=this.findEnumInFile(t,this.context.spec);if(!r&&this.context.getCodeGeneratorRequest()){for(let i of this.context.getCodeGeneratorRequest().protoFile)if(r=this.findEnumInFile(t,i),r!=null)break}return r}findEnumInFile(t,r){let i=r.package||"";for(let n of r.enumType)if((i?`${i}.${n.name}`:n.name||"")===t||n.name===t)return n;for(let n of r.messageType){let a=this.findEnumInMessage(t,n,i);if(a!=null)return a}}findEnumInMessage(t,r,i){let n=i?`${i}.${r.name}`:r.name||"";for(let a of r.enumType)if(`${n}.${a.name}`===t||a.name===t)return a;for(let a of r.nestedType){let u=this.findEnumInMessage(t,a,n);if(u!=null)return u}}};var Stu=class extends f_{operation;serviceName;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,operation:i,serviceName:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.serviceName=n,this.sourceCodeInfoPath=a}convert(){let t=this.context.spec.package,r=this.convertRequestBody(),i=this.convertResponseBody();return{group:[t,this.serviceName],endpoint:{id:this.operation.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),name:this.context.casingsGenerator.generateName(this.context.maybePrependPackageName(this.operation.name)),requestBody:r?.requestBody,v2RequestBodies:void 0,response:i?.responseBody,v2Responses:void 0,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:eI.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:{}},path:{head:this.operation.name,parts:[]},pathParameters:[],queryParameters:[],headers:[],sdkRequest:void 0,errors:[],auth:!1,availability:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:!1,basePath:void 0,fullPath:{head:this.operation.name,parts:[]},allPathParameters:[],pagination:void 0,transport:void 0,source:eK.proto({methodType:this.getGrpcMethodType()}),audiences:[]}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?lGt.BidirectionalStream:this.operation.clientStreaming?lGt.ClientStream:this.operation.serverStreaming?lGt.ServerStream:lGt.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:XA.reference({contentType:"application/proto",docs:void 0,requestBodyType:t.reference,v2Examples:void 0}),requestExample:void 0}:{requestBody:void 0,requestExample:void 0}}convertResponseBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.outputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.outputType)});return t.ok?{responseBody:{body:j1.json(GL.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var Dtu=class extends f_{service;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,service:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.service=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let[r,i]of this.service.method.entries()){let a=new Stu({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.SERVICE.METHOD,r]}).convert();a!=null&&t.push(a)}return{endpoints:t,serviceName:this.context.maybePrependPackageName(this.service.name),serviceDisplayName:this.service.name,inlinedTypes:{}}}};function L0_(){return{displayName:void 0,request:{endpoint:{method:Xrr.Post,path:""},baseUrl:void 0,environment:void 0,auth:void 0,headers:void 0,docs:void 0,pathParameters:void 0,queryParameters:void 0,requestBody:void 0},response:{statusCode:200,body:Hs.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var Etu=class extends mQt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}convert(){return this.convertOptions(),this.convertEnumsAndMessages(),this.convertServices(),this.generateExamplesForServices(),this.finalizeIr()}convertOptions(){}convertEnumsAndMessages(){for(let[t,r]of this.context.spec.enumType.entries()){let n=new GRi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[gtu.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...U0_(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new GRi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[gtu.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...U0_(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new Dtu({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[gtu.SERVICE,t]}).convert();if(n!=null)for(let a of n.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:n.serviceName,endpointGroupDisplayName:n.serviceDisplayName})}}generateExamplesForServices(){for(let[t,r]of Object.entries(this.ir.services))for(let[i,n]of Object.entries(r.endpoints)){let a=L0_(),u=this.constructRequestBodyExample(n),c=this.constructResponseBodyExample(n);u!=null&&a.request!=null&&(a.request.requestBody=u),c!=null&&a.response!=null&&(a.response.body=V4.json(c)),n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{[i]:a}}}}constructRequestBodyExample(t){let r=t.requestBody.requestBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new _8a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"request"}).convert().validExample}constructResponseBodyExample(t){let r=(t.response?.body).value.responseBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new _8a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"response"}).convert().validExample}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:a,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}finalizeIr(){return{...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0}}};function U0_(e,t){return Object.fromEntries(Object.entries(e).map(([r,i])=>[t(r),i]))}function V0_({req:e,options:t}){let r,i=Aee({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let c=new Etu({context:new CQn({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new WRi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new TQn,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:F0_(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();c!=null&&(r=r===void 0?c:Nin(r,c,i))}let n=Up.IntermediateRepresentation.json(r,{allowUnrecognizedEnumValues:!0,skipValidation:!0});return n.ok?{name:"ir.json",content:JSON.stringify(n.value,null,2)}:{name:"ir.json",content:JSON.stringify(n.errors,null,2)}}function W0_(e){return{}}var Ljc=NAE({name:"protoc-gen-fern",version:`v${String(h0_)}`,run:V0_});function NAE({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=W0_(i.parameter),a=r({req:i,options:n});return FAE([a],xxd,Rxd)}}}function FAE(e,t,r){return EIa(MMo,{supportedFeatures:BC.parse(IIa.PROTO3_OPTIONAL|IIa.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var G0_=ui(require("net"),1),Q0_=ui(require("os"),1),Mtu=class extends Error{constructor(t){super(`${t} is locked`)}},BQn={old:new Set,young:new Set},LAE=1e3*15;var h8a,UAE=()=>{let e=Q0_.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let i of r)t.add(i.address);return t},H0_=e=>new Promise((t,r)=>{let i=G0_.default.createServer();i.unref(),i.on("error",r),i.listen(e,()=>{let{port:n}=i.address();i.close(()=>{t(n)})})}),$0_=async(e,t)=>{if(e.host||e.port===0)return H0_(e);for(let r of t)try{await H0_({port:e.port,host:r})}catch(i){if(!["EADDRNOTAVAIL","EINVAL"].includes(i.code))throw i}return e.port},VAE=function*(e){e&&(yield*e),yield 0};async function IQn(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let n=e.exclude;if(typeof n[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of n){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(n)}h8a===void 0&&(h8a=setTimeout(()=>{h8a=void 0,BQn.old=BQn.young,BQn.young=new Set},LAE),h8a.unref&&h8a.unref());let i=UAE();for(let n of VAE(t))try{if(r.has(n))continue;let a=await $0_({...e,port:n},i);for(;BQn.old.has(a)||BQn.young.has(a);){if(n!==0)throw new Mtu(n);a=await $0_({...e,port:n},i)}return BQn.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Mtu))throw a}throw new Error("No available ports found")}var Lin=class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function J0_(){return WAE()?0:1}function WAE(){return HAE()&&!process.defaultApp}function HAE(){return!!process.versions.electron}function Ujc(e){return e.slice(J0_()+1)}function K0_(){return process.argv[J0_()]}var Atu=require("assert");var X0_=require("util"),Z0_=require("fs"),k0_=require("url");var jQt=require("path");var JAE={},$AE="require is not supported by ESM",Y0_="loading a directory of commands is not supported yet for ESM",y8a;try{y8a=(0,k0_.fileURLToPath)(JAE.url)}catch{y8a=process.cwd()}var GAE=y8a.substring(0,y8a.lastIndexOf("node_modules")),QAE={assert:{notStrictEqual:Atu.notStrictEqual,strictEqual:Atu.strictEqual},cliui:u2a,findUp:wko,getEnv:e=>process.env[e],inspect:X0_.inspect,getCallerFile:()=>{throw new Lin(Y0_)},getProcessArgvBin:K0_,mainFilename:GAE||process.cwd(),Parser:xGn,path:{basename:jQt.basename,dirname:jQt.dirname,extname:jQt.extname,relative:jQt.relative,resolve:jQt.resolve},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:Z0_.readFileSync,require:()=>{throw new Lin($AE)},requireDirectory:()=>{throw new Lin(Y0_)},stringWidth:e=>[...e].length,y18n:Sko({directory:(0,jQt.resolve)(y8a,"../../../locales"),updateFiles:!1})};var Bg_=ui(Cg_(),1),{applyExtends:uqE,cjsPlatformShim:sqE,Parser:cqE,processArgv:lqE,Yargs:Vtu}=Bg_.default;Vtu.applyExtends=(e,t,r)=>uqE(e,t,r,sqE);Vtu.hideBin=lqE.hideBin;Vtu.Parser=cqE;var Ig_=Vtu;var zg_=require("fs/promises");var xg_=require("path"),Rg_=ui(Gk(),1);async function Ng_({url:e,logger:t}){try{let r=await fqE({url:e,logger:t}),i=await Rg_.default.dir(),n=(0,xg_.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,zg_.writeFile)(n,r),{status:"success",filePath:n}}catch(r){return t.debug(`Encountered an error while loading OpenAPI spec: ${JSON.stringify(r)}`),{status:"failure",errorMessage:`Failed to load OpenAPI spec from ${e}`}}}async function fqE({url:e,logger:t}){let r=await o7.get(e),i=r.headers["content-type"]??"";return i.includes("json")||e.endsWith(".json")?typeof r.data=="string"?r.data:JSON.stringify(r.data,null,2):i.includes("yaml")||e.endsWith(".yml")||e.endsWith(".yaml")?typeof r.data=="string"?r.data:BBo(r.data):(t.warn(`Unrecognized Content-Type "${i}" from endpoint ${e}. Please ensure you're pointing to a URL that returns JSON or YAML and not HTML (e.g. Swagger UI webpage)`),BBo(r.data))}var j8a=ui(igi(),1);function cwc(e,t){if(e=j8a.default.parse(e),t=j8a.default.parse(t),!(j8a.default.compareBuild(e,t)>=0))return j8a.default.diff(e,t)||"build"}var dqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,pqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,_qE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,hqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,yqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,vqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function Xin(e){let t=e.match(yqE);if(t!=null){let[c,d,s,o,l]=t,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:b,minor:g,patch:O,index:m}}let r=e.match(vqE);if(r!=null){let[c,d,s,o,l]=r,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:b,minor:g,patch:O,index:m}}let i=e.match(dqE);if(i!=null){let[c,d,s,o,l]=i,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:b,minor:g,patch:O,commitIndex:m}}let n=e.match(_qE);if(n!=null){let[c,d,s,o,l]=n,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:b,minor:g,patch:O,releaseCandidateIndex:m}}let a=e.match(pqE);if(a!=null){let[c,d,s,o,l,b]=a,g=OR(d),O=OR(s),m=OR(o),P=OR(l),D=OR(b);if(g==null||O==null||m==null||P==null||D==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:g,minor:O,patch:m,releaseCandidateIndex:P,commitIndex:D}}let u=e.match(hqE);if(u!=null){let[c,d,s,o]=u,l=OR(d),b=OR(s),g=OR(o);if(l==null||b==null||g==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:l,minor:b,patch:g}}throw new Error("Failed to parse version: "+e)}function OR(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function que(e,t){if(e===t)return!1;let r=Xin(e),i=Xin(t);if(r.major!==i.major||r.minor!==i.minor||r.patch!==i.patch)return cwc(Fg_(r),Fg_(i))==null;if(r.type==="post-release-commit")return i.type!=="post-release-commit"||r.commitIndex>i.commitIndex;if(r.type==="release")return i.type!=="post-release-commit";if(r.type==="rc"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}return r.releaseCandidateIndex!==i.releaseCandidateIndex&&r.releaseCandidateIndex>i.releaseCandidateIndex}if(r.type==="post-rc-commit"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}if(i.type==="post-rc-commit")return r.releaseCandidateIndex!==i.releaseCandidateIndex?r.releaseCandidateIndex>i.releaseCandidateIndex:r.commitIndex>i.commitIndex}if(r.type==="beta"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1;case"alpha":return!0}return r.index>i.index}if(r.type==="alpha"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1}return r.index>i.index}return!que(t,e)}function Fg_(e){return`${e.major}.${e.minor}.${e.patch}`}var MK=e=>e.name==="up",wqe=e=>e.name==="down",Lg_=e=>e.name==="space",UQn=e=>e.name==="backspace",YRi=e=>e.name==="tab",Wtu=e=>"1234567890".includes(e.name),o2=e=>e.name==="enter"||e.name==="return";var Htu=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},$tu=class extends Error{name="CancelPromptError";message="Prompt was canceled"},w8a=class extends Error{name="ExitPromptError"},Gtu=class extends Error{name="HookError"},Gar=class extends Error{name="ValidationError"};var Hg_=require("async_hooks");var Qtu=require("async_hooks");var Ug_=new Qtu.AsyncLocalStorage;function bqE(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Vg_(e,t){let r=bqE(e);return Ug_.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Zin(){let e=Ug_.getStore();if(!e)throw new Gtu("[Inquirer] Hook functions can only be called from within a prompt");return e}function lwc(){return Zin().rl}function fwc(e){let t=(...r)=>{let i=Zin(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return Qtu.AsyncResource.bind(t)}function VQn(e){let t=Zin(),{index:r}=t,i={get(){return t.hooks[r]},set(a){t.hooks[r]=a},initialized:r in t.hooks},n=e(i);return t.index++,n}function Wg_(){Zin().handleChange()}var kin={queue(e){let t=Zin(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(lwc());if(i!=null&&typeof i!="function")throw new Gar("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Zin();fwc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Zin();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function ng(e){return VQn(t=>{let r=Hg_.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),Wg_())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function Sqe(e,t){VQn(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&kin.queue(e),r.set(t)})}var p6e=ui(u5(),1);var $g_={prefix:{idle:p6e.default.blue("?"),done:p6e.default.green(Q4.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>p6e.default.yellow(e))},style:{answer:p6e.default.cyan,message:p6e.default.bold,error:e=>p6e.default.red(`> ${e}`),defaultAnswer:e=>p6e.default.dim(`(${e})`),help:p6e.default.dim,highlight:p6e.default.cyan,key:e=>p6e.default.cyan(p6e.default.bold(`<${e}>`))}};function Gg_(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Qg_(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=Gg_(a)&&Gg_(n)?Qg_(a,n):n}return t}function j3(...e){let t=[$g_,...e.filter(r=>r!=null)];return Qg_(...t)}function R6({status:e="idle",theme:t}){let[r,i]=ng(!1),[n,a]=ng(0),{prefix:u,spinner:c}=j3(t);return Sqe(()=>{if(e==="loading"){let s,o=-1,l=setTimeout(()=>{i(!0),s=setInterval(()=>{o=o+1,a(o%c.frames.length)},c.interval)},300);return()=>{clearTimeout(l),clearInterval(s)}}else i(!1)},[e]),r?c.frames[n]:typeof u=="string"?u:u[e==="loading"?"idle":e]??u.idle}function Tue(e,t){return VQn(r=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,a)=>n!==t[a])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function _6e(e){return ng({current:e})[0]}function N6(e){let t=_6e(e);t.current=e,Sqe(r=>{let i=!1,n=fwc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var Jg_=ui(rlc(),1),Kg_=ui(llc(),1);function S8a(e,t){return e.split(`
1925
1925
  `).flatMap(r=>(0,Kg_.default)(r,t,{trim:!1,hard:!0}).split(`
1926
1926
  `).map(i=>i.trimEnd())).join(`
@@ -1962,7 +1962,7 @@ ${E}${A}${C}${_m_.default.cursorHide}`});function jru({message:e,error:t,logger:
1962
1962
  Run ${Bs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1963
1963
  Run ${Bs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),WWn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Z1c({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Rm_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of u)n+=`
1964
1964
  ${await HTE(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Bs.dim(c.currentVersion)+Bs.reset(" \u2192 ")+Bs.green(c.latestVersion);return n+=`
1965
- `,i?WWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HTE(e){let r=await new xm_.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 $TE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let b=_Ii(o.name,l),g=await Qrr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=_Ii(s.name,o),b=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await bGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function Lm_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=que(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Eru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await $TE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...Lm_(s,d,t.logger));else u.push(...Lm_(c.versions,void 0,t.logger))}return u}var L8a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var KQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var k1c=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Um_=typeof globalThis.AbortController=="function",Vm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Wm_=typeof globalThis.ReadableStream=="function",Hm_=typeof globalThis.FormData=="function",Mru=["get","post","put","patch","head","delete"],GTE=()=>{};GTE();var $m_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Aru=2147483647,Gm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,qru=Symbol("stop"),Qm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Jm_={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 QTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Gm_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Km_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:c,value:d}=await a.read();if(c){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},Ym_=(e,t,r)=>{let i=QTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var YQn=e=>e!==null&&typeof e=="object";var U8a=(...e)=>{for(let t of e)if((!YQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return rSc({},...e)},eSc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Tru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:rSc(e[r]??[],t[r]??[])}var tSc=(e={},t={})=>({beforeRequest:Tru(e,t,"beforeRequest"),beforeRetry:Tru(e,t,"beforeRetry"),afterResponse:Tru(e,t,"afterResponse"),beforeError:Tru(e,t,"beforeError")}),rSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(YQn(n)){for(let[a,u]of Object.entries(n))YQn(u)&&a in t&&(u=rSc(t[a],u)),t={...t,[a]:u};YQn(n.hooks)&&(i=tSc(i,n.hooks),t.hooks=i),YQn(n.headers)&&(r=eSc(r,n.headers),t.headers=r)}return t};var Zm_=e=>Mru.includes(e)?e.toUpperCase():e,JTE=["get","put","head","delete","options","trace"],KTE=[408,413,429,500,502,503,504],YTE=[413,429,503],Xm_={limit:2,methods:JTE,statusCodes:KTE,afterStatusCodes:YTE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},km_=(e={})=>{if(typeof e=="number")return{...Xm_,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{...Xm_,...e}};async function iSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new KQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function nSc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var eP_=(e,t)=>{let r={};for(let i in t)!(i in Jm_)&&!(i in Qm_)&&!(i in e)&&(r[i]=t[i]);return r},tP_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var V8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Aru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Aru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new L8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Wm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Km_(c.clone(),i._options.onDownloadProgress)}return c},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[c,d]of Object.entries($m_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:eSc(this._input.headers,r.headers),hooks:tSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Zm_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:km_(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(Um_&&Vm_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(k1c&&(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),tP_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Hm_&&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)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!k1c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ym_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof KQn)throw t;if(t instanceof L8a){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Aru);if(this._retryCount<1)throw r;await nSc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===qru)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=eP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):iSc(r,t,this.abortController,this._options)}};var aSc=e=>{let t=(r,i)=>V8a.create(r,U8a(e,i));for(let r of Mru)t[r]=(i,n)=>V8a.create(i,U8a(e,n,{method:r}));return t.create=r=>aSc(U8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),aSc(U8a(e,r))),t.stop=qru,t},XTE=aSc(),rP_=XTE;var SP_=ui(wP_(),1);function lSc(e){let t=(0,SP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var gj_=ui(bj_(),1),Oj_=ui(igi(),1),jSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},wSc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function SSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??lSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,gj_.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,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await rP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new jSc(e):l}if(t.allVersions)return s;let o=new wSc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Oj_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function J8a(e,t){let{version:r}=await SSc(e.toLowerCase(),t);return r}async function t3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:J8a(e.packageName,{version:t?"prerelease":"latest"})}var mj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Wru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Dru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.70.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,jru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IWn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Nm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1965
+ `,i?WWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HTE(e){let r=await new xm_.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 $TE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let b=_Ii(o.name,l),g=await Qrr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=_Ii(s.name,o),b=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function Fm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await bGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function Lm_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=que(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Eru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await $TE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...Lm_(s,d,t.logger));else u.push(...Lm_(c.versions,void 0,t.logger))}return u}var L8a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var KQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var k1c=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Um_=typeof globalThis.AbortController=="function",Vm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Wm_=typeof globalThis.ReadableStream=="function",Hm_=typeof globalThis.FormData=="function",Mru=["get","post","put","patch","head","delete"],GTE=()=>{};GTE();var $m_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Aru=2147483647,Gm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,qru=Symbol("stop"),Qm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Jm_={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 QTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Gm_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Km_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:c,value:d}=await a.read();if(c){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},Ym_=(e,t,r)=>{let i=QTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var YQn=e=>e!==null&&typeof e=="object";var U8a=(...e)=>{for(let t of e)if((!YQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return rSc({},...e)},eSc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Tru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:rSc(e[r]??[],t[r]??[])}var tSc=(e={},t={})=>({beforeRequest:Tru(e,t,"beforeRequest"),beforeRetry:Tru(e,t,"beforeRetry"),afterResponse:Tru(e,t,"afterResponse"),beforeError:Tru(e,t,"beforeError")}),rSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(YQn(n)){for(let[a,u]of Object.entries(n))YQn(u)&&a in t&&(u=rSc(t[a],u)),t={...t,[a]:u};YQn(n.hooks)&&(i=tSc(i,n.hooks),t.hooks=i),YQn(n.headers)&&(r=eSc(r,n.headers),t.headers=r)}return t};var Zm_=e=>Mru.includes(e)?e.toUpperCase():e,JTE=["get","put","head","delete","options","trace"],KTE=[408,413,429,500,502,503,504],YTE=[413,429,503],Xm_={limit:2,methods:JTE,statusCodes:KTE,afterStatusCodes:YTE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},km_=(e={})=>{if(typeof e=="number")return{...Xm_,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{...Xm_,...e}};async function iSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new KQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function nSc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var eP_=(e,t)=>{let r={};for(let i in t)!(i in Jm_)&&!(i in Qm_)&&!(i in e)&&(r[i]=t[i]);return r},tP_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var V8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Aru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Aru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new L8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Wm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Km_(c.clone(),i._options.onDownloadProgress)}return c},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[c,d]of Object.entries($m_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:eSc(this._input.headers,r.headers),hooks:tSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Zm_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:km_(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(Um_&&Vm_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(k1c&&(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),tP_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Hm_&&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)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!k1c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ym_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof KQn)throw t;if(t instanceof L8a){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Aru);if(this._retryCount<1)throw r;await nSc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===qru)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=eP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):iSc(r,t,this.abortController,this._options)}};var aSc=e=>{let t=(r,i)=>V8a.create(r,U8a(e,i));for(let r of Mru)t[r]=(i,n)=>V8a.create(i,U8a(e,n,{method:r}));return t.create=r=>aSc(U8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),aSc(U8a(e,r))),t.stop=qru,t},XTE=aSc(),rP_=XTE;var SP_=ui(wP_(),1);function lSc(e){let t=(0,SP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var gj_=ui(bj_(),1),Oj_=ui(igi(),1),jSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},wSc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function SSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??lSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,gj_.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,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await rP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new jSc(e):l}if(t.allVersions)return s;let o=new wSc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Oj_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function J8a(e,t){let{version:r}=await SSc(e.toLowerCase(),t);return r}async function t3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:J8a(e.packageName,{version:t?"prerelease":"latest"})}var mj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Wru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Dru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.70.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,jru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IWn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Nm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1966
1966
  `)||(r+=`
1967
1967
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=jHs(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new I8a(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new H8}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await IWn()).sendEvent(t)}logger=utr((t,...r)=>this.log(t,...r));stderr=utr((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Pj_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Pj_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=mj_[this.numTasks++%mj_.length],u=Bs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===BI.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}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>DBi.indexOf(n.level)>=DBi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Sb.Debug,stderr:r})}_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 t3i({cliEnvironment:this.environment,includePreReleases:t}),i=que(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Eru({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await R1c({message:t,default:r})}async getInput(t){return await N1c({message:t.message,default:t.default})}};function Pj_(e){return`[${e}]:`}var DQt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var Eqe=class extends DQt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var jmi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1};function K8a({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??jmi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??jmi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??jmi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??jmi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??jmi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??jmi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??jmi.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??jmi.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??jmi.respectForwardCompatibleEnums}}var TK={openapi:e=>({...e,type:"openapi",_visit:function(t){return TK._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return TK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var iJn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return iJn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var jU={basic:e=>({...e,type:"basic",_visit:function(t){return jU._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return jU._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return jU._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return jU._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return jU._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var Yg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Yg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Yg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Yg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Yg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Yg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Yg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Yg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Yg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var D_={int:e=>({value:e,type:"int",_visit:function(t){return D_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return D_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return D_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return D_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return D_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return D_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return D_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return D_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return D_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return D_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return D_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var r3i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return r3i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return r3i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var i3i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return i3i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return i3i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var b$={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case b$.GenerallyAvailable:return t.generallyAvailable();case b$.Beta:return t.beta();case b$.Deprecated:return t.deprecated();default:return t._other()}}};var O6e={cursor:e=>({...e,type:"cursor",_visit:function(t){return O6e._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return O6e._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return O6e._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var wmi={language:e=>({...e,type:"language",_visit:function(t){return wmi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return wmi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var g$={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case g$.Curl:return t.curl();case g$.Python:return t.python();case g$.Javascript:return t.javascript();case g$.Typescript:return t.typescript();case g$.Go:return t.go();case g$.Ruby:return t.ruby();case g$.Csharp:return t.csharp();case g$.Java:return t.java();case g$.Js:return t.js();case g$.Node:return t.node();case g$.Ts:return t.ts();case g$.Nodets:return t.nodets();case g$.Golang:return t.golang();case g$.Dotnet:return t.dotnet();case g$.Jvm:return t.jvm();default:return t._other()}}};var EQt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return EQt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return EQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var MQt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return MQt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return MQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var O$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case O$.Get:return t.get();case O$.Post:return t.post();case O$.Put:return t.put();case O$.Patch:return t.patch();case O$.Delete:return t.delete();case O$.Head:return t.head();case O$.Options:return t.options();case O$.Trace:return t.trace();default:return t._other()}}};var Yar={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Yar._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Yar._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Yar._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Yar._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var Smi={file:e=>({...e,type:"file",_visit:function(t){return Smi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Smi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var CK={file:e=>({...e,type:"file",_visit:function(t){return CK._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return CK._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return CK._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return CK._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return CK._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return CK._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return CK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Ov={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ov._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ov._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ov._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ov._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ov._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ov._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ov._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ov._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ov._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ov._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ov._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var xw={int:e=>({...e,type:"int",_visit:function(t){return xw._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return xw._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return xw._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return xw._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return xw._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return xw._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return xw._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return xw._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return xw._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return xw._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return xw._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var _x={boolean:e=>({value:e,type:"boolean",_visit:function(t){return _x._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return _x._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Dmi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Dmi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Dmi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var Tee={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Tee._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Tee._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Tee._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Tee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var OB={file:e=>({...e,type:"file",_visit:function(t){return OB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return OB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return OB._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return OB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return OB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return OB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return OB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Nl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Nl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Nl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Nl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Nl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Nl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Nl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Nl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Nl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Nl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Nl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Nl._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Cee={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Cee._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Cee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var vp={int:e=>({...e,type:"int",_visit:function(t){return vp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return vp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return vp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return vp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return vp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return vp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return vp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return vp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return vp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return vp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return vp._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Av={};Na(Av,{AllOfPropertyConflict:()=>DJn,ArraySchema:()=>onu,ArraySchemaWithExample:()=>Rnu,Availability:()=>kru,Base64WithExample:()=>Cnu,BasicSecurityScheme:()=>riu,BearerSecurityScheme:()=>iiu,BooleanSchema:()=>enu,BooleanWithExample:()=>Bnu,BytesResponse:()=>vJn,CasingOverrides:()=>oiu,CommonProperty:()=>_nu,CommonPropertyWithExample:()=>Gnu,CursorPagination:()=>Riu,CustomCodeSample:()=>ziu,CustomCodeSampleLanguage:()=>Ciu,CustomCodeSampleSdk:()=>Iiu,CustomPagination:()=>Fiu,DateWithExample:()=>Tnu,DatetimeWithExample:()=>qnu,DiscriminatedOneOfSchema:()=>dnu,DiscriminatedOneOfSchemaWithExample:()=>Hnu,DoubleSchema:()=>Ziu,DoubleWithExample:()=>Mnu,Encoding:()=>Zru,Endpoint:()=>Liu,EndpointExample:()=>mJn,EndpointResponseExample:()=>Tiu,EndpointSdkName:()=>kar,EndpointWithExample:()=>Zj_,EnumSchema:()=>uJn,EnumSchemaWithExample:()=>znu,EnumValue:()=>o3i,ErrorExample:()=>Diu,FernExample:()=>Miu,FileResponse:()=>hJn,FileSchema:()=>biu,FloatWithExample:()=>Enu,FormUrlEncodedRequest:()=>jiu,FullEndpointExample:()=>xiu,FullExample:()=>LT,FullObjectExample:()=>piu,FullOneOfExample:()=>hiu,GlobalHeader:()=>rnu,Header:()=>s3i,HeaderExample:()=>OJn,HeaderSecurityScheme:()=>niu,HeaderWithExample:()=>f3i,HttpEndpointServer:()=>bJn,HttpError:()=>Eiu,HttpErrorWithExample:()=>Pnu,HttpMethod:()=>lJn,IdempotencyHeader:()=>inu,Int64WithExample:()=>wnu,IntSchema:()=>Yiu,IntWithExample:()=>jnu,JsonRequest:()=>Piu,JsonRequestWithExample:()=>bnu,JsonResponse:()=>yJn,JsonResponseWithExample:()=>AJn,KeyValuePair:()=>_iu,LiteralExample:()=>diu,LiteralSchema:()=>SJn,LiteralSchemaValue:()=>nnu,LongSchema:()=>Xiu,MapSchema:()=>unu,MapSchemaWithExample:()=>Nnu,MultipartRequest:()=>_Jn,MultipartRequestProperty:()=>miu,MultipartRequestPropertyEncoding:()=>Oiu,MultipartSchema:()=>giu,NamedFullExample:()=>P6e,Namespace:()=>uiu,NamespaceId:()=>fiu,NullableSchema:()=>cnu,NullableSchemaWithExample:()=>Lnu,OauthSecurityScheme:()=>ciu,ObjectProperty:()=>fnu,ObjectPropertyConflictInfo:()=>EJn,ObjectPropertyWithExample:()=>Wnu,ObjectSchema:()=>anu,ObjectSchemaWithExample:()=>Unu,OctetStreamRequest:()=>pJn,OffsetPagination:()=>Niu,OneOfSchema:()=>lnu,OneOfSchemaWithExample:()=>Vnu,OpenApiIntermediateRepresentation:()=>Yj_,OpenApiSource:()=>Jru,OptionalSchema:()=>snu,OptionalSchemaWithExample:()=>Fnu,Pagination:()=>PJn,ParseFormUrlEncodedRequest:()=>gnu,ParseMultipartRequest:()=>vnu,ParseOctetStreamRequest:()=>ynu,PathParameter:()=>fJn,PathParameterExample:()=>Aiu,PathParameterWithExample:()=>hnu,PrimitiveExample:()=>cJn,PrimitiveSchema:()=>l3i,PrimitiveSchemaValue:()=>tnu,PrimitiveSchemaValueWithExample:()=>Inu,PrimitiveSchemaWithExample:()=>qJn,PropertyKey:()=>sJn,ProtobufEncoding:()=>Xru,ProtobufSource:()=>Kru,QueryParameter:()=>dJn,QueryParameterExample:()=>gJn,QueryParameterWithExample:()=>MJn,QuerySecurityScheme:()=>aiu,ReferencedSchema:()=>eor,Request:()=>wiu,RequestWithExample:()=>Onu,Response:()=>Siu,ResponseWithExample:()=>mnu,Schema:()=>tm,SchemaId:()=>Bee,SchemaWithExample:()=>xM,Schemas:()=>Kiu,SdkGroup:()=>siu,SdkGroupInfo:()=>yiu,SdkGroupName:()=>u3i,SecurityScheme:()=>liu,SecuritySchemeId:()=>tiu,Server:()=>k8a,Source:()=>Yru,StatusCode:()=>Xar,StreamingResponseExample:()=>qiu,StringSchema:()=>kiu,StringSchemaWithExample:()=>Anu,SupportedSdkLanguage:()=>Biu,Tag:()=>eiu,TagId:()=>Iee,Tags:()=>viu,TextResponse:()=>c3i,Uint64WithExample:()=>Dnu,UintWithExample:()=>Snu,UnDiscriminatedOneOfSchema:()=>pnu,UnDiscriminatedOneOfSchemaWithExample:()=>$nu,UnknownSchemaWithExample:()=>xnu,Webhook:()=>Uiu,WebhookExampleCall:()=>wJn,WebhookHttpMethod:()=>jJn,WebhookWithExample:()=>kj_,WebsocketChannel:()=>Jiu,WebsocketHandshake:()=>Viu,WebsocketHandshakeWithExample:()=>Xj_,WebsocketMessageExample:()=>Giu,WebsocketMessageOrigin:()=>Wiu,WebsocketMessageSchema:()=>Hiu,WebsocketServer:()=>$iu,WebsocketSessionExample:()=>Qiu,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Bue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>Zar,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um,commons:()=>qSc,example:()=>TSc,finalIr:()=>CSc,parseIr:()=>BSc});var qSc={};Na(qSc,{BasicSecurityScheme:()=>riu,BearerSecurityScheme:()=>iiu,Encoding:()=>Zru,HeaderSecurityScheme:()=>niu,Namespace:()=>uiu,NamespaceId:()=>fiu,OauthSecurityScheme:()=>ciu,OpenApiSource:()=>Jru,ProtobufEncoding:()=>Xru,ProtobufSource:()=>Kru,QuerySecurityScheme:()=>aiu,SchemaId:()=>Bee,SdkGroup:()=>siu,SdkGroupName:()=>u3i,SecurityScheme:()=>liu,SecuritySchemeId:()=>tiu,Server:()=>k8a,Source:()=>Yru,StatusCode:()=>Xar,Tag:()=>eiu,TagId:()=>Iee,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Bue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>Zar,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um});var gt={};Na(gt,{JsonError:()=>nJn,ParseError:()=>aJn,any:()=>Rj_,bigint:()=>wj_,boolean:()=>Nj_,booleanLiteral:()=>xj_,date:()=>Sj_,discriminant:()=>Qj_,enum_:()=>$ru,getObjectLikeUtils:()=>AQt,getObjectUtils:()=>hnn,getSchemaUtils:()=>FT,isProperty:()=>a3i,lazy:()=>Dj_,lazyObject:()=>Bj_,list:()=>Qru,number:()=>Fj_,object:()=>Gru,objectWithoutOptionalProperties:()=>Cj_,optional:()=>DSc,property:()=>Mj_,record:()=>Wj_,set:()=>Hj_,string:()=>Lj_,stringLiteral:()=>zj_,transform:()=>ESc,undiscriminatedUnion:()=>Gj_,union:()=>Kj_,unknown:()=>Uj_,withParsedProperties:()=>ASc});var fw={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function uq(e,t){return`Expected ${t}. Received ${iBE(e)}.`}function iBE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function wU(e){return{...e,json:jj_(e.json),parse:jj_(e.parse)}}function jj_(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1968
1968
  `)),{ok:!0,value:t}):i}}function Hru(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var nJn=class e extends Error{errors;constructor(t){super(t.map(Hru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var aJn=class e extends Error{errors;constructor(t){super(t.map(Hru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function FT(e){return{optional:()=>DSc(e),transform:t=>ESc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new aJn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new nJn(i.errors)}}}function DSc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>fw.OPTIONAL};return{...t,...FT(t)}}function ESc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...FT(r)}}function wj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:uq(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:uq(t,"bigint")}]},getType:()=>fw.BIGINT};return{...wU(e),...FT(e)}}var nBE=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Sj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:uq(t,"string")}]}:nBE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:uq(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:uq(t,"Date object")}]},getType:()=>fw.DATE};return{...wU(e),...FT(e)}}function BK(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...wU(r),...FT(r)}}}function $ru(e){let t=new Set(e);return BK(fw.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:uq(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:uq(i,"enum")}]}:{ok:!0,value:i})()}function Dj_(e){let t=MSc(e);return{...t,...FT(t)}}function MSc(e){return{parse:(t,r)=>oJn(e).parse(t,r),json:(t,r)=>oJn(e).json(t,r),getType:()=>oJn(e).getType()}}function oJn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Y8a(e){return Object.entries(e)}function X8a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function n3i(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Z8a(e){return Object.keys(e)}function Ej_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function AQt(e){return{withParsedProperties:t=>ASc(e,t)}}function ASc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!n3i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uq(i,"object")}]};let a=new Set(Object.keys(t)),u=X8a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...FT(r),...AQt(r)}}function Mj_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function a3i(e){return e.isProperty}function Gru(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>a3i(i)?i.rawKey:r),_getParsedProperties:()=>Z8a(e),parse:(r,i)=>{let n={},a=[];for(let[u,c]of Y8a(e)){let d=a3i(c)?c.rawKey:u,s=a3i(c)?c.valueSchema:c,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,Tj_(s)&&a.push(d)}return Aj_({value:r,requiredKeys:a,getProperty:u=>{let c=n[u];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of Y8a(e)){let c=a3i(u)?u.valueSchema:u;Tj_(c)&&n.push(a)}return Aj_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return a3i(u)?{transformedKey:u.rawKey,transform:c=>u.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>u.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>fw.OBJECT};return{...wU(t),...FT(t),...AQt(t),...hnn(t)}}function Aj_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!n3i(e))return{ok:!1,errors:[{path:a,message:uq(e,"object")}]};let u=new Set(t),c=[],d={};for(let[s,o]of Object.entries(e)){let l=r(s);if(l!=null){u.delete(s);let b=l.transform(o);b.ok?d[l.transformedKey]=b.value:(d[s]=o,c.push(...b.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return c.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function hnn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>qj_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>qj_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>fw.OBJECT};return{...r,...FT(r),...AQt(r),...hnn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>fw.OBJECT};return{...t,...FT(t),...AQt(t),...hnn(t)}}}}function qj_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=Ej_(Z8a(t),s=>n.has(s)),c=r(X8a(t,u)),d=i(X8a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function Tj_(e){return!aBE(e)}function aBE(e){switch(e.getType()){case fw.ANY:case fw.UNKNOWN:case fw.OPTIONAL:return!0;default:return!1}}function Cj_(e){return Gru(e)}function Bj_(e){let t={...MSc(e),_getRawProperties:()=>oJn(e)._getRawProperties(),_getParsedProperties:()=>oJn(e)._getParsedProperties()};return{...t,...FT(t),...AQt(t),...hnn(t)}}function Qru(e){let t={parse:(r,i)=>Ij_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>Ij_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>fw.LIST};return{...wU(t),...FT(t)}}function Ij_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:uq(e,"list"),path:[]}]}}function zj_(e){return BK(fw.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uq(r,`"${e}"`)}]})()}function xj_(e){return BK(fw.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uq(r,`${e.toString()}`)}]})()}var Rj_=BK(fw.ANY,e=>({ok:!0,value:e}));var Nj_=BK(fw.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"boolean")}]});var Fj_=BK(fw.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"number")}]});var Lj_=BK(fw.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"string")}]});var Uj_=BK(fw.UNKNOWN,e=>({ok:!0,value:e}));function Wj_(e,t){let r={parse:(i,n)=>Vj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Vj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>fw.RECORD};return{...wU(r),...FT(r)}}function Vj_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return n3i(e)?Y8a(e).reduce((a,[u,c])=>{if(c==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),l=i(c,s);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),l.ok||b.push(...l.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:uq(e,"object")}]}}function Hj_(e){let t=Qru(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uq(i,"Set")}]},getType:()=>fw.SET};return{...wU(r),...FT(r)}}function Gj_(e){let t={parse:(r,i)=>$j_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>$j_((n,a)=>n.json(r,a),e,i),getType:()=>fw.UNDISCRIMINATED_UNION};return{...wU(t),...FT(t)}}function $j_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let c of u.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function Qj_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function Kj_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=$ru(Z8a(t)),a={parse:(u,c)=>Jj_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(u,c)=>Jj_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>fw.UNION};return{...wU(a),...FT(a),...AQt(a)}}function Jj_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:c=[]}){if(!n3i(e))return{ok:!1,errors:[{path:c,message:uq(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=n(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let b=u(s,l);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var Um=gt.objectWithoutOptionalProperties({title:gt.string().optional()});var Jru=gt.objectWithoutOptionalProperties({file:gt.string()});var Kru=gt.objectWithoutOptionalProperties({file:gt.string()});var Yru=gt.union("type",{openapi:Jru,protobuf:Kru}).transform({transform:e=>{switch(e.type){case"openapi":return TK.openapi(e);case"protobuf":return TK.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ch=gt.objectWithoutOptionalProperties({source:Yru.optional()});var Xru=gt.objectWithoutOptionalProperties({typeName:gt.string()});var Zru=gt.union("type",{protobuf:Xru}).transform({transform:e=>{switch(e.type){case"protobuf":return iJn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Bue=gt.objectWithoutOptionalProperties({encoding:Zru.optional()});var Of=gt.objectWithoutOptionalProperties({description:gt.string().optional()});var kru=gt.enum_(["GenerallyAvailable","Beta","Deprecated"]);var oy=gt.objectWithoutOptionalProperties({availability:kru.optional()});var Xar=gt.number();var m6e=gt.objectWithoutOptionalProperties({statusCode:Xar.optional()});var pg=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string()});var zM=gt.objectWithoutOptionalProperties({inline:gt.boolean().optional()});var Bee=gt.string();var Iee=gt.string();var eiu=gt.objectWithoutOptionalProperties({id:Iee}).extend(Of);var tiu=gt.string();var riu=gt.objectWithoutOptionalProperties({usernameVariableName:gt.string().optional(),usernameEnvVar:gt.string().optional(),passwordVariableName:gt.string().optional(),passwordEnvVar:gt.string().optional()});var iiu=gt.objectWithoutOptionalProperties({tokenVariableName:gt.string().optional(),tokenEnvVar:gt.string().optional()});var niu=gt.objectWithoutOptionalProperties({headerName:gt.string(),prefix:gt.string().optional(),headerVariableName:gt.string().optional(),headerEnvVar:gt.string().optional()});var aiu=gt.objectWithoutOptionalProperties({queryParameterName:gt.string()});var oiu=gt.objectWithoutOptionalProperties({snake:gt.string().optional(),camel:gt.string().optional(),screamingSnake:gt.string().optional(),pascal:gt.string().optional()});var o3i=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string(),value:gt.string(),casing:oiu.optional()}).extend(Of).extend(oy);var uiu=gt.objectWithoutOptionalProperties({type:gt.stringLiteral("namespace"),name:gt.string()});var siu=gt.undiscriminatedUnion([gt.string(),uiu]);var u3i=gt.list(siu);var Vm=gt.objectWithoutOptionalProperties({groupName:u3i.optional()});var x0=gt.objectWithoutOptionalProperties({namespace:gt.string().optional()});var uJn=gt.objectWithoutOptionalProperties({default:o3i.optional(),values:gt.list(o3i)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var ciu=gt.objectWithoutOptionalProperties({scopesEnum:uJn.optional()});var liu=gt.union("type",{basic:riu,bearer:iiu,header:niu,query:aiu,oauth:ciu}).transform({transform:e=>{switch(e.type){case"basic":return jU.basic(e);case"bearer":return jU.bearer(e);case"header":return jU.header(e);case"query":return jU.query(e);case"oauth":return jU.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var k8a=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string(),audiences:gt.list(gt.string()).optional()}).extend(Of);var fiu=gt.string();var Zar=gt.objectWithoutOptionalProperties({sdkMethodName:gt.string().optional()});var TSc={};Na(TSc,{FullExample:()=>LT,FullObjectExample:()=>piu,FullOneOfExample:()=>hiu,KeyValuePair:()=>_iu,LiteralExample:()=>diu,PrimitiveExample:()=>cJn,PropertyKey:()=>sJn});var sJn=gt.string();var cJn=gt.union("type",{int:gt.object({value:gt.number()}),int64:gt.object({value:gt.number()}),uint:gt.object({value:gt.number()}),uint64:gt.object({value:gt.number()}),float:gt.object({value:gt.number()}),double:gt.object({value:gt.number()}),string:gt.object({value:gt.string()}),datetime:gt.object({value:gt.string()}),date:gt.object({value:gt.string()}),base64:gt.object({value:gt.string()}),boolean:gt.object({value:gt.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return D_.int(e.value);case"int64":return D_.int64(e.value);case"uint":return D_.uint(e.value);case"uint64":return D_.uint64(e.value);case"float":return D_.float(e.value);case"double":return D_.double(e.value);case"string":return D_.string(e.value);case"datetime":return D_.datetime(e.value);case"date":return D_.date(e.value);case"base64":return D_.base64(e.value);case"boolean":return D_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var diu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return r3i.boolean(e.value);case"string":return r3i.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var LT=gt.union("type",{primitive:gt.object({value:cJn}),object:gt.lazyObject(()=>piu),array:gt.object({value:gt.list(gt.lazy(()=>LT))}),map:gt.object({value:gt.list(gt.lazyObject(()=>_iu))}),enum:gt.object({value:gt.string()}),literal:gt.object({value:diu}),oneOf:gt.object({value:gt.lazy(()=>hiu)}),unknown:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"primitive":return Yg.primitive(e.value);case"object":return Yg.object(e);case"array":return Yg.array(e.value);case"map":return Yg.map(e.value);case"enum":return Yg.enum(e.value);case"literal":return Yg.literal(e.value);case"oneOf":return Yg.oneOf(e.value);case"unknown":return Yg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var piu=gt.objectWithoutOptionalProperties({properties:gt.record(sJn,gt.lazy(()=>LT))});var _iu=gt.objectWithoutOptionalProperties({key:cJn,value:gt.lazy(()=>LT)});var hiu=gt.union("type",{discriminated:gt.object({value:gt.record(sJn,gt.lazy(()=>LT))}),undiscriminated:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"discriminated":return i3i.discriminated(e.value);case"undiscriminated":return i3i.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var CSc={};Na(CSc,{AllOfPropertyConflict:()=>DJn,ArraySchema:()=>onu,Availability:()=>kru,BooleanSchema:()=>enu,BytesResponse:()=>vJn,CasingOverrides:()=>oiu,CommonProperty:()=>_nu,CursorPagination:()=>Riu,CustomCodeSample:()=>ziu,CustomCodeSampleLanguage:()=>Ciu,CustomCodeSampleSdk:()=>Iiu,CustomPagination:()=>Fiu,DiscriminatedOneOfSchema:()=>dnu,DoubleSchema:()=>Ziu,Endpoint:()=>Liu,EndpointExample:()=>mJn,EndpointResponseExample:()=>Tiu,EndpointSdkName:()=>kar,EnumSchema:()=>uJn,EnumValue:()=>o3i,ErrorExample:()=>Diu,FernExample:()=>Miu,FileResponse:()=>hJn,FileSchema:()=>biu,FormUrlEncodedRequest:()=>jiu,FullEndpointExample:()=>xiu,GlobalHeader:()=>rnu,Header:()=>s3i,HeaderExample:()=>OJn,HttpEndpointServer:()=>bJn,HttpError:()=>Eiu,HttpMethod:()=>lJn,IdempotencyHeader:()=>inu,IntSchema:()=>Yiu,JsonRequest:()=>Piu,JsonResponse:()=>yJn,LiteralSchema:()=>SJn,LiteralSchemaValue:()=>nnu,LongSchema:()=>Xiu,MapSchema:()=>unu,MultipartRequest:()=>_Jn,MultipartRequestProperty:()=>miu,MultipartRequestPropertyEncoding:()=>Oiu,MultipartSchema:()=>giu,NullableSchema:()=>cnu,ObjectProperty:()=>fnu,ObjectPropertyConflictInfo:()=>EJn,ObjectSchema:()=>anu,OctetStreamRequest:()=>pJn,OffsetPagination:()=>Niu,OneOfSchema:()=>lnu,OpenApiIntermediateRepresentation:()=>Yj_,OptionalSchema:()=>snu,Pagination:()=>PJn,PathParameter:()=>fJn,PathParameterExample:()=>Aiu,PrimitiveSchema:()=>l3i,PrimitiveSchemaValue:()=>tnu,QueryParameter:()=>dJn,QueryParameterExample:()=>gJn,ReferencedSchema:()=>eor,Request:()=>wiu,Response:()=>Siu,Schema:()=>tm,Schemas:()=>Kiu,SdkGroupInfo:()=>yiu,StreamingResponseExample:()=>qiu,StringSchema:()=>kiu,SupportedSdkLanguage:()=>Biu,Tags:()=>viu,TextResponse:()=>c3i,UnDiscriminatedOneOfSchema:()=>pnu,Webhook:()=>Uiu,WebhookExampleCall:()=>wJn,WebhookHttpMethod:()=>jJn,WebsocketChannel:()=>Jiu,WebsocketHandshake:()=>Viu,WebsocketMessageExample:()=>Giu,WebsocketMessageOrigin:()=>Wiu,WebsocketMessageSchema:()=>Hiu,WebsocketServer:()=>$iu,WebsocketSessionExample:()=>Qiu});var yiu=gt.objectWithoutOptionalProperties({summary:gt.string().optional(),description:gt.string().optional()});var viu=gt.objectWithoutOptionalProperties({tagsById:gt.record(Iee,eiu),orderedTagIds:gt.list(Iee).optional()});var lJn=gt.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var fJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var dJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var s3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var kar=gt.objectWithoutOptionalProperties({groupName:u3i,methodName:gt.string()});var pJn=gt.objectWithoutOptionalProperties({contentType:gt.string().optional()}).extend(Of).extend(Ch);var biu=gt.objectWithoutOptionalProperties({isOptional:gt.boolean(),isArray:gt.boolean()}).extend(Of);var giu=gt.union("type",{file:biu,json:gt.object({value:gt.lazy(()=>tm)})}).transform({transform:e=>{switch(e.type){case"file":return Smi.file(e);case"json":return Smi.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Oiu=gt.enum_(["json","form"]);var miu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:giu,contentType:gt.string().optional(),exploded:gt.boolean().optional(),encoding:Oiu.optional()}).extend(Of);var _Jn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),properties:gt.list(miu)}).extend(Of).extend(Ch);var Piu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var jiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var wiu=gt.union("type",{octetStream:pJn,multipart:_Jn,json:Piu,formUrlEncoded:jiu}).transform({transform:e=>{switch(e.type){case"octetStream":return Yar.octetStream(e);case"multipart":return Yar.multipart(e);case"json":return Yar.json(e);case"formUrlEncoded":return Yar.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var hJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var yJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),responseProperty:gt.string().optional()}).extend(Of).extend(Ch).extend(m6e);var c3i=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var vJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var Siu=gt.union("type",{file:hJn,json:yJn,text:c3i,bytes:vJn,streamingSse:yJn,streamingText:c3i,streamingJson:yJn}).transform({transform:e=>{switch(e.type){case"file":return CK.file(e);case"json":return CK.json(e);case"text":return CK.text(e);case"bytes":return CK.bytes(e);case"streamingSse":return CK.streamingSse(e);case"streamingText":return CK.streamingText(e);case"streamingJson":return CK.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Diu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),description:gt.string().optional(),example:gt.lazy(()=>LT)});var Eiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm).optional(),examples:gt.list(Diu).optional()}).extend(Of).extend(pg).extend(Ch);var bJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string().optional(),audiences:gt.list(gt.string()).optional()});var Miu=gt.unknown();var Aiu=gt.objectWithoutOptionalProperties({name:gt.string(),parameterNameOverride:gt.string().optional(),value:gt.lazy(()=>LT)});var gJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>LT)});var OJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>LT)});var qiu=gt.objectWithoutOptionalProperties({sse:gt.boolean(),events:gt.list(gt.lazy(()=>LT))});var Tiu=gt.union("type",{withStreaming:qiu,withoutStreaming:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return MQt.withStreaming(e);case"withoutStreaming":return MQt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Ciu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),language:gt.string(),code:gt.string(),install:gt.string().optional()}).extend(Of);var Biu=gt.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var Iiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),sdk:Biu,code:gt.string()}).extend(Of);var ziu=gt.union("type",{language:Ciu,sdk:Iiu}).transform({transform:e=>{switch(e.type){case"language":return wmi.language(e);case"sdk":return wmi.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var xiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),pathParameters:gt.list(Aiu).optional(),queryParameters:gt.list(gJn).optional(),headers:gt.list(OJn).optional(),request:gt.lazy(()=>LT).optional(),response:Tiu.optional(),codeSamples:gt.list(ziu)}).extend(Of);var mJn=gt.union("type",{unknown:gt.object({value:Miu}),full:xiu}).transform({transform:e=>{switch(e.type){case"unknown":return EQt.unknown(e.value);case"full":return EQt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Riu=gt.objectWithoutOptionalProperties({cursor:gt.string(),nextCursor:gt.property("next_cursor",gt.string()),results:gt.string()});var Niu=gt.objectWithoutOptionalProperties({offset:gt.string(),results:gt.string(),step:gt.string().optional(),hasNextPage:gt.string().optional()});var Fiu=gt.objectWithoutOptionalProperties({results:gt.string()});var PJn=gt.union("type",{cursor:Riu,offset:Niu,custom:Fiu}).transform({transform:e=>{switch(e.type){case"cursor":return O6e.cursor(e);case"offset":return O6e.offset(e);case"custom":return O6e.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var Liu=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:lJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Iee),pathParameters:gt.list(fJn),queryParameters:gt.list(dJn),headers:gt.list(s3i),sdkName:kar.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:wiu.optional(),response:Siu.optional(),errors:gt.record(Xar,Eiu),servers:gt.list(bJn),examples:gt.list(mJn),pagination:PJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var jJn=gt.enum_(["GET","POST"]);var wJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),payload:gt.lazy(()=>LT)}).extend(Of);var Uiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:kar.optional(),method:jJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Iee),headers:gt.list(s3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>tm),examples:gt.list(wJn)}).extend(Of).extend(Ch).extend(x0);var Viu=gt.objectWithoutOptionalProperties({queryParameters:gt.list(dJn),headers:gt.list(s3i),pathParameters:gt.list(fJn)});var Wiu=gt.enum_(["client","server"]);var Hiu=gt.objectWithoutOptionalProperties({name:gt.string(),origin:Wiu,body:gt.lazy(()=>tm)});var $iu=gt.objectWithoutOptionalProperties({name:gt.string(),url:gt.string()});var Giu=gt.objectWithoutOptionalProperties({messageType:gt.string(),payload:gt.lazy(()=>LT)}).extend(Of);var Qiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),queryParameters:gt.list(gJn).optional(),headers:gt.list(OJn).optional(),messages:gt.list(Giu)}).extend(Of);var Jiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),path:gt.string(),groupName:u3i,summary:gt.string().optional(),handshake:Viu,messages:gt.list(Hiu),servers:gt.list($iu),examples:gt.list(Qiu)}).extend(Of).extend(Ch);var Kiu=gt.objectWithoutOptionalProperties({rootSchemas:gt.record(Bee,gt.lazy(()=>tm)),namespacedSchemas:gt.record(fiu,gt.record(Bee,gt.lazy(()=>tm)))});var Yiu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var Xiu=gt.objectWithoutOptionalProperties({default:gt.number().optional()});var Ziu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var kiu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional()});var enu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional()});var tnu=gt.union("type",{int:Yiu,int64:Xiu,uint:gt.object({}),uint64:gt.object({}),float:gt.object({}),double:Ziu,string:kiu,datetime:gt.object({}),date:gt.object({}),base64:gt.object({}),boolean:enu}).transform({transform:e=>{switch(e.type){case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();case"float":return xw.float();case"double":return xw.double(e);case"string":return xw.string(e);case"datetime":return xw.datetime();case"date":return xw.date();case"base64":return xw.base64();case"boolean":return xw.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var l3i=gt.objectWithoutOptionalProperties({schema:tnu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var rnu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),optional:gt.boolean().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var inu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var Yj_=gt.objectWithoutOptionalProperties({apiVersion:gt.unknown().optional(),title:gt.string().optional(),description:gt.string().optional(),basePath:gt.string().optional(),servers:gt.list(k8a),websocketServers:gt.list(k8a),groups:gt.record(gt.string(),yiu),tags:viu,hasEndpointsMarkedInternal:gt.boolean(),endpoints:gt.list(Liu),webhooks:gt.list(Uiu),channels:gt.record(gt.string(),Jiu),groupedSchemas:Kiu,variables:gt.record(gt.string(),l3i),nonRequestReferencedSchemas:gt.set(Bee),securitySchemes:gt.record(tiu,liu),globalHeaders:gt.list(rnu).optional(),idempotencyHeaders:gt.list(inu).optional()});var eor=gt.objectWithoutOptionalProperties({schema:Bee}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um);var nnu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return _x.boolean(e.value);case"string":return _x.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var SJn=gt.objectWithoutOptionalProperties({value:nnu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var tm=gt.union("type",{primitive:l3i,object:gt.lazyObject(()=>anu),array:gt.lazyObject(()=>onu),map:gt.lazyObject(()=>unu),optional:gt.lazyObject(()=>snu),enum:uJn,reference:eor,literal:SJn,oneOf:gt.object({value:gt.lazy(()=>lnu)}),nullable:gt.lazyObject(()=>cnu),unknown:pg}).transform({transform:e=>{switch(e.type){case"primitive":return Ov.primitive(e);case"object":return Ov.object(e);case"array":return Ov.array(e);case"map":return Ov.map(e);case"optional":return Ov.optional(e);case"enum":return Ov.enum(e);case"reference":return Ov.reference(e);case"literal":return Ov.literal(e);case"oneOf":return Ov.oneOf(e.value);case"nullable":return Ov.nullable(e);case"unknown":return Ov.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var DJn=gt.objectWithoutOptionalProperties({propertyKey:gt.string(),allOfSchemaIds:gt.list(Bee),conflictingTypeSignatures:gt.boolean()});var anu=gt.objectWithoutOptionalProperties({allOf:gt.list(eor),properties:gt.list(gt.lazyObject(()=>fnu)),allOfPropertyConflicts:gt.list(DJn),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var EJn=gt.objectWithoutOptionalProperties({differentSchema:gt.boolean()});var fnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),conflict:gt.record(Bee,EJn),generatedName:gt.string(),nameOverride:gt.string().optional(),audiences:gt.list(gt.string())}).extend(oy);var onu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var unu=gt.objectWithoutOptionalProperties({key:l3i,value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Um).extend(zM);var snu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var cnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var lnu=gt.union("type",{discriminated:gt.lazyObject(()=>dnu),undiscriminated:gt.lazyObject(()=>pnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Dmi.discriminated(e);case"undiscriminated":return Dmi.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var dnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>_nu)),schemas:gt.record(gt.string(),gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Ch).extend(Um).extend(zM);var _nu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm)});var pnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Ch).extend(Um).extend(zM);var BSc={};Na(BSc,{ArraySchemaWithExample:()=>Rnu,Base64WithExample:()=>Cnu,BooleanWithExample:()=>Bnu,CommonPropertyWithExample:()=>Gnu,DateWithExample:()=>Tnu,DatetimeWithExample:()=>qnu,DiscriminatedOneOfSchemaWithExample:()=>Hnu,DoubleWithExample:()=>Mnu,EndpointWithExample:()=>Zj_,EnumSchemaWithExample:()=>znu,FloatWithExample:()=>Enu,HeaderWithExample:()=>f3i,HttpErrorWithExample:()=>Pnu,Int64WithExample:()=>wnu,IntWithExample:()=>jnu,JsonRequestWithExample:()=>bnu,JsonResponseWithExample:()=>AJn,MapSchemaWithExample:()=>Nnu,NamedFullExample:()=>P6e,NullableSchemaWithExample:()=>Lnu,ObjectPropertyWithExample:()=>Wnu,ObjectSchemaWithExample:()=>Unu,OneOfSchemaWithExample:()=>Vnu,OptionalSchemaWithExample:()=>Fnu,ParseFormUrlEncodedRequest:()=>gnu,ParseMultipartRequest:()=>vnu,ParseOctetStreamRequest:()=>ynu,PathParameterWithExample:()=>hnu,PrimitiveSchemaValueWithExample:()=>Inu,PrimitiveSchemaWithExample:()=>qJn,QueryParameterWithExample:()=>MJn,RequestWithExample:()=>Onu,ResponseWithExample:()=>mnu,SchemaWithExample:()=>xM,StringSchemaWithExample:()=>Anu,Uint64WithExample:()=>Dnu,UintWithExample:()=>Snu,UnDiscriminatedOneOfSchemaWithExample:()=>$nu,UnknownSchemaWithExample:()=>xnu,WebhookWithExample:()=>kj_,WebsocketHandshakeWithExample:()=>Xj_});var P6e=gt.objectWithoutOptionalProperties({name:gt.string().optional(),value:gt.unknown()}).extend(Of);var MJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var f3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var Xj_=gt.objectWithoutOptionalProperties({queryParameters:gt.list(MJn),headers:gt.list(f3i)});var hnu=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var ynu=gt.objectWithoutOptionalProperties({}).extend(pJn).extend(Zar);var vnu=gt.objectWithoutOptionalProperties({}).extend(_Jn).extend(Zar);var bnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(Zar);var gnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(Zar);var Onu=gt.union("type",{octetStream:ynu,multipart:vnu,json:bnu,formUrlEncoded:gnu}).transform({transform:e=>{switch(e.type){case"octetStream":return Tee.octetStream(e);case"multipart":return Tee.multipart(e);case"json":return Tee.json(e);case"formUrlEncoded":return Tee.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var AJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),responseProperty:gt.string().optional(),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(Ch).extend(m6e);var mnu=gt.union("type",{file:hJn,json:AJn,text:c3i,bytes:vJn,streamingSse:AJn,streamingText:c3i,streamingJson:AJn}).transform({transform:e=>{switch(e.type){case"file":return OB.file(e);case"json":return OB.json(e);case"text":return OB.text(e);case"bytes":return OB.bytes(e);case"streamingSse":return OB.streamingSse(e);case"streamingText":return OB.streamingText(e);case"streamingJson":return OB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Pnu=gt.objectWithoutOptionalProperties({statusCode:Xar,schema:gt.lazy(()=>xM),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(pg).extend(Ch);var Zj_=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:lJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Iee),pathParameters:gt.list(hnu),queryParameters:gt.list(MJn),headers:gt.list(f3i),sdkName:kar.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Onu.optional(),response:mnu.optional(),errors:gt.record(Xar,Pnu),servers:gt.list(bJn),examples:gt.list(mJn),pagination:PJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var kj_=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:kar.optional(),method:jJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Iee),headers:gt.list(f3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>xM),examples:gt.list(wJn)}).extend(Of).extend(Ch).extend(x0);var jnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var wnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Snu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Dnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Enu=gt.objectWithoutOptionalProperties({example:gt.number().optional()});var Mnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Anu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional(),example:gt.string().optional()});var qnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Tnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Cnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Bnu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional(),example:gt.boolean().optional()});var Inu=gt.union("type",{int:jnu,int64:wnu,uint:Snu,uint64:Dnu,float:Enu,double:Mnu,string:Anu,datetime:qnu,date:Tnu,base64:Cnu,boolean:Bnu}).transform({transform:e=>{switch(e.type){case"int":return vp.int(e);case"int64":return vp.int64(e);case"uint":return vp.uint(e);case"uint64":return vp.uint64(e);case"float":return vp.float(e);case"double":return vp.double(e);case"string":return vp.string(e);case"datetime":return vp.datetime(e);case"date":return vp.date(e);case"base64":return vp.base64(e);case"boolean":return vp.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var qJn=gt.objectWithoutOptionalProperties({schema:Inu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var znu=gt.objectWithoutOptionalProperties({default:o3i.optional(),values:gt.list(o3i),example:gt.string().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var xnu=gt.objectWithoutOptionalProperties({example:gt.unknown()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var xM=gt.union("type",{primitive:qJn,object:gt.lazyObject(()=>Unu),array:gt.lazyObject(()=>Rnu),map:gt.lazyObject(()=>Nnu),optional:gt.lazyObject(()=>Fnu),enum:znu,reference:eor,literal:SJn,oneOf:gt.object({value:gt.lazy(()=>Vnu)}),nullable:gt.lazyObject(()=>Lnu),unknown:xnu}).transform({transform:e=>{switch(e.type){case"primitive":return Nl.primitive(e);case"object":return Nl.object(e);case"array":return Nl.array(e);case"map":return Nl.map(e);case"optional":return Nl.optional(e);case"enum":return Nl.enum(e);case"reference":return Nl.reference(e);case"literal":return Nl.literal(e);case"oneOf":return Nl.oneOf(e.value);case"nullable":return Nl.nullable(e);case"unknown":return Nl.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Rnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM),example:gt.list(gt.unknown()).optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Nnu=gt.objectWithoutOptionalProperties({key:qJn,value:gt.lazy(()=>xM),example:gt.unknown().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Um).extend(zM);var Fnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Lnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Unu=gt.objectWithoutOptionalProperties({allOf:gt.list(eor),properties:gt.list(gt.lazyObject(()=>Wnu)),allOfPropertyConflicts:gt.list(DJn),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var Wnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),audiences:gt.list(gt.string()),conflict:gt.record(Bee,EJn),nameOverride:gt.string().optional(),generatedName:gt.string()}).extend(oy);var Vnu=gt.union("type",{discriminated:gt.lazyObject(()=>Hnu),undiscriminated:gt.lazyObject(()=>$nu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Cee.discriminated(e);case"undiscriminated":return Cee.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Hnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>Gnu)),schemas:gt.record(gt.string(),gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Ch).extend(Um).extend(zM);var Gnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM)});var $nu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Bue).extend(Ch).extend(Um).extend(zM);var ew_=/^(\d+)/,TJn=/^[a-zA-Z][a-zA-Z0-9_]*$/,tw_={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function d3i(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),c=e%10;return c===0?i[u]:`${i[u]}_${t[c]}`}if(e<1e3){let u=Math.floor(e/100),c=e%100;return c===0?`${t[u]}_hundred`:`${t[u]}_hundred_${d3i(c)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${d3i(a)}`}function e5a(e){let t=e.match(ew_);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=d3i(n);return i.length>0?`${a}_${i}`:a}}}function CJn(e){let t=e5a(e),r=tw_[e];return t!=null?QB(R_(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":QB(R_(e)))}function Iue(e,t){return e.type==="primitive"&&t.type==="primitive"?rw_(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?oBE(e.values,t.values):e.type==="array"&&t.type==="array"?Iue(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?Iue(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?uBE(e.value,t.value):e.type==="object"&&t.type==="object"?sBE(e,t):e.type==="map"&&t.type==="map"?rw_(e.key.schema,t.key.schema)&&Iue(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function rw_(e,t){return e.type===t.type}function oBE(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return W8(r,i)}function uBE(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:Iue(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:Iue(r,n)}):!1}function sBE(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:Iue(a,n.schema)})}function PR(e){switch(e){case b$.Deprecated:return"deprecated";case b$.Beta:return"pre-release";case b$.GenerallyAvailable:return"generally-available";default:return}}function cBE(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function iw_(e){let t=e?cBE(e):void 0;if(t==null||t.length===0)return mZi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(R_(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(R_(n.name)):r.push(n.name,mZi);break}default:Ao(n.type)}else Ao(n);return r.join("/")}function p3i(e){return wy.of(`${iw_(e)}.yml`)}function ISc({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?mZi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,iw_(r))}function nw_({sdkName:e,namespaceOverride:t}){return wy.of(`${ISc({sdkName:e,namespaceOverride:t})}.yml`)}function aw_({location:e,namespaceOverride:t}){return t!=null?GN(wy.of(t),e):e}function Qnu(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Ao(e.type)}}function BJn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Ao(e)}}function sq(e){return typeof e=="string"?e:e.type}function IJn(e){if(typeof e!="string")return e.docs}function t5a(e){if(typeof e!="string")return e.default}function zSc(e){if(typeof e!="string")return e.validation}var lBE=-2147483648,fBE=2147483647,dBE=-17976931348623157e292,pBE=17976931348623157e292;function Xg({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return Jnu(e);case"array":return NSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return FSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return RSc({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return USc();case"optional":return Knu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return LSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return PBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,VSc(e);case"object":return jBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return wBE({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Ao(e)}}function Jnu(e){switch(e.schema.type){case"string":return yBE({description:e.description,schema:e.schema});case"int":return vBE({description:e.description,schema:e.schema});case"float":return bBE({description:e.description,schema:e.schema});case"double":return gBE({description:e.description,schema:e.schema});case"boolean":return _BE({description:e.description,schema:e.schema});case"int64":return hBE({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function _BE({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function hBE({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function yBE({description:e,schema:t}){let r="string",i=OBE(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function vBE({description:e,schema:t}){let r="integer",i=uw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function bBE({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function gBE({description:e,schema:t}){let r="double",i=uw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function OBE(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=mBE(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function mBE(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function uw_(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=xSc(r,t),i=xSc(i,t),n=xSc(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function xSc(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[lBE,fBE]:[dBE,pBE];return e<r||e>i?void 0:e}function RSc({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=SBE(n)??e.schema,u=BJn(n),c=DBE(n),d=Ynu({context:r,fileContainingReference:t,declarationFile:p3i(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&c==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function NSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=`list<${sq(u)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{},type:c}}function FSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Jnu(e.key),c=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?Qnu(e.encoding):void 0,s=`map<${sq(u)}, ${sq(c)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=PR(e.availability)),o}function LSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return Knu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=sq(u),d=IJn(u),s=t5a(u),o=zSc(u),l=c.startsWith("nullable<")?c:`nullable<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return ow_({typeReference:l,itemType:c});let b={type:l};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=PR(e.availability)),ow_({typeReference:b,itemType:c})}function Knu({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=sq(u),d=IJn(u),s=t5a(u),o=zSc(u),l=c.startsWith("optional<")?c:`optional<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return l;let b={type:l};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=PR(e.availability)),b}function USc(){return"unknown"}function VSc(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ao(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function PBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=r5a(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let c=Ynu({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return c;let d={type:c};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=PR(e.availability)),d}function jBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=WSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Ynu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function wBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=HSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Ynu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function Ynu({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function SBE(e){return Ov._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function DBE(e){return Ov._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function ow_({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var v5;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(v5||(v5={}));function Emi(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ao(e)}}function cw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=ABE(e);break;case"array":a=EBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=MBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=qBE({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=CBE(e.nameOverride,e.generatedName);break;case"optional":a=lw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=TBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=r5a(e,n);break;case"literal":a=BBE(e,e.nameOverride,e.generatedName);break;case"object":a=WSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=HSc({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Ao(e)}return a}function WSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(v5.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,c={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([E,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([E])=>{$Sc({property:g.key,schemaId:E,context:t,namespace:i}).forEach(z=>{d.add(z)})})}let O=Xg({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,P=g.nameOverride,D=PR(g.availability),A=RBE(g);c[g.key]=xBE({typeReference:O,audiences:m,name:P,availability:D,propertyAccess:A})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=fw_({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=Xg({schema:Ov.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(sq(m))}for(let g of d){let O=GSc(t,g,i);for(let m of O.properties)c[m.key]==null&&(s.has(m.key)&&(c[m.key]="unknown"),c[m.key]=Xg({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let P=Xg({schema:Ov.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(sq(P))}}let l={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(c).map(([g,O])=>zBE(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(l.extends=o),e.additionalProperties&&(l["extra-properties"]=!0),e.availability!=null&&(l.availability=PR(e.availability)),e.source!=null&&(l.source=Emi(e.source)),l.inline=QSc(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:l}}function $Sc({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return $Sc({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=GSc(r,t,i),c=a.some(s=>s.key===e),d=[...u.flatMap(s=>$Sc({property:e,context:r,schemaId:s.schema,namespace:i}))];if(c||d.length>0)return[t,...d]}return[]}function GSc(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return GSc(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function EBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:NSc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function MBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:FSc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function ABE(e){let t=Jnu(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function sw_(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function r5a(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,c=a.value;if(u===c&&a.description==null&&(a.casing==null||sw_(a.casing)))return u;let d={value:a.value};if(u!==c&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!sw_(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=QSc(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?Emi(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function qBE({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:RSc({schema:e,context:t,fileContainingReference:r,namespace:i})}}function TBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:LSc({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:lw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function lw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:Knu({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function CBE(e,t){return{name:e??t,schema:USc()}}function BBE(e,t,r){return{name:t??r,schema:VSc(e)}}function HSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?Qnu(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let s of e.commonProperties)c[s.key]=Xg({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=Xg({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?PR(e.availability):void 0,union:d,encoding:a,source:e.source!=null?Emi(e.source):void 0}}}let u=[];for(let c of e.schemas)u.push(Xg({schema:c,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?Emi(e.source):void 0,inline:QSc(e,n)}}}var IBE=/^[0-9]/;function zBE(e){return IBE.test(e)}function fw_({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?fw_({context:t,schema:i.schema,namespace:r}):e}function xBE({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function QSc(e,t){return e.inline===!0||t>0?!0:void 0}function RBE(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return ZN.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return ZN.ObjectPropertyAccess.WriteOnly}}function dw_(e){let t=e.replace(/^x-|^X-/,"");return R_(t)}var pw_="BasicAuthScheme",Xnu="BearerAuthScheme";function _w_(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:pw_,schema:n}),t||(e.builder.setAuth(pw_),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:Xnu,schema:n}),t||(e.builder.setAuth(Xnu),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??dw_(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:Xnu,schema:n}),t||(e.builder.setAuth(Xnu),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(wy.of("__package__.yml"),{name:"OauthScope",schema:r5a(i.scopesEnum,0).schema})}}function tor({header:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=sq(n),u=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:R_(u);if(e.description==null&&e.name===c&&e.env==null&&e.availability==null)return a;let d={type:a};return c!==e.name&&(d.name=c),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=PR(e.availability)),d}function Znu({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return sq(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:sq(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=PR(e.availability)),a}function eau({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=JSc({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=sq(n.value),u=t5a(n.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let c={type:a};return u!=null&&(c.default=u),n.allowMultiple&&(c["allow-multiple"]=!0),e.description!=null&&(c.docs=e.description),e.parameterNameOverride!=null&&(c.name=e.parameterNameOverride),e.availability!=null&&(c.availability=PR(e.availability)),NBE(n.value)&&n.value.validation!==void 0&&(c.validation=n.value.validation),c.default==null&&c["allow-multiple"]==null&&c.docs==null&&c.name==null&&c.availability==null&&c.validation==null?a:c}function JSc({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:wy.of(SS),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[],u=!1;for(let[c,d]of Object.entries(n.value.schemas))d.type==="primitive"&&d.schema.type==="string"&&(u=!0),d.type==="literal"&&d.value.type==="string"&&(TJn.test(d.value.value)?a.push(d.value.value):a.push({value:d.value.value,name:CJn(d.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),u&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[c,d]=n.value.schemas;if(c!=null&&d!=null&&knu({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:d,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(c!=null&&d!=null&&knu({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[c,d]of Object.entries(n.value.schemas))return JSc({schema:d,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[],a=!1;for(let[u,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(a=!0),c.type==="literal"&&c.value.type==="string"&&(TJn.test(c.value.value)?n.push(c.value.value):n.push({value:c.value.value,name:CJn(c.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),a&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[u,c]=e.value.value.schemas;if(u!=null&&c!=null&&knu({array:u,primitive:c}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&c!=null&&knu({array:c,primitive:u}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1};for(let[u,c]of Object.entries(e.value.value.schemas))return JSc({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function knu({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function NBE(e){return e.type!=null}function hw_({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=FBE(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=LBE({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=_3i(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function FBE(e){let t={};return e.forEach(r=>{let i=_3i(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function LBE({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=_3i(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function _3i(e){switch(e.type){case"primitive":return yw_(e.value);case"object":return vw_(e.properties);case"array":return UBE(e.value);case"map":return VBE(e.value);case"oneOf":return WBE(e.value);case"enum":return e.value;case"literal":return HBE(e.value);case"unknown":return _3i(e.value);default:Ao(e)}}function yw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function vw_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,_3i(r)]))}function UBE(e){return e.map(t=>_3i(t))}function VBE(e){return Object.fromEntries(e.map(t=>[yw_(t.key),_3i(t.value)]))}function WBE(e){return e.type==="discriminated"?vw_(e.value):_3i(e.value)}function HBE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function Mmi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function tau(e,t){return t??(e?.groupName!=null?Mmi(e.groupName):void 0)}function bw_({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary),e.description!=null&&(i.docs=e.description);let n=Mmi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=Znu({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=eau({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let c={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=tor({header:d,context:t,fileContainingReference:r,namespace:n});c[d.name]=s}Object.keys(c).length>0&&(i.headers=c),t.builder.addChannel(r,{channel:i});for(let d of e.messages)t.builder.addChannelMessage(r,{messageId:d.name,message:{origin:d.origin,body:Xg({schema:d.body,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=hw_({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var Ami="Base",$BE="Default";function h3i(e){return Object.entries(e).reduce((t,[r,i])=>(zLn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function gw_(e){if(e.environmentOverrides!=null){for(let[g,O]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:g,schema:O});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let g of e.ir.servers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){r.push(O);continue}t[g.name]=O}let i={},n=[];for(let g of e.ir.endpoints)for(let O of g.servers){if(O.url==null)continue;let m=O.audiences?{url:O.url,audiences:O.audiences}:O.url;if(O.name==null){n.push(m);continue}i[O.name]=m}let a={},u=[];for(let g of e.ir.websocketServers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){u.push(O);continue}a[g.name]=O}let c=Object.keys(t).length,d=c>0,s=Object.keys(i).length>0,o=Object.keys(a).length>0;if(!d&&!s&&o&&e.ir.servers.length===0){for(let[g,O]of Object.entries(a))e.builder.addEnvironment({name:g,schema:O});e.builder.setDefaultEnvironment(Object.keys(a)[0]),e.builder.setDefaultUrl(Ami);return}if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),!d){let g=e.ir.servers[0]?.url,O=e.ir.servers[0]?.audiences;if(g!=null){let m=O?{url:g,audiences:O}:g;t[$BE]=m}}let l=Object.values(t).map(g=>typeof g=="string"?g:g.url),b=r.filter(g=>{let O=typeof g=="string"?g:g.url;return!l.includes(O)});if(b.length>0&&e.logger.error(`Skipping top level servers ${b.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),s)if(c===1){let g=Object.keys(t)[0],O=Object.values(t)[0],m=typeof O=="string"?O:O.url;e.builder.addEnvironment({name:g,schema:{urls:{[Ami]:m,...h3i(i),...h3i(a)}}}),e.builder.setDefaultEnvironment(g),e.builder.setDefaultUrl(Ami)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...h3i(i),...h3i(a)}}}),e.builder.setDefaultEnvironment(O),g=!1):e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...h3i(i),...h3i(a)}}});e.builder.setDefaultUrl(Ami)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(o?e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...h3i(a)}}}):e.builder.addEnvironment({name:O,schema:m}),e.builder.setDefaultEnvironment(O),g=!1):o?e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...h3i(a)}}}):e.builder.addEnvironment({name:O,schema:m});o&&e.builder.setDefaultUrl(Ami)}}function rau(e){return sq(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var KSc=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},GBE=.75,QBE=new Set("authorization");function Ow_(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?BJn(i.schema):void 0,u=a!=null?Mmi(a):void 0,c=wy.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?sq(Xg({schema:i.schema,context:e,fileContainingReference:u?GN(wy.of(R_(u)),c):c,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(QBE.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let c=t[a.name],d=tor({header:{...a,schema:c?.schema??a.schema,name:c?.name??a.name},fileContainingReference:wy.of(n6),context:e,namespace:void 0});u=new KSc(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*GBE;for(let[n,a]of Object.entries(r)){let u=t[n],c=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(c?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:rau(a.schema)}))}}}function mw_(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?BJn(t.schema):void 0,i=r!=null?Mmi(r):void 0,n=tor({header:{...t,schema:t.schema??Ov.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:xw.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:wy.of(n6),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:rau(n)})}}function IK(e){switch(e.type){case"primitive":return jw_(e.value);case"object":return ww_(e.properties);case"array":return Sw_(e.value);case"map":return KBE(e.value);case"oneOf":return YBE(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return XBE(e.value);case"unknown":return IK(e.value);default:Ao(e)}}function Pw_(e){switch(e.type){case"withStreaming":return e.sse?{stream:JBE(e.events)}:{stream:Sw_(e.events)};case"withoutStreaming":return{body:IK(e.value)};default:Ao(e)}}function jw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function ww_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,IK(r)]))}function JBE(e){return e.map(t=>({event:"",data:IK(t)}))}function Sw_(e){return e.map(t=>IK(t))}function KBE(e){return Object.fromEntries(e.map(t=>[jw_(t.key),IK(t.value)]))}function YBE(e){return e.type==="discriminated"?ww_(e.value):IK(e.value)}function XBE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function Dw_({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=ZBE(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=kBE(e.queryParameters));let i=e.headers!=null&&e.headers.length>0,n=t.builder.getGlobalHeaders(),a=Object.keys(n).length>0,u=new Set(e.headers?.map(c=>c.name)??[]);if(i||a){let c=[];if(e.headers!=null)for(let d of e.headers)d.name!==t.builder.getAuthHeaderName()&&c.push(d);for(let[d,s]of Object.entries(n))if(!u.has(d))if(s!=null&&typeof s=="object"&&s.type!=null){let o=b6({type:s.type,_default:void 0,validation:void 0,visitor:{primitive:l=>l.toString(),map:l=>l.toString(),list:l=>l,optional:l=>l,nullable:l=>l,set:l=>l,named:l=>l,literal:l=>{if(l.type==="string")return l.string;if(l.type==="boolean")return l.boolean.toString()},unknown:Ko}});o!=null&&c.push({name:d,value:Yg.literal(r3i.string(o))})}else c.push({name:d,value:Yg.primitive(D_.string(d))});r.headers=eIE({context:t,namedFullExamples:c})}return e.request!=null&&(r.request=IK(e.request)),e.response!=null&&(r.response=Pw_(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(c=>c.type==="language"?{name:c.name??void 0,docs:c.description??void 0,language:c.language,code:c.code,install:c.install??void 0}:{name:c.name??void 0,docs:c.description??void 0,sdk:c.sdk,code:c.code}).filter(yy)),r}function ZBE(e){let t={};return e.forEach(r=>{let i=IK(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function kBE(e){let t={};return e.forEach(r=>{let i=IK(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function eIE({context:e,namedFullExamples:t}){let r={};return t.forEach(i=>{let n=IK(i.value);n!=null&&(r[i.name]=n)}),r}function Ew_(e){return O$._visit(e,{get:()=>ZN.HttpMethodSchema.Get,post:()=>ZN.HttpMethodSchema.Post,put:()=>ZN.HttpMethodSchema.Put,patch:()=>ZN.HttpMethodSchema.Patch,delete:()=>ZN.HttpMethodSchema.Delete,head:()=>ZN.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function Mw_(e){return e==="POST"||e==="PUT"||e==="PATCH"}function Aw_({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,c=tau(e.sdkName,e.namespace),d={};for(let P of e.pathParameters)P.parameterNameOverride&&(u=u.replace(P.name,P.parameterNameOverride)),d[P.parameterNameOverride??P.name]=Znu({pathParameter:P,context:r,fileContainingReference:t,namespace:c}),a.add(P.name);let s={};for(let P of e.queryParameters){let D=eau({queryParameter:P,context:r,fileContainingReference:t,namespace:c});D!=null&&(s[P.name]=D,a.add(P.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:Ao(e.pagination)}let l={path:u,method:Ew_(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?Emi(e.source):void 0};!iIE({context:r,request:e.request})&&Object.keys(d).length>0&&(l["path-parameters"]=d),e.summary!=null&&(l["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=r.builder.getAuthHeaderName();O!=null&&g.add(O);let m=e.headers.filter(P=>!g.has(P.name));for(let P of m){let D=tor({header:P,context:r,fileContainingReference:t,namespace:c});b[P.name]=D,a.add(typeof D=="string"?P.name:D.name??P.name)}if(e.request!=null){r.setInState(v5.Request);let P=rIE({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:c});l.request=P.value,n=[...n,...P.schemaIdsToExclude??[]],r.unsetInState(v5.Request)}else{let P=r.inlinePathParameters&&Object.keys(d).length>0,D=Object.keys(s).length>0,A=Object.keys(b).length>0,M={};(P||D||A)&&(M.name=e.requestNameOverride??e.generatedRequestName),P&&(M["path-parameters"]=d),D&&(M["query-parameters"]=s),A&&(M.headers=b),Object.keys(M).length>0&&(l.request=M)}if(e.response!=null&&e.response._visit({json:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l.response={docs:P.description??void 0,type:sq(D)},P.statusCode!=null&&(l.response["status-code"]=P.statusCode),P.responseProperty!=null&&(l.response.property=P.responseProperty)},streamingJson:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:sq(D),format:"json"}},streamingSse:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:sq(D),format:"sse"}},file:P=>{l.response={docs:P.description??void 0,type:"file","status-code":P.statusCode}},bytes:P=>{l.response={docs:P.description??void 0,type:"bytes","status-code":P.statusCode}},streamingText:P=>{l["response-stream"]={docs:P.description??void 0,type:"text"}},text:P=>{l.response={docs:P.description??void 0,type:"text","status-code":P.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let P=r.getDefaultServerName(),D=e.servers[0];D==null?P!=null&&(l.url=P):l.url=D.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=PR(e.availability)),Object.entries(e.errors).forEach(([P,D])=>{let A=D.generatedName,M=wy.of(SS);r.builder.enableUniqueErrorsPerEndpoint&&(A=`${e.generatedRequestName}${D.generatedName}`,D.schema!=null&&(D.schema.type!=="reference"&&D.schema.type!=="oneOf"?D.schema.generatedName=`${e.generatedRequestName}${D.schema.generatedName}`:D.schema.type==="oneOf"&&(D.schema.value.generatedName=`${e.generatedRequestName}${D.schema.value.generatedName}`)));let E={"status-code":parseInt(P)},C=aw_({location:qw_,namespaceOverride:c});if(D.schema!=null){let I=Xg({schema:D.schema,context:r,fileContainingReference:C,declarationFile:C,namespace:c,declarationDepth:0});E.type=sq(I),E.docs=D.description}r.builder.addError(C,{name:A,schema:r.isErrorUnknownSchema(parseInt(P))?{...E,type:"unknown"}:E}),l.errors==null&&(l.errors=[]);let z=r.builder.addImport({file:t,fileToImport:C});l.errors.push(z!=null?`${z}.${A}`:A),E.type!=null&&D.examples?.forEach(I=>{let N={value:IK(I.example),name:I.name,docs:I.description};r.builder.addErrorExample(C,{name:A,example:N})})}),e.examples.length>0&&(l.examples=tIE({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[YSc,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:n}}function tIE({endpointExamples:e,context:t}){return e.map(r=>{try{return Dw_({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function rIE({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:c,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:l}){if(i.type==="json"||i.type==="formUrlEncoded"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,l):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=Xg({schema:i.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),M={schemaIdsToExclude:[],value:{body:A}},E=Object.keys(u??{}).length>0,C=Object.keys(c??{}).length>0,z=Object.keys(s??{}).length>0;return E&&(M.value["path-parameters"]=u),C&&(M.value["query-parameters"]=c),z&&(M.value.headers=s),(E||C||z)&&(M.value.name=n??a),i.contentType!=null&&(M.value["content-type"]=i.contentType),i.description!=null&&(M.value.docs=i.description),M}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(Mw_(e.method)&&A.readonly)).map(A=>{let M=Xg({schema:A.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:1}),E=A.nameOverride??A.key,C=PR(A.availability);if(!o.has(E)&&A.audiences.length<=0)return o.add(E),A.nameOverride!=null?[A.key,{type:sq(M),docs:IJn(M),name:A.nameOverride,availability:C}]:[A.key,C?{...typeof M=="string"?{type:M}:M,availability:C}:M];let z={type:sq(M),docs:IJn(M)};return o.has(E)&&(z.name=A.generatedName),A.audiences.length>0&&(z.audiences=A.audiences),C!=null&&(z.availability=C),o.add(E),[A.key,z]})),m=g.allOf.map(A=>{let M=Xg({schema:Ov.reference(A),fileContainingReference:t,context:r,namespace:l,declarationDepth:0});return sq(M)}).filter(A=>A!=="unknown"),P={properties:O};m.length>0&&(P.extends=m),i.additionalProperties&&(P["extra-properties"]=!0);let D={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":c,headers:s,body:P};return i.contentType!=null&&(D["content-type"]=i.contentType),i.description!=null&&(D.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:D}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":i.contentType??Iq.APPLICATION_OCTET_STREAM,"query-parameters":c,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let P=g.contentType.split(",")[0];m["content-type"]=P}return[g.key,m]}return[g.key,O]}else{let O=Xg({schema:g.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(g.contentType||g.exploded||g.encoding){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.encoding==="json"?m.style="json":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":c,headers:s,body:{properties:b},"content-type":Iq.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Ao(i)}}function iIE({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Ao(t)}}function nIE({location:e,namespaceOverride:t}){return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function aIE(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:wy.of(`${R_(r)}.yml`),endpointId:e.summary!=null?R_(e.summary):R_(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:wy.of(SS),endpointId:R_(e.summary)}:{file:wy.of(SS),endpointId:R_(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:wy.of(SS),endpointId:i};let n=i5a(r),a=i5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=sIE({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let c=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])c.push(s);else{let o=R_(r);return{file:wy.of(`${o}.yml`),endpointId:i,tag:r}}}if(c.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:wy.of(R_(c.join("_"))+".yml"),endpointId:R_(a.slice(c.length).join("_")),tag:r}}function n5a(e){let t=e.tags[0];if(e.sdkName!=null){let r=ISc({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:wy.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return nIE({namespaceOverride:e.namespace,location:aIE(e)})}function i5a(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=j3e(t),t}var oIE=new RegExp("[^a-zA-Z0-9{}]+"),uIE=new RegExp("[{}]","g");function sIE({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(oIE).join("_").replaceAll(uIE,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:wy.of(R_(t)+".yml"),endpointId:R_(e.slice(0,-1*a.length)),tag:t}}function Tw_(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:c,tag:d}=n5a(a),s=c.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,P=g[m];if(P==null)break;if(P.summary!=null||P.description!=null){o=g[m];break}}}let l=d==null?void 0:i.tagsById[d];e.setInState(v5.Endpoint),e.setEndpointMethod(a.method);let b=Aw_({context:e,endpoint:a,declarationFile:c});e.unsetEndpointMethod(),e.unsetInState(v5.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(c,{name:u,schema:b.value,source:a.source!=null?Emi(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(c,{"display-name":o?.summary??l?.id,docs:o?.description??l?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function Cw_(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?Mmi(r.groupName):void 0,n=Xg({schema:Ov.primitive(r),context:e,fileContainingReference:wy.of(SS),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:sq(n),docs:r.description??void 0}})}}function Bw_(e){for(let t of e.ir.webhooks){let r=fIE({webhook:t,context:e});if(r==null)continue;let i=tau(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=tor({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:n,payload:Xg({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:IK(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function cIE({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function lIE({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:wy.of(SS),endpointId:i};let n=i5a(r),a=i5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=[];for(let c=0;c<n.length;++c){let d=n[c];if(d!=null&&d===a[c])u.push(d);else{let s=R_(r);return{file:wy.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:wy.of(R_(u.join("_"))+".yml"),endpointId:R_(a.slice(u.length).join("_")),tag:r}}function fIE({webhook:e,context:t}){return e.sdkName!=null?{file:nw_({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:cIE({namespaceOverride:e.namespace,location:lIE({webhook:e,context:t})})}var dIE=wy.of(SS);function zw_(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return Iw_({namespace:e.namespace,groupName:e.groupName});case"oneOf":return Iw_({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return dIE;default:Ao(e)}}function Iw_({namespace:e,groupName:t}){return e!=null&&t!=null?p3i([{type:"namespace",name:e},...t]):e!=null?p3i([{type:"namespace",name:e}]):p3i(t)}var YSc="external",qw_=wy.of(SS);function xw_({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=zw_(a),c=cw_({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(ZIi(c.schema)){let d=sq(c.schema);if(d===(c.name??n)||d===`optional<${c.name??n}>`||d===`optional<nullable<${c.name??n}>>`)continue}i.builder.addType(u,{name:c.name??n,schema:c.schema})}}function Rw_(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),gw_(e),Ow_(e),mw_(e),_w_(e),Cw_(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(YSc);let t=Tw_(e),r=t.sdkGroups;e.setInState(v5.Webhook),Bw_(e),e.unsetInState(v5.Webhook),e.setInState(v5.Channel);for(let n of Object.values(e.ir.channels)){let a=p3i(n.groupName);bw_({channel:n,context:e,declarationFile:a})}e.unsetInState(v5.Channel);let i=pIE({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});xw_({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))xw_({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function pIE({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}var a5a=class{context;constructor(t){this.context=t}};var iau=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,c]of Object.entries(i.files)){let d=n!=null?wy.of(`${n}${"/"}${u}`):wy.of(u);t[d]=c}let a=Object.keys(i.directories).sort();for(let u of a){let c=n!=null?`${n}${"/"}${u}`:u,d=i.directories[u];r(d,c)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[wy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var ynn=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new iau,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return sir(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))Nw_(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(Nw_(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??R_((x3e(r)+"/"+VZi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===wy.of(n6))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=tBo(x3e(Q8n.of(`/${t}`)),Q8n.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=tBo(x3e(Q8n.of(`/${t}`)),Q8n.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===wy.of(n6))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(c=>W8(c,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=GN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:GN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:GN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===SS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function Nw_(e){return e?.header!=null}var nau=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.useBytesForBinaryResponse=i?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=i?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new ynn(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let c={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let l=parseInt(s),b=c[l];b==null&&o.schema!=null?c[l]=o.schema:b!=null&&o.schema!=null&&Iue(b,o.schema)||this.unknownSchema.add(l)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(v5.Channel,v5.Endpoint,v5.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ao(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Ao(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function XSc(e){let t=new nau(e);return Rw_(t)}var aau=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=XSc({taskContext:t,ir:r,options:K8a({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:i?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums}}),authOverrides:i?.auth!=null?{auth:i.auth}:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:xd.dump(a.rootApiFile)},namedDefinitionFiles:{...Sd(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(u),contents:u})),[wy.of(SS)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var o5a=class extends DQt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;inlineAllOfSchemas;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.inlineAllOfSchemas=t.inlineAllOfSchemas,this.converter=new aau(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new Eqe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};var m$={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var zJn={of(e){return e}};var Fw_={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},ZSc={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:Fw_,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},ad={SOURCE:zJn.of("source"),SDK_NAMESPACE:zJn.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:zJn.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:zJn.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:zJn.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport",IS_DISCRIMINATED:"x-fern-discriminated"};var _7={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json",useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,additionalPropertiesDefaultsTo:!1,typeDatesAsStrings:!0,preserveSingleSchemaOneOf:!1,inlineAllOfSchemas:!1};function qQt({options:e,overrides:t}){return{disableExamples:t?.disableExamples??_7.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??_7.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??_7.useTitlesAsName,audiences:t?.audiences??e?.audiences??_7.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??_7.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??_7.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??_7.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??_7.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??_7.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??_7.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??_7.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??_7.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??_7.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??_7.objectQueryParameters,filter:t?.filter??e?.filter??_7.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??_7.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??_7.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??_7.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??_7.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??_7.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??_7.preserveSingleSchemaOneOf,inlineAllOfSchemas:t?.inlineAllOfSchemas??e?.inlineAllOfSchemas??_7.inlineAllOfSchemas}}var Lw_={naming:"v1"};function hf(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function u5a(e,t,r,i,n=[]){try{let a=hf(e,t);if(a!=null)return r.parse(a)}catch{let u=j3e(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function vnn(e){let t=hf(e,"examples");if(t!=null){if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null)return Object.values(t).map(r=>typeof r=="object"&&r!==null&&"value"in r?r.value:r)}return[]}function Uw_({schema:e,logger:t}){return hf(e,ad.ENCODING)??void 0}function Vw_(e){return hf(e,ad.FERN_ENUM)}function Ww_({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=hf(i,ad.SDK_NAMESPACE),c=hf(i,ad.SDK_GROUP_NAME),d=hf(i,ad.TYPE_DEFINITION);if(d!=null)return s5a({fernType:d,nameOverride:e,generatedName:t,title:r,description:n,availability:a,namespace:u,groupName:typeof c=="string"?[c]:c})}function s5a({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c}){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>{switch(d.v1){case"BASE_64":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.base64({example:void 0})});case"BOOLEAN":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.boolean({default:void 0,example:void 0})});case"DATE":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.date({example:void 0})});case"DATE_TIME":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.datetime({example:void 0})});case"FLOAT":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.float({example:void 0})});case"DOUBLE":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint({default:void 0,example:void 0})});case"INTEGER":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint64({default:void 0,example:void 0})});case"LONG":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Ao(d.v1)}},unknown:()=>Nl.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,namespace:u,groupName:c}),map:({keyType:d,valueType:s})=>d?.type==="primitive"&&s!=null?Nl.map({nameOverride:t,generatedName:r,title:i,key:d,value:s,description:n,availability:a,namespace:u,groupName:c,encoding:void 0,example:void 0,inline:void 0}):void 0,list:d=>d!=null?Nl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,optional:d=>d!=null?Nl.optional({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,nullable:d=>d!=null?Nl.nullable({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,set:d=>d!=null?Nl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,literal:d=>Nl.literal({nameOverride:t,generatedName:r,title:i,value:d._visit({string:s=>_x.string(s),boolean:s=>_x.boolean(s),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,namespace:u,groupName:c}),named:d=>Nl.reference({schema:d,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,source:TK.openapi({file:"<memory>"})})}})}function Hw_(e){let t=hf(e,ad.SOURCE);if(t!=null)return t.endsWith(".proto")?TK.protobuf({file:t}):TK.openapi({file:t})}function bnn(e){if(e!=null&&typeof e=="boolean")return e}function ep(e){return e?.$ref!=null}function $w_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,encoding:b,source:g}){return n===void 0&&(n=d.options.additionalPropertiesDefaultsTo),typeof n=="boolean"||xJn(n,d.options)?oau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Nl.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}),namespace:s,groupName:o,example:l,encoding:b}):oau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Gw_(n0(n,d.options.optionalAdditionalProperties?c:!1,d,[...i,"Value"],g,s,void 0,void 0,void 0)),namespace:s,groupName:o,example:l,encoding:b})}function Gw_(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=Gw_(e.value);break;case"oneOf":e.value.inline=!0;break;default:Ao(e)}return e}function oau({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:c,namespace:d,groupName:s,example:o,encoding:l}){return a?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0}),description:u,availability:c,namespace:d,groupName:s,inline:void 0}):Nl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:c,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0})}function xJn(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!ep(e)&&Object.keys(e).length===0}function Qw_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,source:b}){let g=n==null?Nl.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:o}):n0(n,!1,d,[...i,"Item"],b,s);return _IE({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:o,itemSchema:g,wrapAsNullable:c,description:a,availability:u,example:l})}function _IE({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,example:s}){return n?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):Nl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0})}function zK(e){switch(hf(e,ad.AVAILABILITY)){case"deprecated":return b$.Deprecated;case"beta":return b$.Beta;case"generally-available":return b$.GenerallyAvailable;default:break}if(!ep(e)&&e.deprecated)return b$.Deprecated}function kSc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminator:s,context:o,namespace:l,groupName:b,encoding:g,source:O}){let m=s.propertyName,P=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,M])=>{let E=qmi({$ref:M},!1,o,[M],g,O,l);return o.markReferencedByDiscriminatedUnion({$ref:M},m,1),[A,E]})),D=Object.entries(n).filter(([A])=>A!==m).map(([A,M])=>{let E=c!=null&&c.includes(A),C=n0(M,!E,o,[...i,A],O,l);return{key:A,schema:C}});return Jw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:m,subtypes:P,namespace:l,groupName:b,source:O})}function eDc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminant:s,variants:o,context:l,namespace:b,groupName:g,encoding:O,source:m}){let P=Object.fromEntries(Object.entries(o).map(([A,M])=>{if(ep(M)){let E=qmi(M,!1,l,[M.$ref],O,m,b);return l.markReferencedByDiscriminatedUnion(M,s,1),[A,E]}else{let E=RJn(M,!1,l,[...i,A],O,m,b,new Set([s]));return[A,E]}})),D=Object.entries(n).filter(([A])=>A!==s).map(([A,M])=>{let E=c!=null&&c.includes(A),C=n0(M,!E,l,[...i,A],m,b);return{key:A,schema:C}});return Jw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:s,subtypes:P,namespace:b,groupName:g,source:m})}function Jw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:c,subtypes:d,namespace:s,groupName:o,source:l}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.oneOf(Cee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0})),namespace:s,groupName:o,description:a,availability:u,inline:void 0}):Nl.oneOf(Cee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0}))}function Kw_(e){if(e.proto!=null)return iJn.protobuf({typeName:e.proto.type})}function y3i({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:c,availability:d,wrapAsNullable:s,namespace:o,groupName:l,context:b,source:g,inline:O}){let m=yIE(n??[]),P=new Set(a),D=Array.from(P).map((M,E)=>{let C=i?.[M],z=m[E],G=TJn.test(M),I=C?.name??z,N=G?M:CJn(M);return I!=null&&!TJn.test(I)&&(b?.logger.warn(`Enum name override ${I} is not a valid name. Falling back on ${N}.`),I=void 0),{nameOverride:I,generatedName:N,value:M,description:C?.description,availability:d,casing:{snake:C?.casing?.snake??void 0,pascal:C?.casing?.pascal??void 0,screamingSnake:C?.casing?.screamingSnake??void 0,camel:C?.casing?.camel??void 0}}}),A=u!=null?D.find(M=>M.value===u):void 0;return hIE({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:D,_default:A,description:c,availability:d,namespace:o,groupName:l,source:g,inline:O})}function hIE({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:c,namespace:d,groupName:s,source:o,inline:l}){return e?Nl.nullable({nameOverride:t,generatedName:r,title:i,value:Nl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:c,example:void 0,namespace:d,groupName:s,source:o,inline:l}),description:u,availability:c,namespace:d,groupName:s,inline:l}):Nl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:c,default:a,example:void 0,namespace:d,groupName:s,source:o,inline:l})}function yIE(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function Yw_({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m})}function Xw_(e){return typeof e=="string"?_x.string(e):typeof e=="boolean"?_x.boolean(e):_x.string(`${e}`)}function Zw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,namespace:c,groupName:d}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.literal({nameOverride:e,generatedName:t,title:r,value:Xw_(n),description:a,availability:u,namespace:c,groupName:d}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):Nl.literal({nameOverride:e,generatedName:t,title:r,value:Xw_(n),description:a,availability:u,namespace:c,groupName:d})}function tDc({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==null||i==="double"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.double({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="float"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="int32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="time-delta"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m})}var vIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},bIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},gIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},OIE={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},mIE={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},PIE={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},jIE={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},wIE={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function uau(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[vIE,bIE,gIE,OIE,mIE,PIE,jIE,wIE],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:c}=a.applyStrategy(t);t=u,r=[...r,...c]}}while(t.join("")!==n.join(""));return r}function g5(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:QB(R_(n))).join("");return/^\d/.test(i)?e5a(i)??i:i}function rDc(e){let t=e.join("_");return R_(t)}function bA(e){switch(e.type){case"object":return Ov.object({allOf:e.allOf,properties:e.properties.map(t=>DIE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return Ov.array({description:e.description,availability:e.availability,value:bA(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return Ov.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return Ov.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"nullable":return Ov.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return Ov.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return Ov.primitive({description:e.description,availability:e.availability,schema:kw_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Ov.map({description:e.description,availability:e.availability,key:Ov.primitive({description:e.key.description,availability:e.key.availability,schema:kw_(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:bA(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return Ov.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Ov.oneOf(SIE(e.value));case"unknown":return Ov.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Ao(e)}}function SIE(e){switch(e.type){case"discriminated":return Dmi.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:bA(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,bA(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return Dmi.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>bA(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Ao(e)}}function kw_(e){switch(e.type){case"string":return xw.string(e);case"base64":return xw.base64();case"boolean":return xw.boolean(e);case"date":return xw.date();case"datetime":return xw.datetime();case"double":return xw.double(e);case"float":return xw.float();case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();default:Ao(e)}}function DIE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:bA(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function sau(e,t){return Iue(bA(e),bA(t))}function e1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:c,allOf:d,context:s,propertiesToExclude:o,namespace:l,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:P}){let D=[...u??[]],A={...n},M=[],E=[];for(let N of d)if(!s.options.inlineAllOfSchemas&&ep(N)){let U=s.resolveSchemaReference(N);if(U.discriminator!=null&&U.discriminator.mapping!=null)continue;if(U.oneOf!=null||U.anyOf!=null){let J=U.oneOf??U.anyOf;if(J!=null){for(let X of J){let oe=ep(X)?s.resolveSchemaReference(X):X,pe=n0(oe,!1,s.DUMMY,i,P,l);pe.type==="object"&&M.push(...pe.properties.map(de=>de.schema.type!=="optional"&&de.schema.type!=="nullable"?{...de,schema:Nl.optional({nameOverride:void 0,generatedName:"",title:void 0,value:de.schema,description:void 0,availability:de.availability,namespace:void 0,groupName:void 0,inline:void 0})}:de))}continue}}let Y=v3i(N);if(Y==null)continue;E.push({schemaId:Y,convertedSchema:iDc(N,[Y],P,s.options.preserveSchemaIds),properties:t1_({schema:N,context:s,breadcrumbs:i,source:P,namespace:l})}),s.markSchemaAsReferencedByNonRequest(Y)}else if(ep(N)){let U=s.resolveSchemaReference(N),Y=n0(U,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}else{let U=N.required??[];M=M.map(J=>(J.schema.type==="optional"||J.schema.type==="nullable")&&U.includes(J.key)?{...J,schema:J.schema.value}:J);let Y=n0(N,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}let C={};for(let N of E)for(let[U,Y]of Object.entries(N.properties)){let J=C[U];J!=null?(J.schemaIds.push(N.schemaId),J.schemas.some(oe=>sau(oe,Y))||J.schemas.push(Y)):C[U]={schemaIds:[N.schemaId],schemas:[Y]}}let z=[];for(let[N,U]of Object.entries(C))U.schemaIds.length>1&&z.push({propertyKey:N,allOfSchemaIds:U.schemaIds,conflictingTypeSignatures:U.schemas.length>1});let G=Object.fromEntries(Object.entries(A).filter(([N,U])=>!(!ep(U)&&U.type==="null"))),I=Object.entries(G).map(([N,U])=>{let Y=hf(U,ad.AUDIENCES)??[],J=zK(U),X=ep(U)?!1:U.readOnly,oe=ep(U)?!1:U.writeOnly,pe=D.includes(N)&&!X,de=hf(U,ad.FERN_PROPERTY_NAME),me=[...i,N],Le=rDc(me),yt=pe?n0(U,!1,s,me,P,l):Nl.optional({nameOverride:e,generatedName:Le,title:r,description:void 0,availability:J,value:n0(U,!1,s,me,P,l),namespace:l,groupName:b,inline:void 0}),De={};for(let Ae of E){let Ct=Ae.properties[N];Ct!=null&&!sau(yt,Ct)?De[Ae.schemaId]={differentSchema:!0}:Ct!=null&&(De[Ae.schemaId]={differentSchema:!1})}return{key:N,schema:yt,nameOverride:de,audiences:Y,conflict:De,generatedName:rDc([...i,N]),availability:J,readonly:X,writeonly:oe}});return I.push(...M.map(N=>{let U=N.conflict;for(let Y of E){let J=Y.properties[N.key];J!=null&&!sau(N.schema,J)?U[Y.schemaId]={differentSchema:!0}:J!=null&&(U[Y.schemaId]={differentSchema:!1})}return{...N,conflict:U}})),EIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,properties:I.filter(N=>!o.has(N.key)),description:a,allOf:E.map(N=>N.convertedSchema),allOfPropertyConflicts:z,namespace:l,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:P,context:s})}function EIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:l,availability:b,source:g,context:O}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:xJn(l,O.options),availability:void 0,source:g,inline:void 0}),description:a,availability:b,namespace:d,groupName:s,inline:void 0}):Nl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:xJn(l,O.options),availability:b,source:g,inline:void 0})}function t1_({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,c]=ep(e)?[t.resolveSchemaReference(e),uau(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...t1_({schema:d,context:t,breadcrumbs:c,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=n0(s,!1,t,[...c,d],i,n);a[d]=o}return a}function b3i({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:c,subtypes:d,namespace:s,groupName:o,encoding:l,source:b,subtypePrefixOverrides:g}){let O=qIE({schemas:d}),m=d.flatMap((D,A)=>{if(!ep(D)&&D.enum!=null&&c.options.coerceEnumsToLiterals&&D.type==="string")return D.enum.map(E=>Nl.literal({nameOverride:void 0,generatedName:g5([t,E],c.options.preserveSchemaIds),title:void 0,value:_x.string(String(E)),namespace:s,groupName:void 0,description:void 0,availability:E.availability}));let M=O[A];if(g!=null){let E=g[A];E!=null&&"name"in E&&(M=E.name)}return[n0(D,!1,c,[...i,M??`${A}`],b,s)]}),P=MIE(m);return AIE({uniqueSubtypes:P,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,namespace:s,groupName:o,context:c,encoding:l,source:b})}function MIE(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&Iue(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function AIE({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,context:s,encoding:o,source:l}){if(Object.entries(e).every(([g,O])=>O.type==="literal")){let g={},O=[];return Object.entries(e).forEach(([m,P])=>{P.type==="literal"&&P.value.type==="string"&&(O.push(P.value.value),P.description!=null&&(g[P.value.value]={description:P.description}))}),y3i({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:g,enumVarNames:void 0,enumValues:O,_default:void 0,namespace:c,groupName:d,context:s,source:l,inline:void 0})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:r1_({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,namespace:c,groupName:d,encoding:o,source:l})}function nDc({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,namespace:c,groupName:d,discriminator:s,encoding:o,source:l}){let b=Object.entries(s.mapping??{}).map(([m,P],D)=>{let A={$ref:P},M=qmi(A,!1,u,[P],o,l,c);return u.markSchemaWithDiscriminantValue(A,s.propertyName,m),M.type==="object"&&(M.properties={[s.propertyName]:Nl.literal({nameOverride:void 0,generatedName:g5([t,m],u.options.preserveSchemaIds),title:void 0,value:_x.string(m),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...M.properties.filter(E=>E.key!==s.propertyName)}),M}),g=[];for(let m=0;m<b.length;++m){let P=b[m],D=!1;for(let A=m+1;A<b.length;++A){let M=b[A];if(P!=null&&M!=null&&Iue(P,M)){D=!0;break}}P!=null&&!D&&g.push(P)}if(Object.entries(g).every(([m,P])=>P.type==="literal")){let m={},P=[];return Object.entries(g).forEach(([D,A])=>{A.type==="literal"&&A.value.type==="string"&&(P.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),y3i({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:P,_default:void 0,namespace:c,groupName:d,context:u,source:l,inline:void 0})}return g.length===1&&g[0]!=null&&!u.options.preserveSingleSchemaOneOf?g[0]:r1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,namespace:c,groupName:d,encoding:o,source:l})}function qIE({schemas:e}){let t={},r=0;for(let a of e){if(!ep(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),c={},d=u;for(let[s,o]of Object.entries(t)){let l=nAo(o,u);d=nAo(d,o),c[s]=l}c[r]=d,t=c}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let c=u.sort();if(c[0]!=null){i.push(c[0]),++n;continue}}ep(a)?i.push(d3i(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(d3i(n)??`${n}`),++n}return i}function r1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,namespace:c,groupName:d,encoding:s,source:o}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.oneOf(Cee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0})),description:n,availability:a,namespace:c,groupName:d,inline:void 0}):Nl.oneOf(Cee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0}))}function NJn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function cau({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=vnn(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function i1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=vnn(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function ror({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=vnn(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function n1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=vnn(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var gnn="#/components/schemas/";function n0(e,t,r,i,n,a,u=!1,c=new Set,d){let s=Hw_(e)??n,o=NIE({schema:e,logger:r.logger});if(ep(e)){let l=v3i(e);return l!=null?(u?r.markSchemaAsReferencedByRequest(l):r.markSchemaAsReferencedByNonRequest(l),qmi(e,t,r,i,o,s,a)):RJn(r.resolveSchemaReference(e),t,r,uau(e.$ref),o,s,a,c,u,d)}return RJn(e,t,r,i,o,s,a,c,u,d)}function qmi(e,t,r,i,n,a,u){let c=e.$ref.includes("properties")?RJn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Nl.reference(iDc(e,i,a,r.options.preserveSchemaIds));return t?Nl.nullable({title:void 0,nameOverride:void 0,generatedName:g5(i,r.options.preserveSchemaIds),value:c,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0}):c}function TIE(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function RJn(e,t,r,i,n,a,u,c=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=hf(e,ad.TYPE_NAME)??(r.options.useTitlesAsName?TIE(e.title):void 0),l=hf(e,ad.SDK_GROUP_NAME)??hf(e,m$.TAGS)?.[0],b=(typeof l=="string"?[l]:l)??[];b=r.resolveGroupName(b);let g=g5(i,r.options.preserveSchemaIds),O=e.title,m=e.description,P=zK(e),D=[];e.example!=null&&D.push({name:void 0,value:e.example,description:void 0});let A=hf(e,m$.EXAMPLES);A!=null&&Object.keys(A).length>0&&D.push(...Object.entries(A).map(([z,G])=>({name:G?.summary??z,value:G.value,description:G.description})));let M=vnn(e);M!=null&&Object.keys(M).length>0&&D.push(...M.map(z=>({name:void 0,value:z,description:void 0})));let E=Ww_({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:P});if(E!=null)return E;if(Array.isArray(e.type)){let z=e.type.indexOf("null"),G=z!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&G)e.type.splice(z,1),e.type=e.type[0],e.nullable=!0;else if(G&&(e.type.splice(z,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let I=new Set([...e.oneOf,...e.type]);e.oneOf=[...I]}}if(!t&&e.nullable===!0)return RJn(e,!0,r,i,n,a,u,c,d,s);if("const"in e&&(e.enum=[e.const]),e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(!dau(e.enum))return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:NJn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:P});let z=Vw_(e);return e.enum.length===1&&e.enum[0]!=null&&z==null?Zw_({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:P,namespace:u,groupName:b}):y3i({nameOverride:o,generatedName:g,title:O,fernEnum:z,enumVarNames:hf(e,[m$.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0})}if(dau(e.type)&&e.type.length>1){let z=e.type.includes("null"),G=e.type.filter(I=>I!=="null").map(I=>({type:I,nullable:z}));return b3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:G,namespace:u,groupName:b,encoding:n,source:a})}if(e.type==="boolean"){let z=hf(e,ad.BOOLEAN_LITERAL);return z!=null?a1_({nameOverride:o,generatedName:g,title:O,literal:_x.boolean(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.boolean({default:CIE(e.default),example:i1_({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b})}if(e.type==="number")return tDc({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:bnn(e.exclusiveMinimum),exclusiveMaximum:bnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:cau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="integer")return Yw_({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:bnn(e.exclusiveMinimum),exclusiveMaximum:bnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:cau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="float")return tDc({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:bnn(e.exclusiveMinimum),exclusiveMaximum:bnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:cau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="string"){if(e.format==="date-time")return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.datetime({example:ror({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b});if(e.format==="date"&&r.options.typeDatesAsStrings===!1)return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.date({example:ror({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b});if(e.format==="json-string")return Nl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:b,example:void 0});let z=s1_(e,"const");return z!=null?a1_({nameOverride:o,generatedName:g,title:O,literal:_x.string(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:NJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:P})}if(e.type==="array")return Qw_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,example:n1_({schema:e,logger:r.logger,fallback:s}),source:a});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&lau(e))return $w_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,example:e.example,source:a});if(e.oneOf!=null&&e.oneOf.length>0&&hf(e,ad.IS_DISCRIMINATED)===!1)return b3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf,namespace:u,groupName:b,encoding:n,source:a});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?nDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):kSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf!=null&&e.oneOf.length>0){let z=hf(e,ad.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||z?nDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):kSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(r.options.preserveSingleSchemaOneOf)return b3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:b,source:a});let G=n0(e.oneOf[0],t,r,i,a,u,d);return FJn(G,m,u,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let U=e.oneOf[0],Y=e.oneOf[1];if(!ep(U)&&U.type==="null")return n0(Y,!0,r,i,a,u);if(!ep(Y)&&Y.type==="null")return n0(U,!0,r,i,a,u)}let G=zIE({schemas:e.oneOf});if(G!=null)return y3i({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:G,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0});let I=o1_({schemas:e.oneOf,context:r});if(I!=null&&!r.options.discriminatedUnionV2&&!z)return eDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:I.discriminant,variants:I.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let N=e.oneOf.filter(U=>!ep(U)&&U.type==="null").length>0;return b3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||N,context:r,subtypes:e.oneOf.filter(U=>ep(U)||U.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let I=n0(e.anyOf[0],t,r,i,a,u,d);return FJn(I,m,u,b)}if(e.anyOf.length===2){let[I,N]=e.anyOf;if(I!=null&&N!=null){if(!ep(I)&&I.type==="null"){let U=n0(N,!0,r,i,a,u);return FJn(U,m,u,b)}else if(!ep(N)&&N.type==="null"){let U=n0(I,!0,r,i,a,u);return FJn(U,m,u,b)}}}let z=o1_({schemas:e.anyOf,context:r});if(z!=null&&!r.options.discriminatedUnionV2)return eDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:z.discriminant,variants:z.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let G=e.anyOf.filter(I=>!ep(I)&&I.type==="null").length>0;return b3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||G,context:r,subtypes:e.anyOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}if(e.allOf!=null||e.properties!=null){let z=[];for(let I of e.allOf??[])(ep(I)||Object.keys(I).length>0)&&z.push(I);if((e.properties==null||lau(e))&&z.length===1&&z[0]!=null){let I=n0(z[0],t,r,i,a,u,d);return FJn(I,m,u,b)}let G=z.filter(I=>{let N=fau(I);return N||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(I)}`),N});if((e.properties==null||lau(e))&&G.length===1&&G[0]!=null){let I=n0(G[0],t,r,i,a,u,d);return FJn(I,m,u,b)}return e1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:G,context:r,propertiesToExclude:c,namespace:u,groupName:b,fullExamples:D,additionalProperties:e.additionalProperties,availability:P,encoding:n,source:a})}if(e.type==="object"&&BIE(e)&&IIE(e)&&lau(e))return oau({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:NJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b},valueSchema:Nl.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:u,groupName:b}),namespace:u,groupName:b,encoding:n,example:e.example});e.type!=null&&r.logger.warn(`Failed to parse an OpenAPI schema at the following location: ${i.join("->")}. Coercing to unknown.`);let C=e.example??e.default;return Nl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:b,example:C})}function CIE(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function v3i(e){if(e.$ref.startsWith(gnn))return e.$ref.replace(gnn,"")}function iDc(e,t,r,i){let n=hf(e,ad.TYPE_NAME),a=g5(t,i),u=e.description,c=zK(e),d=v3i(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return Ov.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:c,namespace:void 0,groupName:void 0,source:r})}function BIE(e){return e.oneOf==null||e.oneOf.length===0}function IIE(e){return e.allOf==null||e.allOf.length===0}function lau(e){return e.properties==null||zq(e.properties)===0}function dau(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function FJn(e,t,r,i){return e.type==="reference"?Nl.reference({...e,description:t,availability:e.availability,namespace:r,groupName:i}):e.type==="optional"?Nl.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e.type==="nullable"?Nl.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e}function fau(e){return ep(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>fau(t)):e.oneOf!=null?e.oneOf.every(t=>fau(t)):e.anyOf!=null?e.anyOf.every(t=>fau(t)):!1}function a1_({literal:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,nameOverride:u,generatedName:c,title:d}){return t?Nl.nullable({nameOverride:u,generatedName:c,title:d,value:Nl.literal({nameOverride:u,generatedName:c,title:d,value:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Nl.literal({nameOverride:u,generatedName:c,title:d,value:e,namespace:r,groupName:i,description:n,availability:a})}function b5({primitive:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,generatedName:u,nameOverride:c,title:d}){return i=typeof i=="string"?[i]:i,t?Nl.nullable({nameOverride:c,generatedName:u,title:d,value:Nl.primitive({nameOverride:c,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Nl.primitive({nameOverride:c,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i})}function zIE({schemas:e}){let t=new Set;for(let r of e){if(ep(r))return;if(r.enum!=null&&dau(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function o1_({schemas:e,context:t}){let r={};for(let i of e){let n=u1_({schema:i,context:t});for(let[a,u]of Object.entries(n)){let c=r[a];c!=null?c[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function u1_({schema:e,context:t}){let r=ep(e)?t.resolveSchemaReference(e):e;return xIE({schema:r,context:t})}function xIE({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=u1_({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=ep(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&dau(a.enum)&&RIE(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=s1_(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function RIE(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function s1_(e,t){let r=e[t];if(r!=null)return r}function NIE({schema:e,logger:t}){let r=Uw_({schema:e,logger:t});if(r!=null)return Kw_(r)}var LJn=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(gnn))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(gnn.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,c]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(ep(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&c!=null){let s=d.properties?.[c];if(s==null)throw new Error(`Property "${c}" not found on "${a}". Full ref: ${t.$ref}`);ep(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var pau=class extends LJn{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",i=this.document.components;if(i==null||i.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let n=t.$ref.substring(r.length),a=i.messages[n];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function UJn(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let i={};for(let[n,a]of Object.entries(t))switch(a.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(a.namespace==null){r[n]=a;continue}let u=a.namespace;i[u]??={},i[u][n]=a;continue}case"oneOf":case"unknown":r[n]=a;continue;default:Ao(a)}return{rootSchemas:r,namespacedSchemas:i}}function g3i(e){if(typeof e=="string")return Yg.primitive(D_.string(e));if(typeof e=="number")return Number.isInteger(e)?Yg.primitive(D_.int(e)):Yg.primitive(D_.double(e));if(typeof e=="boolean")return Yg.primitive(D_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>g3i(r));return t.length===0?void 0:Yg.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=g3i(i);n!=null&&t.push({key:D_.string(r),value:n})}return Yg.map(t)}}function c5a(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function c1_(e){if(e!=null&&Array.isArray(e))return e}var O3i=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:c}){switch(i.type){case"enum":return typeof r=="string"&&l1_({schema:i,value:r})?Yg.enum(r):i.values[0]!=null?Yg.enum(i.values[0]?.value):void 0;case"literal":return Yg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:c});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:c});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return Yg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?c:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},l=c5a(r),b=l?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,l);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let P of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=Yg.primitive(D_.string(b));break}else{let D=this.buildExampleHelper({exampleId:t,schema:P[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:c});if(D!=null){this.mergeExampleWith(D,d),d[i.value.discriminantProperty]=Yg.primitive(D_.string(P[0]));break}}for(let P of i.value.commonProperties){s[P.key]={schema:P.schema,readonly:!1};let D=this.getResolvedSchema(P.schema);D.type!=="optional"&&D.type!=="nullable"&&(o[P.key]=P.schema)}for(let[P,D]of Object.entries(s)){let A=P in o;if(A&&l?.[P]!=null){let M=this.buildExampleHelper({schema:D.schema,exampleId:t,example:l[P],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});if(M!=null)d[P]=M;else return}else{let M=this.buildExampleHelper({exampleId:t,schema:D.schema,example:l?.[P],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});if(M!=null)d[P]=M;else if(A)return}}return Yg.oneOf(i3i.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:c});break}}return;case"unknown":if(r!=null){let d=g3i(r);if(d!=null)return Yg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?Yg.primitive(D_.string(u.name??"string")):Yg.map([{key:D_.string("key"),value:Yg.primitive(D_.string("value"))}]);case"array":{let d=c1_(r),s=[];if(d!=null&&d.length>0)for(let o of d){let l=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});l!=null&&s.push(l)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let l=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});l!=null&&s.push(l)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});o!=null&&s.push(o)}return Yg.array(s)}case"map":{let d=c5a(r??i.example);if(d!=null&&Object.entries(d).length>0){let l=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});m!=null&&l.push({key:O,value:m})}return Yg.map(l)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return Yg.map([{key:D_.string("key"),value:Yg.unknown(Yg.primitive(D_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:c});return o!=null?Yg.map([{key:s,value:o}]):Yg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=c5a(r)??(s!=null?c5a(s.value):{})??{},l=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(l)){if(c&&O.readonly||O.schema._visit({optional:A=>typeof A.availability=="string"&&A.availability==="Deprecated",primitive:()=>!1,object:()=>!1,array:()=>!1,map:()=>!1,enum:()=>!1,reference:()=>!1,literal:()=>!1,oneOf:()=>!1,nullable:()=>!1,unknown:()=>!1,_other:()=>!1}))continue;let m=g in b,P=Object.keys(o).includes(g),D=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:c});if(m&&D!=null)d[g]=D;else{if(m)return;(P&&D!=null||!u.ignoreOptionals&&D!=null)&&(d[g]=D)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Nl.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:c});m!=null&&(d[g]=m)}}return Yg.object({properties:d})}default:Ao(i)}}mergeExampleWith(t,r){t._visit({array:Ko,enum:Ko,literal:Ko,map:i=>{for(let n of i){let a=n.key;a.type==="string"&&(r[a.value]=n.value)}},object:i=>{for(let[n,a]of Object.entries(i.properties))r[n]=a},oneOf:i=>{if(i.type==="discriminated")for(let[n,a]of Object.entries(i.value))r[n]=a;else this.mergeExampleWith(i.value,r)},primitive:Ko,unknown:Ko,_other:Ko})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return l1_({schema:t,value:r})?5:0;case"object":{if(!Tw(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!Tw(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?D_.string(t):r.example!=null?D_.string(r.example):D_.string(i.name??Hh.STRING);case"base64":return t!=null&&typeof t=="string"?D_.base64(t):r.example!=null?D_.base64(r.example):D_.base64(Hh.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?D_.boolean(t):r.example!=null?D_.boolean(r.example):D_.boolean(Hh.BOOLEAN);case"date":return t!=null&&typeof t=="string"?D_.date(t):r.example!=null?D_.date(r.example):D_.date(Hh.DATE);case"datetime":return t!=null&&typeof t=="string"?D_.datetime(t):r.example!=null?D_.datetime(r.example):D_.datetime(Hh.DATE_TIME);case"double":return t!=null&&typeof t=="number"?D_.double(t):r.example!=null?D_.double(r.example):D_.double(Hh.DOUBLE);case"float":return t!=null&&typeof t=="number"?D_.float(t):r.example!=null?D_.float(r.example):D_.float(Hh.FLOAT);case"int":return t!=null&&typeof t=="number"?D_.int(t):r.example!=null?D_.int(r.example):D_.int(Hh.INT);case"int64":return t!=null&&typeof t=="number"?D_.int64(t):r.example!=null?D_.int64(r.example):D_.int64(Hh.INT64);case"uint":return t!=null&&typeof t=="number"?D_.uint(t):r.example!=null?D_.uint(r.example):D_.uint(Hh.UINT);case"uint64":return t!=null&&typeof t=="number"?D_.uint64(t):r.example!=null?D_.uint64(r.example):D_.uint64(Hh.UINT64);default:Ao(r)}}};function l1_({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function TQt(e){switch(e.type){case"object":return Nl.object({allOf:e.allOf,properties:e.properties.map(t=>LIE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return Nl.array({description:e.description,availability:e.availability,value:TQt(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Nl.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Nl.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName});case"nullable":return Nl.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:TQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Nl.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:TQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Nl.primitive({description:e.description,availability:e.availability,schema:f1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Nl.map({description:e.description,availability:e.availability,key:Nl.primitive({description:e.key.description,availability:e.key.availability,schema:f1_(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:TQt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return Nl.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Nl.oneOf(FIE(e.value));case"unknown":return Nl.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,namespace:void 0,groupName:void 0,description:void 0,availability:void 0});default:Ao(e)}}function FIE(e){switch(e.type){case"discriminated":return Cee.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:TQt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,TQt(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return Cee.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>TQt(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Ao(e)}}function f1_(e){switch(e.type){case"string":return vp.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return vp.base64({example:void 0});case"boolean":return vp.boolean({default:e.default,example:void 0});case"date":return vp.date({example:void 0});case"datetime":return vp.datetime({example:void 0});case"double":return vp.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return vp.float({example:void 0});case"int":return vp.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return vp.int64({default:e.default,example:void 0});case"uint":return vp.uint({default:void 0,example:void 0});case"uint64":return vp.uint64({default:void 0,example:void 0});default:Ao(e)}}function LIE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:TQt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function _au(e){return e.type!=="optional"&&e.type!=="nullable"}function aDc(e){return e==="POST"||e==="PUT"||e==="PATCH"}function l5a(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var hau=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,i){this.schemas=t,this.context=r,this.globalHeaders=i,this.schemas=t,this.exampleTypeFactory=new O3i(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=VIE(t.request),i=WIE(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:aDc(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:aDc(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(l&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let l=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,MQt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,MQt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,MQt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,MQt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let l of t.pathParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:g})}let c=[];for(let l of t.queryParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&c.push({name:l.name,value:g})}let d=[];for(let l of t.headers){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:l.name,value:g})}for(let l of this.globalHeaders){let b=l.schema!=null?TQt(l.schema):Nl.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:vp.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),g=this.exampleTypeFactory.buildExample({schema:b,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),g==null)return[];g!=null&&d.push({name:l.header,value:g})}let s=[];t.request!=null&&t.response!=null?s=UIE(n,a):t.request!=null?s=n.map(([l,b])=>({id:l,request:b,response:void 0})):t.response!=null&&(s=a.map(([l,b])=>({id:l,request:void 0,response:b})));let o=t.examples.filter(l=>l5a(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let b=l.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return l.codeSamples}).filter(l=>yy(l));return s.length===0?[EQt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:c,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:l,request:b,response:g})=>EQt.full({name:l,description:void 0,pathParameters:u,queryParameters:c,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?wmi.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):wmi.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?g$.Csharp:r.sdk,code:r.code})).filter(yy)}isSchemaRequired(t){return _au(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function UIE(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,c]of t)r.push({id:u??n,request:a,response:c});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,c]of e)r.push({id:u??n,request:c,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let c=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),c=!0)}!c&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],c=e.find(([d])=>d==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:u})}return r}function VIE(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:HIE(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function WIE(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function CQt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return CQt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return CQt(e.value.value);default:return!1}default:Ao(e)}}function HIE(e){return Nl.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:TQt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(yy),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var VJn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new O3i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let u=[];for(let c of r){let d=[];for(let l of i.queryParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!CQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&d.push({name:l.name,value:g})}let s=[];for(let l of i.headers){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!CQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&s.push({name:l.name,value:g})}let o=[];for(let l of c.messages){let b=t.getExampleMessageReference(l),g=t.resolveMessageReference({$ref:b}),O=ep(g.payload)?t.resolveSchemaReference(g.payload):g.payload,m=this.exampleTypeFactory.buildExample({schema:n0(O,!1,t,[l.messageId],n,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&o.push({messageType:l.type,payload:m,description:void 0})}u.push({name:c.summary,queryParameters:d,headers:s,description:c.description,messages:o})}return u}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let u of t.queryParameters){let c=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!CQt(d)&&(d=void 0),c&&d==null)return;d!=null&&n.push({name:u.name,value:d})}let a=[];for(let u of t.headers){let c=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!CQt(d)&&(d=void 0),c&&d==null)return;d!=null&&a.push({name:u.name,value:d})}for(let u of r){let c=this.exampleTypeFactory.buildExample({schema:u.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&i.messages.push({messageType:u.type,payload:c,description:void 0})}return i}isSchemaRequired(t){return _au(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var zee={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function yau(e){return hf(e,zee.FERN_EXAMPLES)??[]}function vau(e,t){return t.includes("://")?t:`${e}://${t}`}function bau(e){return e.startsWith("/")?e:"/"+e}function _1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let l=n0(o,!1,e,[s],r,e.namespace);a[s]=l}let c=new VJn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:vau(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let l=hf(o,zee.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[D,A]of Object.entries(o.parameters??{}))b.push({name:D,description:A.description,parameterNameOverride:void 0,schema:A.schema!=null?n0(A.schema,!1,e,t,r,e.namespace):Nl.primitive({schema:vp.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:zK(A),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let D=o.bindings.ws.headers.required??[];for(let[A,M]of Object.entries(o.bindings.ws.headers.properties??{})){if(ep(M)){let E=e.resolveSchemaReference(M);g.push({name:A,schema:qmi(M,!1,e,t,void 0,r,e.namespace),description:E.description,parameterNameOverride:void 0,env:void 0,availability:zK(E),source:r});continue}g.push({name:A,schema:n0(M,!D.includes(A),e,[...t,A],r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:zK(M),source:r})}}if(o.bindings.ws.query!=null){let D=o.bindings.ws.query.required??[];for(let[A,M]of Object.entries(o.bindings.ws.query.properties??{})){if(ep(M)){let E=e.resolveSchemaReference(M);O.push({name:A,schema:qmi(M,!1,e,t,void 0,r,e.namespace),description:E.description,parameterNameOverride:void 0,availability:zK(E),source:r});continue}O.push({name:A,schema:n0(M,!D.includes(A),e,[...t,A],r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:zK(M),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=d1_({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=p1_({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let P;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?P=d1_({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):P=p1_({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||P!=null){let D=yau(o),A=[];if(D.length>0)A=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:D,handshake:{headers:g,queryParameters:O},source:r,namespace:e.namespace});else{let z=[];m!=null&&z.push({type:"publish",payload:m}),P!=null&&z.push({type:"subscribe",payload:P});let G=c.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},messages:z});G!=null&&A.push(G)}let M=hf(o,zee.FERN_CHANNEL_ADDRESS),E=M??bau(s),C=[];m!=null&&C.push({origin:"client",name:"publish",body:bA(m)}),P!=null&&C.push({origin:"server",name:"subscribe",body:bA(P)}),u[s]={audiences:hf(o,ad.AUDIENCES)??[],handshake:{headers:g.map(z=>({...z,schema:bA(z.schema),env:z.env})),queryParameters:O.map(z=>({...z,schema:bA(z.schema)})),pathParameters:b.map(z=>({...z,parameterNameOverride:void 0,schema:bA(z.schema)}))},groupName:e.resolveGroupName([hf(o,zee.FERN_SDK_GROUP_NAME)??s]),messages:C,servers:(o.servers?.map(z=>d[z])??Object.values(d)).filter(z=>z!=null),summary:hf(o,zee.FERN_DISPLAY_NAME),path:E,description:o.description,examples:A,source:r}}}return{groupedSchemas:UJn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:hf(n,zee.BASE_PATH)}}function d1_({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],d=[];for(let s of t.message.oneOf){let o,l={type:"notFound"};if(ep(s)){let b=r.resolveMessageReference(s);!ep(b.payload)&&u.naming==="v2"?(l=b.name?{type:"name",name:b.name}:l,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(l),c.push(o)}return b3i({description:t.description??t.message.description,availability:zK(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function p1_({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return ep(r.payload)&&(a=i.resolveSchemaReference(r.payload)),n0(a,!1,i,[t,e],n,i.namespace)}}var gau=class extends LJn{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(r.length),n=this.document.components.parameters[i];if(n==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in n?this.resolveParameterReference(n):n}resolveMessageReference(t){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let c=t.$ref.split("/"),d=c[2],s=c[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let l=this.document.channels[d].messages?.[s];if(l==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in l?this.resolveMessageReference(l):{name:s,...l}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var h1_="#/channels/",y1_="#/servers/",oDc="$message.";function b1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},c={},d=[],s={};for(let[O,m]of Object.entries(n.components?.schemas??{}))a[O]=n0(m,!1,e,[O],r,e.namespace);for(let[O,m]of Object.entries(n.channels??{}))if(u[O]||(u[O]={}),m.messages){for(let[P,D]of Object.entries(m.messages))if(e.isReferenceObject(D)||e.isMessageWithPayload(D))if(c[P]||(c[P]=[]),e.isReferenceObject(D)){let A=e.resolveMessageReference(D);c[P].push({channelId:O,payload:A.payload})}else c[P].push({channelId:O,payload:D.payload})}for(let[O,m]of Object.entries(c))if(m.length===1){let P=m[0],D=P.channelId;u[D]=u[D]||{},u[D][O]=n0(P.payload,!1,e,[O],r,e.namespace)}else{d.push(O);for(let{channelId:P,payload:D}of m){let A=`${P}_${O}`;u[P]||(u[P]={}),u[P][A]=n0(D,!1,e,[A],r,e.namespace)}}let o=Object.values(u).reduce((O,m)=>({...O,...m}),{}),l=new VJn(o,e),b={};for(let[O,m]of Object.entries(n.servers??{}))b[O]={name:O,url:vau(m.protocol,m.host)};let g={};for(let[O,m]of Object.entries(n.operations??{})){if(hf(m,zee.IGNORE))continue;let P=$IE(m);if(g[P]||(g[P]={subscribe:[],publish:[],__parsedMessages:[]}),m.action==="receive")g[P].subscribe.push(...m.messages);else if(m.action==="send")g[P].publish.push(...m.messages);else throw new Error(`Operation ${O} has an invalid action: ${m.action}`)}for(let[O,m]of Object.entries(g)){let P=[];P.push(...v1_({messages:m.subscribe,channelPath:O,origin:"server",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),P.push(...v1_({messages:m.publish,channelPath:O,origin:"client",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),g[O]!=null&&(g[O].__parsedMessages=P)}for(let[O,m]of Object.entries(n.channels??{})){if(hf(m,zee.IGNORE))continue;let P=[],D=[],A=[];if(m.parameters!=null)for(let[M,E]of Object.entries(m.parameters)){let C=e.isReferenceObject(E)?e.resolveParameterReference(E):E,{type:z,parameterKey:G}=C.location!=null?GIE(C.location):{type:m.address?.includes(`={${M}}`)?"query":"path",parameterKey:M},I=hf(C,zee.FERN_PARAMETER_OPTIONAL),N=QB(R_(O))+QB(R_(M)),U={...C,type:"string",title:N,example:C.examples?.[0],default:C.default,enum:C.enum,required:void 0},Y=n0(U,!1,e,[G],r,e.namespace);I&&(Y=Nl.optional({value:Y,description:void 0,availability:void 0,generatedName:"",title:N,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let J={name:G,description:C.description,parameterNameOverride:void 0,schema:Y,variableReference:void 0,availability:zK(E),source:r};z==="header"?P.push({...J,env:void 0}):z==="path"?D.push(J):(z==="payload"||z==="query")&&A.push(J)}if(P.length>0||A.length>0||g[O]!=null&&(g[O].publish!=null||g[O].subscribe!=null)){let M=yau(m),E=g[O]?.__parsedMessages??[],C=[];if(M.length>0)C=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:M,handshake:{headers:P,queryParameters:A},source:r,namespace:e.namespace});else{let z=[],{examplePublishMessage:G,exampleSubscribeMessage:I}=JIE({messages:E,messageSchemas:u[O]??{}});G!=null&&z.push(G),I!=null&&z.push(I);let N=l.buildWebsocketSessionExample({handshake:{headers:P,queryParameters:A},messages:z});N!=null&&C.push(N)}s[O]={audiences:hf(m,ad.AUDIENCES)??[],handshake:{headers:P.map(z=>({...z,schema:bA(z.schema),env:z.env})),queryParameters:A.map(z=>({...z,schema:bA(z.schema)})),pathParameters:D.map(z=>({...z,parameterNameOverride:void 0,schema:bA(z.schema)}))},groupName:e.resolveGroupName([hf(m,zee.FERN_SDK_GROUP_NAME)??O]),messages:E,summary:hf(m,zee.FERN_DISPLAY_NAME),servers:m.servers?.map(z=>QIE(b,z))??Object.values(b),path:m.address?.split("?")[0]??bau(O),description:m.description,examples:C,source:r}}}return{groupedSchemas:UJn(e.namespace,a),channels:s,servers:Object.values(b),basePath:hf(n,zee.BASE_PATH)}}function $IE(e){if(!e.channel.$ref.startsWith(h1_))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(h1_.length)}function GIE(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(oDc))throw new Error(`Invalid location format: ${e}; expected ${oDc} prefix`);let i=t.substring(oDc.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function QIE(e,t){if(!t.$ref.startsWith(y1_))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(y1_.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function v1_({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let u=[];return e.forEach((c,d)=>{let o=a.resolveMessageReference(c).name;n.includes(o)&&(o=`${t}_${o}`);let l=i[o];l!=null&&u.push({origin:r,name:o??`${r}Message${d+1}`,body:bA(l)})}),u}function JIE({messages:e,messageSchemas:t}){let r=e.find(u=>u.origin==="client")?.name,i=e.find(u=>u.origin==="server")?.name,n=r!=null?t[r]:void 0,a=i!=null?t[i]:void 0;return{examplePublishMessage:n!=null&&r!=null?{type:r,payload:n}:void 0,exampleSubscribeMessage:a!=null&&i!=null?{type:i,payload:a}:void 0}}function g1_({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?u.push(c.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new pau({document:c,taskContext:t,options:r,namespace:a});return _1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:c})}else{let c=e,d=new gau({document:c,taskContext:t,options:r,namespace:a});return b1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:c})}}function O1_(e){return hf(e,ad.ASYNC_CONFIG)}var m1_="$request.";function P1_(e){let t=hf(e,ad.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:KIE(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function KIE(e){return e.startsWith(m1_)?e.slice(m1_.length):e}function j1_(e){let t=e;if(t.cursor!=null)return O6e.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return O6e.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return O6e.custom({results:r.results})}throw new Error("Invalid pagination extension")}function w1_(e,t){let r=hf(t,ad.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=hf(e,ad.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:j1_(i)}return j1_(r)}}function S1_(e){let t=YIE(e),r={};return uDc({obj:t,occurrences:r,breadcrumbs:[]}),r}function uDc({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)uDc({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)uDc({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function YIE(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?f5a(r.get):void 0,put:r?.put!=null?f5a(r.put):void 0,post:r?.post!=null?f5a(r.post):void 0,patch:r?.patch!=null?f5a(r.patch):void 0,delete:r?.delete!=null?f5a(r.delete):void 0}]))}}function f5a(e){return{...e,requestBody:e.requestBody!=null?ep(e.requestBody)?e.requestBody:XIE(e.requestBody):void 0}}function XIE(e){let t,r;for(let i in e.content){let n=Iq.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[Iq.MULTIPART_FORM_DATA]:r}}:e}var Oau=class{endpoints;parser=new uen;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var D1_="#/components/parameters/",E1_="#/components/responses/",M1_="#/components/examples/",A1_="#/components/requestBodies/",WJn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=S1_(t),this.options=n,this.source=a,this.filter=new Oau({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};if(Array.isArray(i)){let a=parseInt(n,10);if(isNaN(a)||a<0||a>=i.length)return{"x-fern-type":"unknown"};i=i[a]}else i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(ep(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(D1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(D1_.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(A1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(A1_.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(E1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(E1_.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(M1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(M1_.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var Onn=class extends WJn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var ZIE=Yo.object({lang:Yo.string(),label:Yo.optional(Yo.string()),source:Yo.string()}),sDc=Yo.array(ZIE);var q1_={README_EXT:"x-readme"};function kIE(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Tw(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function T1_(e){let t=hf(e,q1_.README_EXT);if(!Tw(t))return[];let r=t["code-samples"];if(!kIE(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function C1_(e,t,r){let n=(hf(t,ad.EXAMPLES)??[]).filter(s=>{let o=ZN.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=u5a(t,m$.REDOCLY_CODE_SAMPLES_KEBAB,sDc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...u5a(t,m$.REDOCLY_CODE_SAMPLES_CAMEL,sDc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&n.push({"code-samples":c.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=T1_(t);return d.length>0&&n.push({"code-samples":d}),n.map(EQt.unknown)}function B1_(e){let t=hf(e,ad.AVAILABILITY);if(t==="ga"||t==="generally-available")return b$.GenerallyAvailable;if(t==="beta"||t==="pre-release")return b$.Beta;if(t==="deprecated")return b$.Deprecated;if(e.deprecated)return b$.Deprecated}function mau(e){return{url:ezE({url:e.url,variables:e.variables??{}}),description:e.description,name:tzE(e),audiences:hf(e,ad.AUDIENCES)}}function ezE({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,encodeURIComponent(n));return e}function tzE(e){let t=hf(e,[ad.SERVER_NAME_V1,ad.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function I1_(e){return hf(e,ad.PARAMETER_NAME)}function z1_(e){return hf(e,ad.SDK_VARIABLE)}function Pau({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let d=hf(c,ad.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=ep(c)?i.resolveParameterReference(c):c,o=s.required??!1,l=zK(s),b=[...n,s.name],g=g5(b,i.options.preserveSchemaIds),O=s.schema!=null?n0(s.schema,!o,i,b,a,i.namespace,!1,new Set,ror({schema:s,logger:i.logger})):o?Nl.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:ror({schema:s,logger:i.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):Nl.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Nl.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:ror({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:l,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!ep(s.schema)&&s.schema.default!=null){let P=s.schema.default;typeof P=="string"&&P.length>0&&(O=Nl.literal({nameOverride:void 0,generatedName:g,title:void 0,value:_x.string(P),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:I1_(s),availability:l,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:z1_(s)}):s.in==="header"?!rzE.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var rzE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function x1_(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:d5a(i,t)}}}function izE(e){return e.includes("json")||e==="*/*"}function cDc({content:e,context:t}){for(let[r,i]of Object.entries(e))if(jau({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function jau({mediaType:e,mediaTypeObject:t,context:r}){if(!izE(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:d5a(t,r)}}function wau({content:e,context:t}){let r=cDc({content:e,context:t});if(!r)return;let[i,n]=r;return jau({mediaType:i,mediaTypeObject:n,context:t})}function R1_(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:d5a(i,t)}}}function d5a(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=hf(e,m$.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=ep(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function nzE({content:e,context:t}){for(let[r,i]of Object.entries(e))if(F1_({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function F1_({mediaType:e,mediaTypeObject:t,context:r}){if(Iq.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:d5a(t,r)}}function azE({content:e}){for(let[t,r]of Object.entries(e))if(L1_({mediaType:t,mediaTypeObject:r}))return[t,r]}function L1_({mediaType:e,mediaTypeObject:t}){if(Iq.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function U1_({mediaType:e}){return Iq.parse(e)?.isBinary()??!1}function ozE({content:e}){for(let[t,r]of Object.entries(e))if(U1_({mediaType:t}))return[t,r]}function uzE(e,t){let r=ep(e)?lDc(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!ep(n)&&n.type==="string"&&n.format==="binary")!=null}function Dau({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}){let c=ozE({content:e});if(c){let[b,g]=c;return ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}let d=azE({content:e}),s=cDc({content:e,context:i}),o=szE({json:s,multipart:d,document:r,visitor:{json:([b,g])=>ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),multipart:([b,g])=>ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),neither:()=>{}}});if(o)return o;let l=nzE({content:e,context:i});if(l){let[b,g]=l;return ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}}function szE({json:e,multipart:t,document:r,visitor:i}){if(!e&&!t)return i.neither();let[,n]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!n?.schema&&!a?.schema?i.neither():n?.schema&&a?.schema?n.schema&&uzE(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function ior({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:u,namespace:c}){let d=czE({mediaTypeObject:t});if(U1_({mediaType:e}))return Tee.octetStream({description:r,source:u,sdkMethodName:d,contentType:e});let s=L1_({mediaType:e,mediaTypeObject:t}),o=s?.schema,l=s?.encoding;if(o){let O=ep(o)?lDc(o,i):{id:void 0,schema:o},m=n0(O.schema,!1,n,a,u,c,!1),P=[];if(m.type==="object")for(let D of m.properties){let{isFile:A,isOptional:M,isArray:E,description:C}=Sau({schema:D.schema});if(A){let z=N1_(D.key,l);P.push({key:D.key,schema:Smi.file({isOptional:M,isArray:E,description:C}),description:C,contentType:z,exploded:!1,encoding:z==null?n.options.defaultFormParameterEncoding:void 0})}else{let z=N1_(D.key,l);P.push({key:D.key,schema:Smi.json(D.schema),description:void 0,contentType:z,exploded:l?.[D.key]?.explode,encoding:z==null?n.options.defaultFormParameterEncoding:fzE(z)})}}return Tee.multipart({name:ep(o)&&n.getNumberOfOccurrencesForRef(o)===1?O.id:void 0,description:O.schema.description,properties:P,source:u,sdkMethodName:d})}let b=jau({mediaType:e,mediaTypeObject:t,context:n});if(b){let O=n0(b.schema,!1,n,a,u,c,!0);return Tee.json({description:void 0,schema:O,contentType:b.contentType,fullExamples:b.examples,additionalProperties:!ep(b.schema)&&xJn(b.schema.additionalProperties,n.options),source:u,sdkMethodName:d})}let g=F1_({mediaType:e,mediaTypeObject:t,context:n});if(g!=null&&g.schema!=null){let O=n0(g.schema,!1,n,a,u,c,!1);return Tee.formUrlEncoded({schema:O,description:r,contentType:g.contentType,source:u,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:d})}}function czE({mediaTypeObject:e}){return hf(e,ad.SDK_METHOD_NAME)}var lzE={"application/json":"json"};function fzE(e){return e?lzE[e]:void 0}function lDc(e,t){if(!e.$ref.startsWith(gnn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=v3i(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return ep(i)?lDc(i,t):{id:r,schema:i}}function Sau({schema:e,isOptional:t,isArray:r,description:i}){return pzE(e)?Sau({schema:e.value,isOptional:!0,isArray:r,description:e.description}):_zE(e)?Sau({schema:e.value,isOptional:t,isArray:r,description:e.description}):hzE(e)?Sau({schema:e.value,isOptional:t,isArray:!0,description:e.description}):dzE(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:i??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function dzE(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function pzE(e){return e.type==="optional"}function _zE(e){return e.type==="nullable"}function hzE(e){return e.type==="array"}function N1_(e,t){return t?.[e]?.contentType}var fDc={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},V1_=new Set(Object.values(fDc));var yzE=["200","201","202","204"];function H1_({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let c=vzE({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:yzE){let l=t[o];l!=null&&(d=!0,s==null&&(s=W1_({operationContext:e,response:l,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=W1_({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:c};case"streamingJson":case"streamingSse":return{value:s,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:c};default:Ao(s)}return{value:void 0,errors:c}}function W1_({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:c}){let d=ep(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=ep(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?OB.bytes({description:d.description,source:a,statusCode:c}):OB.file({description:d.description,source:a,statusCode:c});let s=x1_(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return OB.streamingJson({statusCode:c,description:d.description,responseProperty:hf(e.operation,ad.RESPONSE_PROPERTY),fullExamples:s.examples,schema:n0(s.schema,!1,i,n,a,u),source:a});case"sse":return OB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:n0(s.schema,!1,i,n,a,u),source:a,statusCode:c})}let o=wau({context:i,content:d.content??{}});if(o){if(t!=null)switch(t){case"json":return OB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:n0(o.schema,!1,i,n,a,u),source:a,statusCode:c});case"sse":return OB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:n0(o.schema,!1,i,n,a,u),source:a,statusCode:c})}return OB.json({description:d.description,schema:n0(o.schema,!1,i,n,a,u),responseProperty:hf(e.operation,ad.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:c})}for(let[l,b]of Object.entries(d.content??{})){let g=Iq.parse(l);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo()||g.isMultiPartMixed())return OB.file({description:d.description,source:a,statusCode:c});if(g.isPlainText()){let O=b.schema;if(O==null)return OB.text({description:d.description,source:a,statusCode:c});let m=ep(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?OB.file({description:d.description,source:a,statusCode:c}):OB.text({description:d.description,source:a,statusCode:c})}}}}function vzE({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let d=ep(u)?t.resolveResponseReference(u):u,s=R1_(d.content??{},t),o=fDc[c];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[c]={statusCode:c,nameOverride:void 0,generatedName:o,description:d.description,schema:n0(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function Tmi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:c,path:d,method:s,baseBreadcrumbs:o}=e,l=hf(c,ad.IDEMPOTENT),b=hf(c,[ad.REQUEST_NAME_V1,ad.REQUEST_NAME_V2]),g=[...o,"Request"],O=Pau({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:d,httpMethod:s,source:a}),m=/{([^}]+)}/g,D=[...d.matchAll(m)].map(I=>I[1]).filter(I=>!O.pathParameters.some(N=>N.name===I));if(D.length>0)for(let I of D)O.pathParameters.push({name:I??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Nl.primitive({schema:vp.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0});let A=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let I=ep(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,N=Object.values(I.content).every(Y=>bzE({mediaTypeObject:Y})!=null),U=[];if(N)return U.push(...Object.entries(I.content).map(([Y,J])=>{let X=ior({mediaType:Y,mediaTypeObject:J,description:I.description,document:u,context:new Onn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return $1_({context:t,convertedParameters:O})&&X!=null&&(X.type==="json"||X.type==="formUrlEncoded")&&X.schema.type!=="object"&&c.requestBody!=null?X=ior({mediaType:Y,mediaTypeObject:J,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(X=ior({mediaType:Y,mediaTypeObject:J,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),X}).filter(Y=>Y!=null)),U.length===0?[void 0]:U;{let Y=Dau({content:I.content,description:I.description,document:u,context:new Onn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return $1_({context:t,convertedParameters:O})&&Y!=null&&(Y.type==="json"||Y.type==="formUrlEncoded")&&Y.schema.type!=="object"&&c.requestBody!=null?Y=Dau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(Y=Dau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),[Y]}})(),M=[...o,"Response"],E=H1_({operationContext:e,streamFormat:n,responses:c.responses,context:t,responseBreadcrumbs:M,responseStatusCode:r,source:a}),C=B1_(c),z=C1_(e,c,t),G=hf(c,ad.SERVER_NAME_V2);return A.map(I=>({summary:c.summary,internal:hf(c,m$.INTERNAL),idempotent:l,audiences:hf(c,ad.AUDIENCES)??[],operationId:c.operationId!=null&&i!=null?c.operationId+"_"+i:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:gzE({operationContext:e,request:I}),pathParameters:O.pathParameters,queryParameters:O.queryParameters,headers:O.headers,requestNameOverride:b??void 0,generatedRequestName:g5(g,t.options.preserveSchemaIds),request:I,response:E.value,errors:E.errors,servers:G!=null?[{name:G,url:void 0,audiences:void 0}]:(c.servers??[]).map(N=>mau(N)),description:c.description,authed:OzE(c,u),availability:C,method:s,path:d,examples:z,pagination:e.pagination,source:a}))}function bzE({mediaTypeObject:e}){return hf(e,ad.SDK_METHOD_NAME)}function gzE({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function OzE(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function $1_({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function Q1_({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,c=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=G1_({context:t,headerToIgnore:c,parameters:a}),l=G1_({context:t,headerToIgnore:c,parameters:u}),b=Tmi({operationContext:{...e,pathItemParameters:o,operationParameters:l,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=Tmi({operationContext:{...e,pathItemParameters:o,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.forEach(O=>{O.headers.push({name:c,schema:Nl.literal({nameOverride:void 0,generatedName:g5([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:_x.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:b,async:g}}function G1_({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=ep(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var dDc="stream";function X1_({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:Tmi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=J1_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=v3i(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=K1_({operation:e.operation,response:r.responseStream}),a=Tmi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+dDc}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,dDc]},context:t,streamFormat:r.format,suffix:dDc,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(o=>Y1_(o,t)!==!1)});let u=J1_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=K1_({operation:e.operation,response:r.response}),d=Tmi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:c}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(o=>Y1_(o,t)!==!0)}),{streaming:a,nonStreaming:d}}default:Ao(r)}}function J1_({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=ep(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=wau({content:n.content,context:e});if(a==null)return;let u=ep(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let c=u.properties?.[r.streamConditionProperty];c!=null&&ep(c)&&(c=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...c??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[Iq.APPLICATION_JSON]:{schema:d}}},schemaReference:ep(a.schema)?a.schema:void 0}}function K1_({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[Iq.APPLICATION_JSON]:{schema:t}}}}}function Y1_(e,t){return e._visit({unknown:r=>{let i=ZN.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function Z1_({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:c,sdkMethodName:d}=t,s=[...c,"Payload"],o=Pau({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`),[];let l=n.operationId;if(l==null)return e.logger.error(`Skipping webhook ${a} because no operation id present`),[];if(u!=="POST"&&u!=="GET")return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`),[];let b=ep(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(b.content).map(([g,O])=>ior({mediaType:g,mediaTypeObject:O,description:b.description,document:i,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:n.summary,audiences:hf(n,ad.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:u,operationId:l,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:g5(s,e.options.preserveSchemaIds),payload:g.schema,description:n.description,examples:mzE(g.fullExamples),source:r}}).filter(g=>g!=null)}function mzE(e){if(e==null)return[];let t=[];for(let r of e){let i=g3i(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function pDc({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=hf(r,ad.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=PzE(r,e),u=w1_(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:jzE({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i)return{type:"webhook",value:Z1_({context:e,operationContext:c,source:e.source})};let d=P1_(r);if(d!=null){let l=X1_({context:e,operationContext:c,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let s=O1_(r);if(s!=null){let l=Q1_({context:e,operationContext:c,asyncExtension:s,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:Tmi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function PzE(e,t){let r=hf(e,ad.SDK_METHOD_NAME),i=hf(e,ad.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function jzE({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(R_(`${r}_${i.split("/").join("_")}`));return a}function k1_(e,t,r,i){let n=[],a=tS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=wzE({operation:c.operation}),s=pDc({context:i,pathItemContext:{...u,method:c.method},operation:c.operation,convertToWebhook:d});s&&n.push(s)}return n}function eS_(e,t,r,i){let n=[],a=tS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=pDc({context:i,pathItemContext:{...u,method:c.method},operation:c.operation,convertToWebhook:!0});d&&n.push(d)}return n}function tS_(e){let t=[];return e.get!=null&&t.push({method:O$.Get,operation:e.get}),e.post!=null&&t.push({method:O$.Post,operation:e.post}),e.put!=null&&t.push({method:O$.Put,operation:e.put}),e.delete!=null&&t.push({method:O$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:O$.Patch,operation:e.patch}),e.head!=null&&t.push({method:O$.Head,operation:e.head}),t}function wzE({operation:e}){return hf(e,[ad.WEBHOOK])??!1}function rS_(e){let t=hf(e,ad.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=hf(e,ad.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function iS_(e){return hf(e,ad.FERN_BASIC_AUTH)}function _Dc(e,t){if(ep(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return SzE(e,t)}function SzE(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=hf(e,m$.BEARER_FORMAT),i=hf(e,ad.FERN_HEADER_AUTH);return jU.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??hf(e,ad.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let r=hf(e,ad.FERN_BEARER_TOKEN);return jU.bearer({tokenVariableName:r?.name??hf(e,ad.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let r=iS_(e),i=rS_(e);return jU.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return jU.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return jU.oauth({scopesEnum:DzE(e,t)})}}function DzE(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=y3i({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=bA(i);if(n.type==="enum")return n}}function nS_(e){return hf(e,ad.BASE_PATH)}var EzE=Yo.record(Yo.string(),Yo.object({summary:Yo.string().optional(),description:Yo.string().optional()}));function aS_({document:e,context:t}){return u5a(e,ad.GROUPS,EzE,t.logger)}function oS_({context:e,document:t}){return hf(t,ad.FERN_VERSION)??void 0}function uS_(e){let t=hf(e,ad.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?s5a({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function sS_(e){let t=hf(e,ad.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?s5a({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function cS_(e,t){let r=hf(e,ad.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:g5([i],t),title:n.title,schema:xw.string({default:NJn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var MzE="webhooks";function lS_(e){return hf(e,MzE)??{}}var Eau=class extends WJn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new Onn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function fS_(e){return hf(e,ad.RESOLUTIONS)}function dS_({openapi:e}){let t=fS_(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=AzE({openapi:e,schemaReference:a,schemaName:i.name}),e=pS_({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function AzE({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function pS_({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return pS_({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let c=a[a.length-1];return c==null||(u[c]={$ref:r}),e}function hS_({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=dS_({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,N])=>_Dc(N,i)==null?[]:[I,_Dc(N,i)])),u=new Set(...Object.entries(a).map(([I,N])=>N.type==="basic"||N.type==="bearer"?"Authorization":N.type==="header"?N.headerName:null)),c=cS_(e,r.preserveSchemaIds),d=uS_(e),s=sS_(e),o=r.audiences??[],l=[],b=[],g=new Eau({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,N])=>{if(N==null)return;t.logger.debug(`Converting path ${I}`);let U=k1_(I,N,e,g);for(let Y of U){let J=_S_({operation:Y});if(!(o.length>0&&!o.some(X=>J.includes(X))))switch(Y.type){case"async":l.push(...Y.sync),l.push(...Y.async);break;case"http":l.push(...Y.value);break;case"streaming":l.push(...Y.streaming),Y.nonStreaming&&l.push(...Y.nonStreaming);break;case"webhook":b.push(...Y.value);break;default:Ao(Y)}}}),Object.entries(lS_(e)).forEach(([I,N])=>{if(N==null)return;t.logger.debug(`Converting path ${I}`);let U=eS_(I,N,e,g);for(let Y of U){let J=_S_({operation:Y});o.length>0&&!o.some(X=>J.includes(X))||b.push(...Y.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,N])=>{let U=hf(N,ad.SDK_NAMESPACE);if(!ep(N)){let Y=hf(N,ad.IGNORE);if(Y!=null&&Y)return[];if(V1_.has(I))return[I,n0({...N,"x-fern-type-name":`${I}Body`},!1,g,[I],i,U??n)]}return[I,n0(N,!1,g,[I],i,U??n)]}).filter(I=>I.length>0)),m=qzE(O,g,i),P=TzE(m,g),D={};for(let[I,N]of Object.entries(P)){let U=bA(N);g.isSchemaExcluded(I)||(D[I]=U,t.logger.debug(`Converted schema ${I}`))}let A=new O3i(P,g.nonRequestReferencedSchemas,g),M=b.map(I=>{let U=I.examples;if(!r.disableExamples&&U.length===0){let Y=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Y!=null&&(U=[{name:void 0,description:void 0,payload:Y}])}return{...I,payload:bA(I.payload),examples:U}}),E=new hau(P,g,d),C=l.map(I=>{let N=I.examples,U=N;if(!r.disableExamples&&(N.length===0||N.every(l5a))){let X=E.buildEndpointExample(I);X.length>0&&(U=[...X,...N.filter(oe=>!l5a(oe))])}let Y=I.request,J=I.response;return{...I,request:Y?.type==="json"||Y?.type==="formUrlEncoded"?{...Y,schema:bA(Y.schema)}:Y,response:J?.type==="json"?{...J,schema:bA(J.schema)}:J,queryParameters:I.queryParameters.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,availability:X.availability,source:X.source})),pathParameters:I.pathParameters.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,variableReference:X.variableReference,availability:X.availability,source:X.source})),headers:I.headers.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,env:X.env,availability:X.availability,source:X.source})),examples:U,errors:Sd(I.errors,X=>{let oe=X.fullExamples?.map(pe=>{let de=g3i(pe.value);if(de!=null)return{name:pe.name,description:pe.description,example:de}}).filter(yy);if(oe?.length===0){let pe=A.buildExample({schema:X.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});pe!=null&&oe.push({name:void 0,description:void 0,example:pe})}return{generatedName:X.generatedName,nameOverride:X.nameOverride,schema:bA(X.schema),description:X.description,source:X.source,examples:oe}})}}),z=aS_({document:e,context:g});return{apiVersion:oS_({context:g,document:e}),basePath:nS_(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(z??{}).map(([I,N])=>[I,{summary:N.summary??void 0,description:N.description??void 0}])),servers:(e.servers??[]).map(I=>mau(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:M,channels:{},groupedSchemas:UJn(n,D),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:c,globalHeaders:d,idempotencyHeaders:s}}function qzE(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},c=t.getReferencesFromDiscriminatedUnion(u);if(c==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!c.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!c.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=yS_({schema:a,schemas:e});for(let o of[...new Set(s)]){let l=i[o]??e[o];l==null||l.type!=="object"||(i[o]={...l,type:"object",properties:l.properties.filter(b=>!c.discriminants.has(b.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(b=>!c.discriminants.has(b.propertyKey))})}}return i}function TzE(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let c=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&c.push({...s,schema:Nl.literal({nameOverride:void 0,generatedName:g5([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:_x.string(o),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else c.push(s);let d={...n,type:"object",properties:c};r[i]=d}return r}function yS_({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...yS_({schema:n,schemas:t}))}return r}function Mau(e){return[...new Set(e)]}function _S_({operation:e}){let t=[];switch(e.type){case"async":t=Mau(e.async.flatMap(r=>r.audiences));break;case"http":t=Mau(e.value.flatMap(r=>r.audiences));break;case"streaming":t=Mau(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=Mau(e.value.flatMap(r=>r.audiences));break;default:Ao(e)}return t}function mnn({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:TK.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=hS_({taskContext:e,openApi:n.value,options:qQt({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=BzE(i,u);break}case"asyncapi":{let u=g1_({document:n.value,taskContext:e,options:qQt({options:n.settings,overrides:r}),source:a,asyncApiOptions:CzE({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(c=>({...c,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=vS_(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Ao(n)}}return i}function CzE({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??Lw_.naming}}function BzE(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:vS_(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function vS_(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var VI_=ui(wcu(),1),Scu={config:new VI_.Config({apis:{},styleguide:{plugins:[ZSc],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function LKn(e){if(e.settings==null&&e.raw?.api?.auth==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.raw?.api?.auth!=null&&(t.auth=e.raw?.api?.auth),t}function v9a(e){return e.swagger!=null}function ETc(e){return e.openapi!=null}function b9a({options:e,overrides:t}={}){return{...qQt({options:e,overrides:t}),...K8a({options:e,overrides:t})}}function J3i(e,t={}){return{...Object.fromEntries(r6(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...r6(e.importedDefinitions).reduce((r,[i,n])=>({...r,...HIa(J3i(n.definition,{defaultURL:n.url}),(a,u)=>GN(i,wy.of(u)))}),{})}}function g9a(e,t={}){return{...Object.fromEntries(r6(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...r6(e.importedDefinitions).reduce((r,[i,n])=>({...r,...HIa(g9a(n.definition,{defaultURL:n.url}),(a,u)=>GN(i,wy.of(u)))}),{})}}function Kmi(e){return{...g9a(e),...J3i(e)}}function Vue(e,t){return Kmi(e.definition)[t]?.contents}function V6(e,t){for(let[r,i]of r6(Kmi(e.definition)))t(r,i.contents,{isPackageMarker:VZi(r)===SS,defaultUrl:i.defaultUrl})}function Qnn(e,t){for(let[r,i]of r6(g9a(e.definition)))t(r,i.contents)}function C6e({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Bs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Bs.dim(r)),i.join(`
@@ -2328,7 +2328,7 @@ ${a}]`:`[${e.join(u)}]`},R_u=(e,t,r)=>`let ${e} = ${C3c(t,r)}`,C3c=(e,t,r)=>{swi
2328
2328
  `)},e.heapify=function(t,r){var i=new e(r);return i.heapArray=t,i.init(),i},e.heappop=function(t,r){var i=new e(r);return i.heapArray=t,i.pop()},e.heappush=function(t,r,i){var n=new e(i);n.heapArray=t,n.push(r)},e.heappushpop=function(t,r,i){var n=new e(i);return n.heapArray=t,n.pushpop(r)},e.heapreplace=function(t,r,i){var n=new e(i);return n.heapArray=t,n.replace(r)},e.heaptop=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.top(r)},e.heapbottom=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.bottom(r)},e.nlargest=function(t,r,i){var n=new e(i);return n.heapArray=Jee([],x$(r),!1),n.init(),n.top(t)},e.nsmallest=function(t,r,i){var n=new e(i);return n.heapArray=Jee([],x$(r),!1),n.init(),n.bottom(t)},e.prototype.add=function(t){return this._sortNodeUp(this.heapArray.push(t)-1),this._applyLimit(),!0},e.prototype.addAll=function(t){var r,i=this.length;(r=this.heapArray).push.apply(r,Jee([],x$(t),!1));for(var n=this.length;i<n;++i)this._sortNodeUp(i);return this._applyLimit(),!0},e.prototype.bottom=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1?[this.heapArray[0]]:t>=this.heapArray.length?Jee([],x$(this.heapArray),!1):this._bottomN_push(~~t)},e.prototype.check=function(){var t=this;return this.heapArray.find(function(r,i){return!!t.getChildrenOf(i).find(function(n){return t.compare(r,n)>0})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t,r){return r===void 0&&(r=e.defaultIsEqual),this.indexOf(t,r)!==-1},e.prototype.init=function(t){t&&(this.heapArray=Jee([],x$(t),!1));for(var r=Math.floor(this.heapArray.length);r>=0;--r)this._sortNodeDown(r);this._applyLimit()},e.prototype.isEmpty=function(){return this.length===0},e.prototype.indexOf=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return-1;for(var i=[],n=0;n<this.heapArray.length;){var a=this.heapArray[n];if(r(a,t))return n;this.compare(a,t)<=0&&i.push.apply(i,Jee([],x$(e.getChildrenIndexOf(n)),!1)),n=i.shift()||this.heapArray.length}return-1},e.prototype.indexOfEvery=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return[];for(var i=[],n=[],a=0;a<this.heapArray.length;){var u=this.heapArray[a];r(u,t)?(n.push(a),i.push.apply(i,Jee([],x$(e.getChildrenIndexOf(a)),!1))):this.compare(u,t)<=0&&i.push.apply(i,Jee([],x$(e.getChildrenIndexOf(a)),!1)),a=i.shift()||this.heapArray.length}return n},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){t<0||isNaN(t)?this._limit=0:this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.setLimit=function(t){return this.limit=t,t<0||isNaN(t)?NaN:this._limit},e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){var t=this.heapArray.pop();return this.length>0&&t!==void 0?this.replace(t):t},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.length<1?!1:t.length===1?this.add(t[0]):this.addAll(t)},e.prototype.pushpop=function(t){var r;return this.compare(this.heapArray[0],t)<0&&(r=x$([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],this._sortNodeDown(0)),t},e.prototype.remove=function(t,r){var i=this;if(r===void 0&&(r=e.defaultIsEqual),!this.heapArray.length)return!1;if(t===void 0)return this.pop(),!0;for(var n=[0];n.length;){var a=n.shift();if(r(this.heapArray[a],t))return a===0?this.pop():a===this.heapArray.length-1?this.heapArray.pop():(this.heapArray.splice(a,1,this.heapArray.pop()),this._sortNodeUp(a),this._sortNodeDown(a)),!0;if(this.compare(this.heapArray[a],t)<=0){var u=e.getChildrenIndexOf(a).filter(function(c){return c<i.heapArray.length});n.push.apply(n,Jee([],x$(u),!1))}}return!1},e.prototype.replace=function(t){var r=this.heapArray[0];return this.heapArray[0]=t,this._sortNodeDown(0),r},e.prototype.size=function(){return this.length},e.prototype.top=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1||t===1?[this.heapArray[0]]:t>=this.heapArray.length?Jee([],x$(this.heapArray),!1):this._topN_push(~~t)},e.prototype.toArray=function(){return Jee([],x$(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(i){return r.heapArray[i]}).filter(function(i){return i!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return RgM(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this.toArray()},e.prototype._applyLimit=function(){if(this._limit>0&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){var r=new e(this.compare);r.limit=t,r.heapArray=this.heapArray.slice(-t),r.init();for(var i=this.heapArray.length-1-t,n=e.getParentIndexOf(i),a=[],u=i;u>n;--u)a.push(u);for(var c=this.heapArray;a.length;){var u=a.shift();this.compare(c[u],r.peek())>0&&(r.replace(c[u]),u%2&&a.push(e.getParentIndexOf(u)))}return r.toArray()},e.prototype._moveNode=function(t,r){var i;i=x$([this.heapArray[r],this.heapArray[t]],2),this.heapArray[t]=i[0],this.heapArray[r]=i[1]},e.prototype._sortNodeDown=function(t){for(var r=this.heapArray.length;;){var i=2*t+1,n=i+1,a=t;if(i<r&&this.compare(this.heapArray[i],this.heapArray[a])<0&&(a=i),n<r&&this.compare(this.heapArray[n],this.heapArray[a])<0&&(a=n),a===t)break;this._moveNode(t,a),t=a}},e.prototype._sortNodeUp=function(t){for(;t>0;){var r=e.getParentIndexOf(t);if(this.compare(this.heapArray[t],this.heapArray[r])<0)this._moveNode(t,r),t=r;else break}},e.prototype._topN_push=function(t){var r=new e(this._invertedCompare);r.limit=t;for(var i=[0],n=this.heapArray;i.length;){var a=i.shift();a<n.length&&(r.length<t?(r.push(n[a]),i.push.apply(i,Jee([],x$(e.getChildrenIndexOf(a)),!1))):this.compare(n[a],r.peek())<0&&(r.replace(n[a]),i.push.apply(i,Jee([],x$(e.getChildrenIndexOf(a)),!1))))}return r.toArray()},e.prototype._topN_fill=function(t){var r=this.heapArray,i=new e(this._invertedCompare);i.limit=t,i.heapArray=r.slice(0,t),i.init();for(var n=e.getParentIndexOf(t-1)+1,a=[],u=n;u<t;++u)a.push.apply(a,Jee([],x$(e.getChildrenIndexOf(u).filter(function(c){return c<r.length})),!1));for((t-1)%2&&a.push(t);a.length;){var u=a.shift();u<r.length&&this.compare(r[u],i.peek())<0&&(i.replace(r[u]),a.push.apply(a,Jee([],x$(e.getChildrenIndexOf(u)),!1)))}return i.toArray()},e.prototype._topN_heap=function(t){for(var r=this.clone(),i=[],n=0;n<t;++n)i.push(r.pop());return i},e.prototype._topIdxOf=function(t){if(!t.length)return-1;for(var r=0,i=t[r],n=1;n<t.length;++n){var a=this.compare(t[n],i);a<0&&(r=n,i=t[n])}return r},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=new e(this.compare);return i.init(t),i.peek()},e})();function sX_(e,t,r,i,n){if(r<=0)return[];let a=i??(c=>c),u=new oX_(NgM);for(let c of t){let d=uX_.default.get(a(e),a(c));n!=null&&d>n||(u.push({neighbor:c,distance:d}),u.size()>r&&u.pop())}return FgM(u).reverse().map(c=>c.neighbor)}function NgM(e,t){return e.distance!==t.distance?t.distance-e.distance:t.neighbor.localeCompare(e.neighbor)}function FgM(e){let t=[];for(;e.size()>0;){let r=e.pop();r&&t.push(r)}return t}var LgM=3,UgM=5;function a7i(e,t){let r=sX_(e,t,LgM,VgM,UgM),i=Array.from(t),n=`Failed to locate API section ${e}.`;switch(r.length){case 0:return n=`${n} No similar API sections found. Available API sections:`,i.length===0?`${n} []`:`${n} [
2329
2329
  ${i.map(a=>` ${a}`).join(`,
2330
2330
  `)}
2331
- ]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function jon(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function VgM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function CXn({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,c),o==null||o.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(o),b=c.isResponseStream?c:o,g=c.isResponseStream?o:c,O={id:Do.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[l]=O}),a}function $hu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return CXn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Xor(e,t){if(t!=null)return IT(e.absoluteFilePath,t)}function Ghu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let c=Do.V1.PageId(Xor(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??CT(t.title)});return{id:i.get(c),type:"page",pageId:c,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Qhu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=c,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#e=n7i.create(r,a),this.#c=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let l=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:l?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??CT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(b=>this.#j(b)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?n7i.getSubpackageId(r):void 0;return t.map(a=>uVa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Do.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(yy)}#p(t,r){return Ghu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=n7i.getSubpackageId(a),c=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(jon(t.package)),this.#a.add(u),this.#o.set(c,[u]);let d=t.slug??(Yor(a)?a.urlSlug:this.apiSection.slug??CT(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:c,type:"apiPackage",children:o,title:t.title??(Yor(a)?a.displayName??nJt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(a7i(t.package,this.#e.subpackageLocators));let u=t.slug??CT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,c);return{id:this.#c.get(i??`${this.apiDefinitionId}:${CT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),c=t.referencedSubpackages.map(l=>{let b=this.#e.getSubpackageByIdOrLocator(l),g=b!=null?n7i.getSubpackageId(b):void 0;if(g===void 0){this.taskContext.logger.error(a7i(l,this.#e.subpackageLocators));return}return{subpackageId:g,locator:l}}).filter(l=>l!=null).filter(yy);this.#o.set(u,c.map(l=>l.subpackageId)),c.forEach(l=>{this.#a.has(l.subpackageId)&&this.taskContext.logger.error(jon(l.locator)),this.#a.add(l.subpackageId)});let d=t.slug??CT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(R_(t));if(n!=null){let a=n7i.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(jon(t)),this.#a.add(a),this.#o.set(u,[a]);let c=Yor(n)?n.urlSlug:"",d=i.apply({urlSlug:c});return{id:u,type:"apiPackage",children:[],title:Yor(n)?n.displayName??nJt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.endpoints.get(h2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let c=this.#e.getEndpointId(n);if(c==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(c)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${c}`),this.#t.add(c);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"endpoint",method:n.method,endpointId:c,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??PB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webSockets.get(h2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let c=this.#e.getWebSocketId(a);if(c==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(c)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${c}`),this.#r.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webSocket",webSocketId:c,title:t.title??a.name??PB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webhooks.get(h2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Do.V1.WebhookId(t.endpoint));if(u!=null){let c=this.#e.getWebhookId(u);if(c==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(c)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${c}`),this.#n.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webhook",webhookId:c,method:u.method,title:t.title??u.name??Fb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return $hu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>PB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return sVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??PB(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:void 0,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??PB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??PB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??nJt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Yor(a)?r.apply(a):r,c=this.#m(n,u);c.length>0&&i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:c,title:Yor(a)?a.displayName??nJt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(a7i(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Hhu(t)}mergeEndpointPairs(t){return CXn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>PB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Jhu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[R_(r).toLowerCase()]=i,this.#e[`subpackage_${R_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Fb(a.baseUrl,PB(i.path))}`]=i,this.#r[`${n} ${Fb(a.baseUrl,K6e(i.path))}`]=i;let u=Whu(a);u!=null&&(this.#r[`${n} ${Fb(u,PB(i.path))}`]=i,this.#r[`${n} ${Fb(u,K6e(i.path))}`]=i)}),this.#r[`${i.method} ${PB(i.path)}`]=i,this.#r[`${i.method} ${K6e(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${PB(i.path)}`]=i,this.#n[`STREAM ${K6e(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function lVa({item:e,parentSlug:t}){return t.apply({urlSlug:CT(e.id.split(".").pop()??"")}).get()}var fVa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=c,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new Jhu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let l=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:l?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??CT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(b=>this.#w(b)),this.#m(this.#e,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>uVa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Do.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(yy)}#_(t,r){return Ghu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let c=t.slug??CT(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??nJt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(a7i(t.package,this.#t.subpackageLocators));let u=t.slug??CT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,c),s={id:this.#c.get(i??`${this.apiDefinitionId}:${CT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(b=>{let g=this.#t.getSubpackageByLocator(b);if(g==null){this.taskContext.logger.error(a7i(b,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:b}}).filter(b=>b!=null).filter(yy),c=u.map(b=>b.subpackageId);this.#o.set(a,c),u.forEach(b=>{this.#a.has(b.subpackageId)&&this.taskContext.logger.error(jon(b.locator)),this.#a.add(b.subpackageId)});let d=t.slug??CT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),l={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return c.forEach(b=>{this.#l.set(b,l)}),l}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(jon(t)),this.#a.add(a),this.#o.set(u,[a]);let c=CT(n.name),d=i.apply({urlSlug:c}),s={id:u,type:"apiPackage",children:[],title:n.displayName??nJt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let c=t.slug!=null?i.append(t.slug).get():lVa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??PB(n.path),slug:c,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??PB(a.path),slug:t.slug!=null?i.append(t.slug).get():lVa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Fb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():lVa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return $hu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>PB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return sVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${Pon(a.method,a.path)}. Got undefined.`);return}!this.#r.has(Hq.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(Hq.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(Hq.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)}),i}#g(t,r,i){let n=Do.V1.SlugGenerator.init(i.get()).apply({urlSlug:CT(r.name)}),a=this.#E(t,n),u={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??nJt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=lVa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:Hq.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??PB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:Hq.WebSocketId(t),title:r.displayName??PB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:Hq.WebhookId(t),method:r.method,title:r.displayName??nJt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,c])=>t===this.#e.id?c.id.split(".").length===1:c.id!=null&&c.id.includes(t)&&c.id!==t&&c.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t)));return{id:Hq.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(a7i(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Hhu(t)}mergeEndpointPairs(t){return CXn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>PB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var cX_=ui(require("crypto"),1);function WgM(e){return cX_.default.createHash("sha256").update(e).digest("hex")}var Khu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),WgM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Do.V1.NodeId(this.#n(t))}};function Yhu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Xhu=ui(NAe(),1);var U6c=ui(NAe(),1);function lX_({auth:e,ir:t,playgroundConfig:r,context:i}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix,description:e.docs};case"oauth":{let a=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(u=>u.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:U6c.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:U6c.FernRegistry.JqString(a),headerName:n.configuration.tokenHeader,tokenPrefix:n.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{n.tokenEndpoint.authenticatedRequestHeaders.length>1&&i.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let a=n.tokenEndpoint.authenticatedRequestHeaders.find(c=>c.headerName.toLowerCase()==="authorization");if(a)return a.responseProperty.propertyPath!=null&&a.responseProperty.propertyPath.length>0&&i.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:a.responseProperty.property.name.wireValue,description:e.docs};let u=n.tokenEndpoint.authenticatedRequestHeaders[0];return u?{type:"header",headerWireValue:u.headerName,prefix:u.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ao(n)}}}var Hm=ui(NAe(),1);var o7i=ui(NAe(),1);function dX_(e){return e._visit({alias:t=>({type:"alias",value:hM(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:g2(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>o7i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:o7i.FernRegistry.PropertyKey(r.name.wireValue),valueType:hM(r.valueType),availability:g2(r.availability),propertyAccess:r.propertyAccess})),extraProperties:GgM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:o7i.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g2(i.availability):void 0,additionalProperties:Hs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[o7i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:o7i.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:hM(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function hM(e){return e._visit({container:t=>Hs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:hM(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:hM(r),valueType:hM(i)}),optional:r=>({type:"optional",itemType:hM(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:hM(r)}),set:r=>({type:"set",itemType:hM(r)}),literal:r=>Hs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:o7i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Hs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>$gM(t.v2),float:()=>fX_(t.v2),double:()=>fX_(t.v2),string:()=>HgM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function HgM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function $gM(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 fX_(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 GgM(e){return typeof e=="boolean"?e?ol.unknown():void 0:typeof e=="string"?{type:"id",value:o7i.FernRegistry.TypeId(e),default:void 0}:hM(e)}function W6c(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?JgM(r,t):[],webhooks:i!=null?QgM(i):[],websockets:n!=null?[KgM(n,t)]:[],types:e.types.map(a=>Hm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>Hm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?Hm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function QgM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:Hm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??cZi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),payload:tOM(t.payload),examples:r}})}function JgM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.values(d).map(b=>b.response?.statusCode).filter((b,g,O)=>O.indexOf(b)!==g).length>0;for(let[b,g]of Object.entries(d))c=hX_({shouldUseExampleName:o,exampleName:g.displayName??b,example:g,irEndpoint:i}),c!=null&&a.push(c);let l=Object.values(s).map(b=>b.response?.statusCode).filter((b,g,O)=>O.indexOf(b)!==g).length>0;for(let[b,g]of Object.entries(s))c=hX_({shouldUseExampleName:l,exampleName:g.displayName??b,example:g,irEndpoint:i}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>V6c({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yy));else if(n!=null){let c=V6c({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=PQn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=V6c({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:g2(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:kgM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?YgM({environmentsConfig:t.environments,endpoint:i}):void 0,id:Hm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??cZi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...BXn(i.basePath),...BXn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...t.basePath!=null?BXn(t.basePath):[],...BXn(e.basePath),...BXn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),request:i.requestBody!=null?pX_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(pX_).filter(yy)},response:i.response!=null?_X_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(_X_).filter(yy)},errors:void 0,errorsV2:eOM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}})};r.push(u)}return r}function KgM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[Hm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:g2(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?XgM({environmentsConfig:t.environments,channel:e}):[],id:Hm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??cZi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.originalName),type:hM(i.valueType),availability:void 0})),parts:BXn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:hM(i.valueType),description:i.docs,availability:g2(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),messages:e.messages.map(i=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:rOM(i.body),description:i.docs,availability:g2(i.availability)})),examples:r}}function g2(e){if(e!=null)switch(e.status){case"DEPRECATED":return Hm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return Hm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return Hm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return Hm.FernRegistry.Availability.Beta;default:Ao(e.status)}}function YgM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(c=>{let d=c.urls[u];if(d==null)throw new Error(`Expected environment ${c.id} to contain url for ${u}`);return{id:Hm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,c,d)=>c===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:Ao(r)}}function XgM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:ZgM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ao(r)}}function ZgM(e,t){return e.replace(/^[^:]+/,t)}function kgM(e){return Hs.http.HttpMethod._visit(e,{get:()=>Hm.FernRegistry.HttpMethod.Get,post:()=>Hm.FernRegistry.HttpMethod.Post,put:()=>Hm.FernRegistry.HttpMethod.Put,patch:()=>Hm.FernRegistry.HttpMethod.Patch,delete:()=>Hm.FernRegistry.HttpMethod.Delete,head:()=>Hm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function BXn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:Hm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function pX_(e){let t=Hs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Iq.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>Hm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Iq.APPLICATION_JSON,shape:{type:"reference",value:hM(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:Hm.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:g2(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yy)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function _X_(e){if(e.body==null)return;let t,r=Hs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:hM(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function eOM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:hM(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:iOM(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:hM(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function hX_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Tw(r.request.requestBody)){let c=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=c[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let l=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:l}}},bodyProperty:s=>{if(s.style==="exploded"){let o=c[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:c[s.name.wireValue]}},_other:P3e})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yy)}}function V6c({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d=c.valueType.type==="container"&&c.valueType.container.type==="literal"?c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:c.name,value:{jsonExample:d,shape:Hs.ExampleTypeReferenceShape.primitive(Hs.ExamplePrimitive.string({original:d}))}}}).filter(yy),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[Hm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),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:c=>{if(a.request==null)return;let d={};if(Tw(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of c.properties)o._visit({file:l=>{let b=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(l.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[l.key.wireValue]={type:"filenames",value:g}}},bodyProperty:l=>{if(l.style==="exploded"){let b=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:P3e})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Hs.http.ExampleResponse._visit(a.response,{ok:c=>c._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: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(c=>LAe._visit(c,{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(yy)}}function tOM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:hM(e.payloadType)},description:e.docs};default:Ao(e)}}function rOM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:hM(e.bodyType)};default:Ao(e)}}function iOM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function Kee({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:W6c(e.rootPackage,e),auth:lX_({auth:e.auth,ir:e,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:g2(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:hM(a.valueType)})),navigation:void 0};for(let[a,u]of Object.entries(e.types))n.types[Xhu.FernRegistry.TypeId(a)]={description:u.docs??void 0,name:u.name.name.originalName,shape:dX_(u.shape),availability:g2(u.availability),displayName:u.name.displayName};for(let[a,u]of Object.entries(e.subpackages)){let c=u.service!=null?e.services[u.service]:void 0;n.subpackages[Xhu.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:Xhu.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??u.displayName,name:u.name.originalName,description:u.docs??void 0,...W6c(u,e)}}return n}var H6c=ui(NAe(),1);async function $6c({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let c=gx({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new vx(r,t)}),d=Nen({token:i.value}),s=Kee({ir:c,snippetsConfig:a,playgroundConfig:u,context:r}),o=await d.api.v1.register.registerApiDefinition({orgId:H6c.FernRegistry.OrgId(e),apiId:H6c.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:c};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 nOM=new fon({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function dVa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return IUa(TUa(Kee({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r,context:i}),h2.ApiDefinitionId(t),nOM))}var Bh={};Na(Bh,{AlgoliaSearchIndex:()=>yX_,ApiDefinitionId:()=>RX_,ApiId:()=>UX_,Availability:()=>rZ_,DocsConfigId:()=>VX_,EndpointId:()=>HX_,EndpointPathLiteral:()=>eZ_,EnvironmentId:()=>WX_,FileId:()=>KX_,HttpMethod:()=>tZ_,IndexSegmentId:()=>vX_,JqString:()=>XX_,OrgId:()=>FX_,PageId:()=>JX_,PayloadLocation:()=>AZ_,PropertyKey:()=>ZX_,PullRequestState:()=>wZ_,RoleId:()=>kX_,TokenId:()=>LX_,TypeId:()=>QX_,Url:()=>YX_,VersionId:()=>NX_,WebSocketId:()=>$X_,WebhookId:()=>GX_,algolia:()=>G6c,api:()=>rFc,commons:()=>iFc,diff:()=>iZ_,docs:()=>dFc,generators:()=>_Fc,git:()=>hFc,navigation:()=>bFc,sdks:()=>OFc,snippets:()=>EZ_,snippetsFactory:()=>MZ_,templates:()=>mFc,tokens:()=>qZ_});var G6c={};Na(G6c,{AlgoliaSearchIndex:()=>yX_,IndexSegmentId:()=>vX_});function yX_(e){return e}function vX_(e){return e}var rFc={};Na(rFc,{latest:()=>K6c,v1:()=>tFc});var K6c={};Na(K6c,{AuthSchemeId:()=>bX_,WebhookHttpMethod:()=>PX_,auth:()=>Q6c,commons:()=>gX_,endpoint:()=>OX_,type_:()=>mX_,webhook:()=>J6c,websocket:()=>jX_});var Q6c={};Na(Q6c,{AuthSchemeId:()=>bX_});function bX_(e){return e}var gX_={};var OX_={};var mX_={};var J6c={};Na(J6c,{WebhookHttpMethod:()=>PX_});var PX_={Get:"GET",Post:"POST"};var jX_={};var tFc={};Na(tFc,{SubpackageId:()=>BX_,WebSocketMessageId:()=>IX_,WebSocketMessageOrigin:()=>zX_,WebhookHttpMethod:()=>xX_,commons:()=>eFc,db:()=>Y6c,read:()=>Z6c,register:()=>k6c});var Y6c={};Na(Y6c,{endpoint:()=>wX_});var wX_={};var Z6c={};Na(Z6c,{SupportedLanguage:()=>SX_,endpoint:()=>X6c,type_:()=>DX_,webhook:()=>EX_,websocket:()=>MX_});var X6c={};Na(X6c,{SupportedLanguage:()=>SX_});var SX_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var DX_={};var EX_={};var MX_={};var k6c={};Na(k6c,{SourceId:()=>aOM,endpoint:()=>AX_,type_:()=>qX_,webhook:()=>TX_,websocket:()=>CX_});var AX_={};var qX_={};var TX_={};var CX_={};function aOM(e){return e}var eFc={};Na(eFc,{SubpackageId:()=>BX_,WebSocketMessageId:()=>IX_,WebSocketMessageOrigin:()=>zX_,WebhookHttpMethod:()=>xX_});function BX_(e){return e}function IX_(e){return e}var zX_={Client:"client",Server:"server"};var xX_={Get:"GET",Post:"POST"};var iFc={};Na(iFc,{ApiDefinitionId:()=>RX_,ApiId:()=>UX_,Availability:()=>rZ_,DocsConfigId:()=>VX_,EndpointId:()=>HX_,EndpointPathLiteral:()=>eZ_,EnvironmentId:()=>WX_,FileId:()=>KX_,HttpMethod:()=>tZ_,JqString:()=>XX_,OrgId:()=>FX_,PageId:()=>JX_,PropertyKey:()=>ZX_,RoleId:()=>kX_,TokenId:()=>LX_,TypeId:()=>QX_,Url:()=>YX_,VersionId:()=>NX_,WebSocketId:()=>$X_,WebhookId:()=>GX_});function RX_(e){return e}function NX_(e){return e}function FX_(e){return e}function LX_(e){return e}function UX_(e){return e}function VX_(e){return e}function WX_(e){return e}function HX_(e){return e}function $X_(e){return e}function GX_(e){return e}function QX_(e){return e}function JX_(e){return e}function KX_(e){return e}function YX_(e){return e}function XX_(e){return e}function ZX_(e){return e}function kX_(e){return e}function eZ_(e){return e}var tZ_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var rZ_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var iZ_={};var dFc={};Na(dFc,{latest:()=>oFc,v1:()=>lFc,v2:()=>fFc});var oFc={};Na(oFc,{Layout:()=>aZ_,MdxEngine:()=>oOM,TwitterCardSetting:()=>oZ_,commons:()=>nZ_,frontmatter:()=>nFc,seo:()=>aFc});var oOM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var nZ_={};var nFc={};Na(nFc,{Layout:()=>aZ_});var aZ_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var aFc={};Na(aFc,{TwitterCardSetting:()=>oZ_});var oZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var lFc={};Na(lFc,{commons:()=>cFc,db:()=>uZ_,read:()=>sZ_,write:()=>uFc});var uZ_={};var sZ_={};var uFc={};Na(uFc,{DocsRegistrationId:()=>sOM,FilePath:()=>uOM});function uOM(e){return e}function sOM(e){return e}var cFc={};Na(cFc,{ContentAlignment:()=>dZ_,FontDisplay:()=>vZ_,FontStyle:()=>yZ_,HeaderPosition:()=>pZ_,JsScriptStrategy:()=>hZ_,ProgrammingLanguage:()=>cZ_,SearchbarPlacement:()=>lZ_,TabsPlacement:()=>fZ_,TwitterCardSetting:()=>_Z_,commons:()=>sFc});var sFc={};Na(sFc,{ContentAlignment:()=>dZ_,FontDisplay:()=>vZ_,FontStyle:()=>yZ_,HeaderPosition:()=>pZ_,JsScriptStrategy:()=>hZ_,ProgrammingLanguage:()=>cZ_,SearchbarPlacement:()=>lZ_,TabsPlacement:()=>fZ_,TwitterCardSetting:()=>_Z_});var cZ_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var lZ_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var fZ_={Header:"HEADER",Sidebar:"SIDEBAR"};var dZ_={Center:"CENTER",Left:"LEFT"};var pZ_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var _Z_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var hZ_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var yZ_={Normal:"normal",Italic:"italic"};var vZ_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var fFc={};Na(fFc,{read:()=>bZ_,write:()=>gZ_});var bZ_={};var gZ_={};var _Fc={};Na(_Fc,{ChangelogEntryType:()=>mZ_,GeneratorId:()=>cOM,GeneratorLanguage:()=>lOM,ReleaseType:()=>PZ_,cli:()=>OZ_,commons:()=>pFc,versions:()=>jZ_});var OZ_={};var pFc={};Na(pFc,{ChangelogEntryType:()=>mZ_,ReleaseType:()=>PZ_});var mZ_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var PZ_={Ga:"GA",Rc:"RC"};var jZ_={};function cOM(e){return e}var lOM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var hFc={};Na(hFc,{PullRequestState:()=>wZ_});var wZ_={Open:"open",Closed:"closed",Merged:"merged"};var bFc={};Na(bFc,{latest:()=>yFc,v1:()=>vFc});var yFc={};Na(yFc,{NodeId:()=>pOM,ProductId:()=>_OM,Slug:()=>fOM,TabId:()=>dOM});function fOM(e){return e}function dOM(e){return e}function pOM(e){return e}function _OM(e){return e}var vFc={};Na(vFc,{NavigationV1Availability:()=>gOM,NodeId:()=>vOM,ProductId:()=>bOM,Slug:()=>hOM,TabId:()=>yOM});function hOM(e){return e}function yOM(e){return e}function vOM(e){return e}function bOM(e){return e}var gOM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var OFc={};Na(OFc,{Language:()=>SZ_,VersionBump:()=>DZ_,versions:()=>gFc});var gFc={};Na(gFc,{Language:()=>SZ_,VersionBump:()=>DZ_});var SZ_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var DZ_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var EZ_={};var MZ_={};var mFc={};Na(mFc,{PayloadLocation:()=>AZ_});var AZ_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var qZ_={};var IXn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function sp(e){return e!=null}var CZ_=ui(Z2n(),1);var TZ_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function Zor(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,CZ_.default)(e,{special:TZ_}).replace(/V\s(\d)/g,"V$1")}function Zhu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],c=Bh.api.v1.SubpackageId(u.join("."));r[c]={id:c,name:a,displayName:Zor(a)},n.push(a)})}),r}var khu=class{errors=new IXn},zXn=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function BZ_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var eyu=class extends khu{},A_=class extends zXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,c)=>u===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${BZ_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},X6=class extends A_{},rse=class extends X6{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var IZ_="x-fern-base-path",zZ_="x-fern-availability",tyu="x-fern-sdk-group-name",xZ_="x-fern-global-headers",RZ_="x-fern-sdk-method-name";var NZ_="x-fern-webhook",FZ_="x-fern-access-token-locator",LZ_="x-fern-basic",UZ_="x-fern-username-variable-name",VZ_="x-fern-password-variable-name",WZ_="x-fern-bearer",HZ_="x-fern-token-variable-name",$Z_="x-fern-header",GZ_="x-fern-header-variable-name",QZ_="x-fern-server-name",JZ_="x-fern-examples";var ryu=class extends A_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[QZ_]}convert(){if(this.serverName!=null)return this.serverName}};var iyu=class extends A_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Bh.EnvironmentId(t),baseUrl:this.url}}};function kor(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),u=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new iyu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function AD(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function R$(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(AD(n)&&(n=R$(n,t,r)),n)}function nyu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return AD(r)?R$(r,t,void 0):r}var _k_=ui(bx());var ayu=class extends A_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[LZ_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var oyu=class extends A_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[VZ_]}convert(){return this.passwordVariableName}};var uyu=class extends A_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[UZ_]}convert(){return this.usernameVariableName}};var syu=class extends A_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[WZ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var cyu=class extends A_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[HZ_]}convert(){return this.tokenVariableName}};function KZ_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var YZ_="x-bearer-format",XZ_="x-code-samples",ZZ_="x-codeSamples";var lyu=class extends A_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[YZ_]}convert(){return this.bearerFormat}};var fyu=class extends A_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[$Z_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var dyu=class extends A_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[GZ_]}convert(){return this.headerVariableName}};function kZ_(e){return e.type==="apiKey"}var xXn=class extends A_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){kZ_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function pyu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function _yu(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function hyu(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:u?c==='"'||c==="'"?a=c:c==="]"?(u=!1,t.push(n),n=""):n+=c:c==="["?(u=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function pVa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(Kpu(t))return r;let i=e[t];return i===void 0?pyu(t)?pVa(e,hyu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=_yu(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return OOM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),Kpu(t))return r;let i=e[t];return i===void 0?r:i}}}function OOM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||Kpu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function ek_(e){return function(t){return pVa(t,e)}}function tk_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function PFc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function rk_(e,t,r){return typeof r!="function"?RXn(e,t):jFc(e,t,function i(n,a,u,c,d,s){let o=r(n,a,u,c,d,s);return o!==void 0?!!o:jFc(n,a,i,s)},new Map)}function jFc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return mOM(e,t,r,i);case"function":return Object.keys(t).length>0?jFc(e,{...t},r,i):PFc(e,t);default:return tk_(e)?typeof t=="string"?t==="":!0:PFc(e,t)}}function mOM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return ik_(e,t,r,i);if(t instanceof Map)return POM(e,t,r,i);if(t instanceof Set)return jOM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i&&i.has(t))return i.get(t)===e;i&&i.set(t,e);try{for(let a=0;a<n.length;a++){let u=n[a];if(!Wpu(e)&&!(u in e)||t[u]===void 0&&e[u]!==void 0||t[u]===null&&e[u]!==null||!r(e[u],t[u],u,e,t,i))return!1}return!0}finally{i&&i.delete(t)}}function POM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let u=e.get(n);if(r(u,a,n,e,t,i)===!1)return!1}return!0}function ik_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let u=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],o=!1;if(r(s,u,a,e,t,i)&&(o=!0),o){n.add(d),c=!0;break}}if(!c)return!1}return!0}function jOM(e,t,r,i){return t.size===0?!0:e instanceof Set?ik_([...e],[...t],r,i):!1}function RXn(e,t){return rk_(e,t,()=>{})}function nk_(e){return e=qV_(e),t=>RXn(t,e)}function ak_(e,t){return AV_(e,(r,i,n,a)=>{let u=t?.(r,i,n,a);if(u!==void 0)return u;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case Gpu:case $pu:case Qpu:{let c=new e.constructor(e?.valueOf());return HNi(c,e),c}case Jpu:{let c={};return HNi(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function ok_(e){return ak_(e)}var wOM=/^(?:0|[1-9]\d*)$/;function uk_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return wOM.test(e)}}function sk_(e){return e!==null&&typeof e=="object"&&Hpu(e)==="[object Arguments]"}function ck_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&pyu(t)&&e?.[t]==null?r=hyu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||sk_(i))&&uk_(a)&&a<i.length))return!1;i=i[a]}return!0}function lk_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=_yu(e);break}}return t=ok_(t),function(r){let i=pVa(r,e);return i===void 0?ck_(r,e):t===void 0?i===void 0:RXn(i,t)}}function fk_(e){if(e==null)return uhu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?lk_(e[0],e[1]):nk_(e);case"string":case"symbol":case"number":return ek_(e)}}function wFc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(wFc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function yyu(e,t=uhu){return e==null?{}:I$(e,fk_(t))}function dk_(e){return typeof e!="string"&&(e=wFc(e)),e.replace(/['\u2019]/g,"")}function aJt(e){return CV_(dk_(e))}function pq(e){if(e!=null)return Array.isArray(e)?e:[e]}function vyu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${SOM(u)}${DOM(e)}.${EOM(i,n,a,c)}`}function SOM(e){return e?"webhook_":"endpoint_"}function DOM(e){return e!=null?pq(e)?.map(t=>aJt(t)).join("/"):""}function EOM(e,t,r,i){return e||t||aJt(r??"")||aJt(i??"")}function pk_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var byu=class extends A_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[FZ_],this.accessTokenLocator!=null&&(pk_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var gyu=class extends A_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new xXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=vyu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Bh.EndpointId(r),accessTokenLocator:Bh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var NXn=class extends A_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new uyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new syu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{KZ_(this.input)?(this.authScheme="header",this.headerAuthNode=new xXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new gyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new _k_.UnreachableCaseError(this.authScheme);return}}};var FXn=class extends A_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=nyu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new NXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(sp))}};var Oyu=class extends A_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[IZ_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function hk_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function yk_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function LXn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>pq(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!hk_(n))&&(u=yk_(u,u.type==="enum"?u.default:void 0)),{key:Bh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(sp)).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function myu(e,t){return AD(e)?R$(e,t,void 0):e}function u7i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function vk_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function bk_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var gk_=ui(bx());var SFc=["decimal","decimal128","double-int","double","float","sf-decimal"],DFc=["int16","int32","int64","int8","sf-integer","uint8"],EFc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],MFc=["beta","pre-release","in-development","generally-available","deprecated"];function Z6(e,t){return AD(e)?R$(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var X6e=class extends A_{availability;constructor(t){super(t),this.safeParse()}parse(){if(Z6(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[zZ_];r!=null&&(MFc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${MFc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Bh.Availability.Beta;case"in-development":return Bh.Availability.InDevelopment;case"generally-available":return Bh.Availability.GenerallyAvailable;case"deprecated":return Bh.Availability.Deprecated;case void 0:return;default:new gk_.UnreachableCaseError(this.availability);return}}};var jyu=ui(bx());function Ok_(e){return typeof e=="object"&&e!=null&&"language"in e}function mk_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Pk_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function jk_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Pyu(e){return typeof e=="object"&&e!=null&&"event"in e}function AFc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Pyu)}function s7i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function wk_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var wyu=class extends A_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[JZ_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return s7i(u)?[n,{type:"filenameWithData",filename:u.filename,data:Bh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(c=>s7i(c)))return[n,{type:"filenamesWithData",value:u.map(c=>({filename:c.filename,data:Bh.FileId(c.data)}))}];if(u.every(c=>typeof c=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new jyu.UnreachableCaseError(a.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=wk_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new jyu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Pk_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{AFc(r.response)&&(u={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!AFc(r.response)&&jk_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new jyu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Ok_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):mk_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,b])=>[Bh.PropertyKey(l),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,b])=>[Bh.PropertyKey(l),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([l,b])=>[Bh.PropertyKey(l),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:c}}))}};var _Va=class extends A_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[tyu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Bh.api.v1.SubpackageId(aJt(r)))}};var Syu=class extends A_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[RZ_]}convert(){return this.sdkMethodName}};var Dyu=class extends A_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[NZ_]}convert(){return this.isWebhook}};var Eyu=class extends A_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[XZ_]??[],...this.input[ZZ_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Bh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var won=ui(bx());function qFc(e,t){return AD(e)?R$(e,t,void 0):e}function Sk_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var RU="",eur=class extends A_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(s7i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>s7i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new won.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=qFc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=qFc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new won.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Pyu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new won.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return s7i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Bh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>s7i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Bh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new won.UnreachableCaseError(i.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new won.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new won.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,c])=>[u,c.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Sk_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Zor(this.name):this.summary!=null?Zor(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Dk_(e,t){return AD(e)?R$(e,t,void 0):e}var Fk_=ui(bx());var Ek_="#/components/schemas/";function UXn(e){if(e.$ref.startsWith(Ek_))return e.$ref.replace(Ek_,"")}function UPi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function c7i(e){return typeof e.type=="string"&&e.type==="array"}function Mk_(e){return e.type==="boolean"}function Ak_(e){return e.type==="integer"}function l7i(e){return!Array.isArray(e.type)&&!c7i(e)}function qk_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||l7i(t)||c7i(t))}function Tk_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ck_(e){return e.type==="null"}function Bk_(e){return e.type==="number"}function TFc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Ik_(e){return e.type==="string"}var Myu=class extends rse{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new $T({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return pq(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Ayu=class extends X6{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var qyu=class extends rse{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new $T({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(sp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>pq(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(sp).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(c=>[...u,c]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(UPi).filter(sp):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Tyu(e){return e!=null&&e.length>0?e:[void 0]}var VXn=class extends rse{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new $T({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(AD(t))return UXn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new $T({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(sp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return LXn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:pq(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(sp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Tyu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Bh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=Z6(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new $T({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var Cyu=class extends rse{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>Z6(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>Z6(t,this.context.document)?.type!=="null"?new $T({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(sp);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=Z6({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new $T({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(sp);return this.isNullable&&n!=null?n.map(UPi).filter(sp):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Bh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>pq(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??Zor(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(sp)).filter(sp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>pq(n.convert())?.map(u=>{if(u==null)return;t+=1;let c=u.type==="object"?Zor(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?Zor(u.value.id):c),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(sp)).filter(sp)}:void 0,i=this.isNullable?UPi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var Byu=class extends X6{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var f7i=class extends X6{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(AD(r)){let n=Z6(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(sp),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var zk_=ui(bx());function MOM(e){return DFc.includes(e)}var Iyu=class extends X6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(MOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${DFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new zk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var zyu=class extends X6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UPi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var xk_=ui(bx());function AOM(e){return SFc.includes(e)}var xyu=class extends X6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(AOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${SFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new xk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Rk_=ui(bx());function qOM(e){return EFc.includes(e)}var Ryu=class extends X6{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new Rk_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(qOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${EFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new f7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var Nk_=ui(bx());var Nyu=class extends X6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Nk_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Son=class extends rse{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=UXn(this.input);let t=Z6(this.input,this.context.document);t?.enum!=null&&l7i(t)&&(this.maybeEnumConverterNode=new f7i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Bh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=Z6(this.input,this.context.document);if(r!=null)return new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var $T=class e extends rse{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),l7i(this.input)&&Tk_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),AD(this.input)){let t=UXn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Son({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(qk_(this.input))this.typeShapeNode=new qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(l7i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new Cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(TFc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new VXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(l7i(this.input)&&this.input.enum!=null)this.typeShapeNode=new f7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":TFc(this.input)&&(this.typeShapeNode=new VXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":c7i(this.input)&&(this.typeShapeNode=new Myu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Mk_(this.input)&&(this.typeShapeNode=new Byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Ak_(this.input)&&(this.typeShapeNode=new Iyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Bk_(this.input)&&(this.typeShapeNode=new xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Ik_(this.input)&&(this.typeShapeNode=new Ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Ck_(this.input)&&(this.typeShapeNode=new zyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new Fk_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new VXn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Nyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!AD(this.input)&&(!c7i(this.input)&&this.input==null||c7i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=pq(t)?.map(i=>this.nullable?UPi(i):i).filter(sp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function d7i(e){if(e!=null)return LXn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(sp))}var tur=class extends X6{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;AD(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new X6e({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Dk_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function Lk_(e,t){return AD(e)?R$(e,t,void 0):e}var CFc=ui(bx());function Fyu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Bh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var Uk_=ui(sHs(),1),WXn=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=Uk_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function TOM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var HXn=class extends A_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),TOM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(AD(r)?n=nyu(r.$ref,this.context.document):n=r,n!=null)return[t,new NXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(sp)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Bh.api.latest.AuthSchemeId(t),i]}).filter(sp)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=pq(r.convert());return n==null?[t,void 0]:[Bh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>sp(r))):void 0}}};var Lyu=class extends $T{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=Z6(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${AD(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=Z6(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var Uyu=class extends A_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=Z6(this.input.schema,this.context.document);this.availability=new X6e({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=AD(this.input.schema)?new Son({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=WXn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Lyu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(sp))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[RU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[RU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:pq(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=aJt([this.method,this.path,this.contentType,"request"].join("_"));return Fyu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new CFc.UnreachableCaseError(n);return}}).filter(sp)}convert(){if(this.schema instanceof Son)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=pq(n.convert()),u=n.multipartType;return a?.map(c=>({type:u,key:Bh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new CFc.UnreachableCaseError(n.multipartType),[]}}).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var Vyu=class extends A_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Lk_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new Uyu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>pq(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(sp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>pq(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(sp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var Vk_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function Wk_(e,t){if(AD(e)){let r=R$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Wyu=ui(bx());var Hk_="application/json";var $k_="application/octet-stream";function Gk_(e,t){return e===t||t===RU||e===RU}var hVa=class extends A_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)Gk_(c,a)&&(i.add(c),this.examples?.push(new eur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,u7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,c]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new eur({input:{requestExample:o,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,u7i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new eur({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,u7i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new eur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,u7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[RU];if(a!=null)for(let u of a)this.examples?.push(new eur({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,u7i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=WXn.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=Hk_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=$k_,this.contentSubtype=Z6(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=yyu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[RU]??=[],r[RU]=[{value:this.input.example}]);let i=Z6(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=yyu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[RU]??=[],r[RU]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[RU]??=[],r[RU]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==RU).map(([d,s])=>[c,d,s]));let u=Object.entries(r).filter(([c,d])=>!n.has(c)&&sp(d)&&c!==RU);Object.keys(r).every(c=>c===RU)||this.matchExamplesByIndex(a,u),!n.has(RU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return pq(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Wyu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return pq(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=aJt([this.method,this.path,this.statusCode,"response"].join("_"));return Fyu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Wyu.UnreachableCaseError(i);return}}).filter(sp)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Wyu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var yVa=class extends A_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=Wk_(this.input,this.context.document);if(r==null){this.context.errors.error({message:AD(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new tur({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new hVa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new hVa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(sp)}};var Hyu=class extends A_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new yVa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new yVa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return Tyu(d7i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(c=>c.convert()).filter(sp))})))}).filter(sp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=pq(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??Vk_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(sp)})).filter(sp)})).filter(sp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var p7i=class extends A_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new eur({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,u7i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=kor(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(AD(i)){let a=myu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new Eyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Vyu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Hyu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new FXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new _Va({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new _Va({input:{[tyu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Syu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>vyu({namespace:pq(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(sp),this.xFernExamplesNode=new wyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(sp)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Bh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(sp),n=bk_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:vk_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Bh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:d7i(this.queryParameters)?.flat(),headers:d7i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(sp)}}).filter(sp);let a=this.servers?.map(o=>o.convert()).filter(sp),u=this.convertPathToPathParts();if(u==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(sp);return this.endpointIds.map((o,l)=>({id:Bh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(b=>Bh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:c?.map(b=>Bh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:d7i(this.pathParameters)?.flat(),queryParameters:d7i(this.queryParameters)?.flat(),requestHeaders:d7i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var $Xn=class extends A_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=kor(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new p7i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new p7i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new p7i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new p7i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new p7i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(sp)}};function $yu(e){return"payloads"in e}var Gyu=class extends A_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new $Xn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:kor(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(sp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{$yu(a)?r[Bh.WebhookId(a.id)]=a:t[Bh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Qyu=class extends A_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[xZ_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||myu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new tur({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return LXn(this.globalHeaders,this.requiredProperties)?.flat()}};function Qk_(e,t){if(AD(e)){let r=R$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Jyu=class extends A_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=Qk_(a,this.context.document);if(u!=null)return new $Xn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(sp)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{$yu(i)&&(t[Bh.WebhookId(i.id)]=i)}),t),{})}};var Kyu=class extends A_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=kor(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new FXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Gyu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Jyu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new HXn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yue(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=Zhu({endpoints:i,webhookEndpoints:n}),{types:u,auths:c}=this.components?.convert()??{};return{id:Bh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var GXn=class extends zXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function Z6e(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function oJt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(Z6e(n)&&(n=oJt(n,t,r)),n)}function Jk_(e,t){return Z6e(e)?oJt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var Zk_=ui(bx());function VPi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=VPi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VPi(t)):[VPi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return VPi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VPi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VPi(r));return t}}function vVa(e,t){return Z6e(e)?oJt(e,t,{name:"",schema:{type:"object"}}):e}function Kk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}function Yk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}function Xk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}var COM={key:Bh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},Yyu=class extends GXn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?vVa(this.method.result,this.context.openrpc):void 0,r=t?new $T({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(c=>vVa(c,this.context.openrpc)).filter(sp)?.map(c=>{let d=new $T({input:c.schema,context:this.context,accessPath:this.accessPath,pathId:["params",c.name],seenSchemas:new Set,nullable:void 0,schemaName:c.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:Bh.PropertyKey(c.name),valueShape:c.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:c.description,availability:void 0}}).filter(sp),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(c=>{let d=Yk_(c,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=Kk_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(sp))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(sp)??[];if(u.length<=0){let c=VPi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=vVa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:c},responseStatusCode:200,responseBody:{type:"json",value:VPi(vVa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:Bh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:Bh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[COM],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(sp):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(c=>c.convert()).filter(sp),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=Xk_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[Bh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=pq(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new Zk_.UnreachableCaseError(u);return}}).filter(sp)[0];if(n)return{statusCode:200,body:n,description:r}}};var bVa=class extends GXn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=kor(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=Jk_(t,this.context.openrpc);r!=null&&this.methods.push(new Yyu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new HXn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=yue(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(sp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=Zhu({endpoints:n});return{id:Bh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var gVa=class extends eyu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function OVa(e,t){if(e instanceof Por){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let r=new GQt(e.absoluteFilePath),i=await V6e({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let c={document:u.value,logger:t.logger,errors:new IXn,generatedTypes:{}},d=new Kyu({input:u.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=wHs(a,d.convert())}return a}var kk_=require("fs/promises");async function eeh(e,t){let r=await(0,kk_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new gVa({openrpc:i,logger:t.logger});return new bVa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function BOM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function IOM(e){return/^(https?:)?\/\//.test(e)}async function zOM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||IOM(e))return;let r=$v(t,za.of(e));if(await Cf(r))return r}async function QXn({iconPath:e,filepaths:t,docsWorkspace:r}){if(BOM(e)){let i=await zOM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function teh({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await BFc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function BFc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>mVa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await QXn({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>mVa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await mVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await BFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await mVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await BFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function mVa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>mVa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function reh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){ROM(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await IFc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await IFc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function IFc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await Ver(e,{alphabetized:Ko,api:Ko,apiName:Ko,audiences:Ko,displayErrors:Ko,snippets:Ko,summary:Ko,title:Ko,layout:Ko,icon:Ko,slug:Ko,hidden:Ko,skipSlug:Ko,paginated:Ko,playground:Ko,flattened:Ko,path:Ko,page:Ko,featureFlag:Ko,openrpc:Ko,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await IFc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Ko,orphaned:Ko}),xOM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function xOM(e){return e.api!=null}function ROM(e){return e[0]?.tab!=null}function Yee(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ieh.default.extend(neh.default);var NOM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Xyu=0,FOM=async({ir:e})=>(Xyu++,`${e.apiName.snakeCase.unsafeName}-${Xyu}`),LOM=async({api:e})=>(Xyu++,`${e.id}-${Xyu}`),uJt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,c=NOM,d=FOM,s=LOM){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=c,this.registerApi=d,this.registerApiV2=s}#e=Khu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await RZs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[za.of(o)]=l;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await reh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=IT(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents,this.rawMarkdownFiles[za.of(g)]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await oRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await aRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await teh({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=San(l,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[za.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=nRc(l,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let c={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,l])=>{let b=UOM(this.editThisPage,o),g=this.rawMarkdownFiles[za.of(o)];c[ZQt.PageId(o)]={markdown:l,editThisPageUrl:b?ZQt.Url(b):void 0,rawMarkdown:g}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async l=>{let b=$v(this.docsWorkspace.absoluteFilePath,l);(await(0,Zyu.stat)(b)).isDirectory()?(await $ae(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async l=>{let b=this.toRelativeFilepath(l),g=(await(0,Zyu.readFile)(l)).toString();return[b,g]})))}return{config:d,pages:c,jsFiles:s}}resolveFilepath(t){if(t!=null)return $v(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return IT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,zFc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,zFc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Do.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Do.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Do.isPage(n))return;let u=Do.getPageId(n);if(u==null)return;let c=Bu(this.docsWorkspace.absoluteFilePath,za.of(u));t[c]=a}),t}getDocsBasePath(){return new URL(Yee(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?ZQt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:ZQt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:ZQt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Do.V1.SlugGenerator.init(Do.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Do.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return _8n(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),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Do.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??CT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??CT(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ao(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Do.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??CT(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Do.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?VOM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild(n,c,i))),u=[];return a.forEach(c=>{if(c.type==="apiReference"){u.push(c);return}if(c.type==="section"&&!c.collapsed){u.push(c);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return _8n(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=$v(this.docsWorkspace.absoluteFilePath,za.of(t.openrpc));if(!await Cf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await eeh(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:Yhu(t.snippetsConfiguration)}),new fVa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=Yhu(t.snippetsConfiguration),O=await OVa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new fVa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=Yhu(t.snippetsConfiguration),a,u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),c=this.parsedDocsConfig.experimental?.openapiParserV3;if(c==null||c)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(a=gx({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new vx(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:u}),o=dVa({ir:a,apiDefinitionId:s,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new Qhu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Do.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=Do.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??CT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?Do.PageId(a):void 0,c=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??CT(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:c,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(l=>this.toNavigationChild(c,l,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return _8n(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Do.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??CT(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):ZQt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yy),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:ZQt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return _8n(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:ZQt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function UOM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${Yee(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function VOM(e){switch(e){case"beta":return Do.V1.NavigationV1Availability.Beta;case"deprecated":return Do.V1.NavigationV1Availability.Deprecated;case"ga":return Do.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Do.V1.NavigationV1Availability.Stable;default:Ao(e)}}async function N$(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof D3?t:null))).filter(yy)}async function xFc(e,t,r){if(e instanceof Por){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return Kee({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var blh=ui(FFc(),1),glh=ui(Avu(),1),Olh=ui(require("http"),1),mlh=ui(require("path"),1);var Inh=require("events"),Ivu=ui(require("fs"),1),Ion=ui(require("path"),1);var ynh=ui(require("os"),1),vnh=300,g7i=20,WVa=1e7,bnh=ynh.default.platform();var SEM=bnh==="darwin",z4c=bnh==="win32",O7i=SEM||z4c,gnh=3e3,Onh=2e4,x4c=1250;var aur;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(aur||(aur={}));var Bon;(function(e){e.CHANGE="change",e.RENAME="rename"})(Bon||(Bon={}));var HVa;(function(e){e.CHANGE="change",e.ERROR="error"})(HVa||(HVa={}));var F0;(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"})(F0||(F0={}));var kee;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(kee||(kee={}));var DEM=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,c,d=0,s=0,o=()=>{let E=Date.now(),C=E-d,z=E-s,G=C>=t||z>=a;return[E,G]},l=E=>{if(s=E,!u)return;let C=u;u=void 0,e.apply(void 0,C)},b=()=>{A(0)},g=()=>{c&&(b(),l(Date.now()))},O=E=>{if(s=E,i)return l(E)},m=E=>{if(n&&u)return l(E);u=void 0},P=()=>{c=void 0;let[E,C]=o();return C?m(E):D(E)},D=E=>{let C=E-d,z=E-s,G=t-C,I=a-z,N=Math.min(G,I);return A(N)},A=E=>{c&&clearTimeout(c),!(E<=0)&&(c=setTimeout(P,E))},M=(...E)=>{let[C,z]=o(),G=!!c;if(u=E,d=C,(z||!c)&&A(t),z)return G?l(C):O(C)};return M.cancel=b,M.flush=g,M},qvu=DEM;var L4c=ui(require("fs"),1),Cvu=ui(require("path"),1);var LM=ui(require("fs"),1),F$=require("util");var WPi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},our=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var R4c=ui(require("process"),1),mnh=R4c.default.getuid?!R4c.default.getuid():!1,Pnh=1e4,ase=()=>{};var $Va={isChangeErrorOk:e=>{if(!$Va.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mnh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!$Va.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(!$Va.isNodeError(e))throw e;if(!$Va.isChangeErrorOk(e))throw e}},k6=$Va;var N4c=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Pnh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},jnh=new N4c;var HPi=(e,t)=>function(i){return function n(...a){return jnh.schedule().then(u=>{let c=s=>(u(),s),d=s=>{if(u(),Date.now()>=i)throw s;if(t(s)){let o=Math.round(100*Math.random());return new Promise(b=>setTimeout(b,o)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},$Pi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var EEM={attempt:{chmod:WPi((0,F$.promisify)(LM.default.chmod),k6.onChangeError),chown:WPi((0,F$.promisify)(LM.default.chown),k6.onChangeError),close:WPi((0,F$.promisify)(LM.default.close),ase),fsync:WPi((0,F$.promisify)(LM.default.fsync),ase),mkdir:WPi((0,F$.promisify)(LM.default.mkdir),ase),realpath:WPi((0,F$.promisify)(LM.default.realpath),ase),stat:WPi((0,F$.promisify)(LM.default.stat),ase),unlink:WPi((0,F$.promisify)(LM.default.unlink),ase),chmodSync:our(LM.default.chmodSync,k6.onChangeError),chownSync:our(LM.default.chownSync,k6.onChangeError),closeSync:our(LM.default.closeSync,ase),existsSync:our(LM.default.existsSync,ase),fsyncSync:our(LM.default.fsync,ase),mkdirSync:our(LM.default.mkdirSync,ase),realpathSync:our(LM.default.realpathSync,ase),statSync:our(LM.default.statSync,ase),unlinkSync:our(LM.default.unlinkSync,ase)},retry:{close:HPi((0,F$.promisify)(LM.default.close),k6.isRetriableError),fsync:HPi((0,F$.promisify)(LM.default.fsync),k6.isRetriableError),open:HPi((0,F$.promisify)(LM.default.open),k6.isRetriableError),readFile:HPi((0,F$.promisify)(LM.default.readFile),k6.isRetriableError),rename:HPi((0,F$.promisify)(LM.default.rename),k6.isRetriableError),stat:HPi((0,F$.promisify)(LM.default.stat),k6.isRetriableError),write:HPi((0,F$.promisify)(LM.default.write),k6.isRetriableError),writeFile:HPi((0,F$.promisify)(LM.default.writeFile),k6.isRetriableError),closeSync:$Pi(LM.default.closeSync,k6.isRetriableError),fsyncSync:$Pi(LM.default.fsyncSync,k6.isRetriableError),openSync:$Pi(LM.default.openSync,k6.isRetriableError),readFileSync:$Pi(LM.default.readFileSync,k6.isRetriableError),renameSync:$Pi(LM.default.renameSync,k6.isRetriableError),statSync:$Pi(LM.default.statSync,k6.isRetriableError),writeSync:$Pi(LM.default.writeSync,k6.isRetriableError),writeFileSync:$Pi(LM.default.writeFileSync,k6.isRetriableError)}},wnh=EEM;var Tvu=ui(require("fs"),1),GVa=ui(require("path"),1);var F4c=()=>{};var MEM=()=>{let e=F4c,t=F4c,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=o=>(r=!0,d(o)),t=o=>(i=!0,s(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},Snh=MEM;var AEM=()=>{let{promise:e,resolve:t,isPending:r}=Snh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},Dnh=AEM;var Enh={then:e=>{e()}};var Mnh=e=>Array.isArray(e)?e:[e],Anh=e=>typeof e=="function";var qEM=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Mnh(a).map(De=>Anh(De)?De:Ae=>De.test(Ae)),c=De=>u.some(Ae=>Ae(De)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),o=[],l=new Set,b={},g=[],O=new Set,m={},P=[],D=new Set,A={},M={},E=new Set,C={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},z={directories:o,directoriesNames:l,directoriesNamesToPaths:b,files:g,filesNames:O,filesNamesToPaths:m,symlinks:P,symlinksNames:D,symlinksNamesToPaths:A,map:M},{promise:G,increment:I,decrement:N}=Dnh(),U=0,Y=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.directories.push(Ae),De.directoriesNames.add(Ct),o.push(Ae),l.add(Ct),b.propertyIsEnumerable(Ct)||(b[Ct]=[]),b[Ct].push(Ae),E.add(Ae),!(Pe>=i)&&(U>=n||me(Ae,Pe+1)))},J=(De,Ae,Ct)=>{E.has(Ae)||U>=n||(U+=1,De.files.push(Ae),De.filesNames.add(Ct),g.push(Ae),O.add(Ct),m.propertyIsEnumerable(Ct)||(m[Ct]=[]),m[Ct].push(Ae),E.add(Ae))},X=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.symlinks.push(Ae),De.symlinksNames.add(Ct),P.push(Ae),D.add(Ct),A.propertyIsEnumerable(Ct)||(A[Ct]=[]),A[Ct].push(Ae),E.add(Ae),r&&(Pe>=i||U>=n||Le(Ae,Pe+1)))},oe=(De,Ae,Ct,Pe,St)=>{d.aborted||c(Ae)||(Pe.isDirectory()?Y(De,Ae,Ct,St):Pe.isFile()?J(De,Ae,Ct):Pe.isSymbolicLink()&&X(De,Ae,Ct,St))},pe=(De,Ae,Ct,Pe)=>{if(d.aborted)return;let St=Ae===GVa.default.sep?"":GVa.default.sep,at=Ct.name,Oe=`${Ae}${St}${at}`;c(Oe)||(Ct.isDirectory()?Y(De,Oe,at,Pe):Ct.isFile()?J(De,Oe,at):Ct.isSymbolicLink()&&X(De,Oe,at,Pe))},de=(De,Ae,Ct,Pe)=>{for(let St=0,at=Ct.length;St<at;St++)pe(De,Ae,Ct[St],Pe)},me=(De,Ae)=>{d.aborted||Ae>i||U>=n||(I(),Tvu.default.readdir(De,{withFileTypes:!0},(Ct,Pe)=>{if(Ct||d.aborted||!Pe.length)return N();(s(Pe)||Enh).then(()=>{let at=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};de(at,De,Pe,Ae),N()})}))},Le=(De,Ae)=>{I(),Tvu.default.realpath(De,(Ct,Pe)=>{if(Ct||d.aborted)return N();Tvu.default.stat(Pe,(St,at)=>{if(St||d.aborted)return N();let Oe=GVa.default.basename(Pe),je=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};oe(je,Pe,Oe,at,Ae),N()})})};return(async(De,Ae=1)=>(De=GVa.default.normalize(De),E.add(De),me(De,Ae),await G,d.aborted?C:z))(e)},qnh=qEM;var uur={lang:{debounce:qvu,attempt:e=>{try{return e()}catch(t){return uur.lang.castError(t)}},castArray:e=>uur.lang.isArray(e)?e:[e],castError:e=>uur.lang.isError(e)?e:uur.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(uur.lang.isNaN(e))return uur.lang.isNaN(t);if(uur.lang.isPrimitive(e)||uur.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(Cvu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?L4c.default.realpathSync.native(e):L4c.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Cvu.default.sep&&t.length-e.length>Cvu.default.sep.length,poll:(e,t=Onh)=>wnh.retry.stat(t)(e,{bigint:!0}).catch(uur.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await qnh(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},sP=uur;var Bvu=ui(require("path"),1);var U4c=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||sP.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=vnh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...o]);this.onTargetEvents(l)},u=sP.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,c=r[u];return a===c||a===F0.CHANGE&&c===F0.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===F0.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===F0.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??g7i:Math.min(1,this.options.depth??g7i),u=this.options.limit??WVa,[c,d]=await sP.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())sP.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(F0.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!O7i&&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(F0.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(F0.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Bvu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Bvu.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(F0.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===F0.ADD?this.onTargetAdd(i):r===F0.ADD_DIR?this.onTargetAddDir(i):r===F0.CHANGE?this.onTargetChange(i):r===F0.UNLINK?this.onTargetUnlink(i):r===F0.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Bon.CHANGE,r){if(this.watcher.isClosed())return;let i=Bvu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){z4c&&t.code==="EPERM"?this.onWatcherChange(Bon.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(HVa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(HVa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Bon.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&O7i&&this.options.native!==!1?this.options.depth??g7i:Math.min(1,this.options.depth??g7i),i=this.options.limit??WVa,[n,a]=await sP.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Bon.CHANGE,c,t)}))}}},Tnh=U4c;var ete={interval:100,intervalId:void 0,fns:new Map,init:()=>{ete.intervalId||(ete.intervalId=setInterval(ete.resolve,ete.interval))},reset:()=>{ete.intervalId&&(clearInterval(ete.intervalId),delete ete.intervalId)},add:(e,t)=>{ete.fns.set(e,Date.now()+t),ete.init()},remove:e=>{ete.fns.delete(e)},resolve:()=>{if(!ete.fns.size)return ete.reset();let e=Date.now();for(let[t,r]of ete.fns)r>=e||(ete.remove(t),t())}},QVa=ete;var JVa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=x4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,b=>b!==n);if(l&&l!==n){if(sP.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{u.add.delete(i),QVa.remove(s)},s=()=>{d(),c()};QVa.add(s,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;d();let b=l();n===b?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,b,n)};u.add.set(i,o),o()}getLockUnlink(t,r=x4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{u.unlink.delete(i),QVa.remove(s)},s=()=>{d(),c()};QVa.add(s,r);let o=()=>(d(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,F0.ADD,aur.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,F0.ADD_DIR,aur.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK,aur.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK_DIR,aur.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};JVa.DIR_EVENTS={add:F0.ADD_DIR,rename:F0.RENAME_DIR,unlink:F0.UNLINK_DIR};JVa.FILE_EVENTS={add:F0.ADD,change:F0.CHANGE,rename:F0.RENAME,unlink:F0.UNLINK};var Cnh=JVa;var V4c=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(sP.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(sP.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return sP.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);sP.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},W4c=V4c;var H4c=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}},Bnh=H4c;var $4c=class{constructor(){this.inos={},this.paths=new W4c,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await sP.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Bnh(i)}reset(){this.inos={},this.paths=new W4c,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,F0.ADD,n),[F0.ADD];if(n.isDirectory())return this.updateIno(t,F0.ADD_DIR,n),[F0.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,F0.UNLINK,i),[F0.UNLINK];if(i.isDirectory())return this.updateIno(t,F0.UNLINK_DIR,i),[F0.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,F0.CHANGE,n),[F0.CHANGE]);if(n.isDirectory())return this.updateIno(t,F0.UNLINK,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK,F0.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD,n),[F0.UNLINK_DIR,F0.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK_DIR,F0.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?aur.FILE:aur.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},G4c=$4c;var Q4c=class e extends Inh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(kee.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(kee.CLOSE,n)),this._readyWait=new Promise(n=>this.on(kee.READY,n)),this._locker=new Cnh(this),this._roots=new Set,this._poller=new G4c,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(sP.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(kee.CLOSE))}error(t){if(this.isClosed())return!1;let r=sP.lang.castError(t);return this.emit(kee.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(kee.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(kee.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)sP.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new Tnh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=sP.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let u=Ion.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[u]?.find(o=>(c===1||o.options.recursive&&c<=(o.options.depth??g7i))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&O7i&&o.options.native!==!1)))return!0;if(!O7i)break;let s=Ion.default.dirname(t);if(u===s)break;u=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=sP.lang.uniq(t).sort();let u;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||O7i&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Ivu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||c)){let g={...r,ignoreInitial:!0,recursive:!1},O=Ion.default.dirname(c),m=c;await this.watchDirectories([O],g,i,m,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||O7i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??g7i,c=r.limit??WVa,[d]=await sP.fs.readdir(t,r.ignore,u,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let o=sP.fs.getDepth(t);for(let l of d){let b=sP.fs.getDepth(l),g=Math.max(0,u-(b-o)),O={...r,depth:g};await this.watchDirectories([l],O,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,o)=>{o===t&&(d(),i())},u=new e(a),c=()=>{this._subwatchers.add(n),this.on(kee.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(kee.CLOSE,d),u.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Ion.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new G4c,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return sP.lang.noop;if(this.pollerExists(t,r))return sP.lang.noop;let n={...r,interval:r.pollingInterval??gnh},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(kee.CLOSE,c),Ivu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(kee.CLOSE,c),Ivu.default.unwatchFile(t,i)};return sP.lang.attempt(u),()=>sP.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=sP.lang.uniq(t).sort(),t.every((a,u)=>t.every((c,d)=>d===u||!sP.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Ion.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await sP.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Ion.default.dirname(t);return(await sP.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=sP.lang.noop){if(sP.lang.isFunction(t))return this.watch([],{},t);if(sP.lang.isUndefined(t))return this.watch([],r,i);if(sP.lang.isFunction(r))return this.watch(t,{},r);if(sP.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=sP.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==sP.lang.noop&&this.on(kee.ALL,i),r.readdirMap=void 0,this.ready())}},zvu=Q4c;var KMM=ui(Aah(),1),YMM=ui(n2c(),1),XMM=ui(u2c(),1),iWa=ui(Qvu(),1),nWa=ui(Nah(),1);var kch=ui(wbu(),1),rte=require("fs/promises"),elh=require("os"),tlh=ui(Gk(),1),rlh=ui(Zch(),1),Ubu=process.platform==="win32",cCM="etag",lCM="preview",fCM="app-preview",dCM="bundle",pCM=".next",_CM="standalone",hCM=".fern",yCM="packages/fern-docs/bundle/.next/server/instrumentation.js",vCM=".npmrc",bCM=".pnpmfile.cjs",gCM="pnpm-workspace.yaml",OCM='Cannot find matching keyid: {"signatures":';function mCM(){return Bu($c.of((0,elh.homedir)()),za.of(hCM))}function Vbu({app:e=!1}){return Bu(mCM(),za.of(e?fCM:lCM))}function M7i({app:e=!1}){return Bu(Vbu({app:e}),za.of(e?pCM:dCM))}function wWa({app:e=!1}){return Bu(M7i({app:e}),za.of(_CM))}function PCM({app:e=!1}){return Bu(wWa({app:e}),za.of(yCM))}function jCM({app:e=!1}){return Bu(wWa({app:e}),za.of(gCM))}function wCM({app:e=!1}){return Bu(wWa({app:e}),za.of(bCM))}function SCM({app:e=!1}){return Bu(wWa({app:e}),za.of(vCM))}function $on(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function DCM({app:e=!1}){return Bu(Vbu({app:e}),za.of(cCM))}var ECM=`packages:
2331
+ ]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function jon(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function VgM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function CXn({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,c),o==null||o.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(o),b=c.isResponseStream?c:o,g=c.isResponseStream?o:c,O={id:Do.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[l]=O}),a}function $hu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return CXn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Xor(e,t){if(t!=null)return IT(e.absoluteFilePath,t)}function Ghu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let c=Do.V1.PageId(Xor(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??CT(t.title)});return{id:i.get(c),type:"page",pageId:c,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Qhu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=c,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#e=n7i.create(r,a),this.#c=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let l=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:l?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??CT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(b=>this.#j(b)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?n7i.getSubpackageId(r):void 0;return t.map(a=>uVa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Do.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(yy)}#p(t,r){return Ghu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=n7i.getSubpackageId(a),c=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(jon(t.package)),this.#a.add(u),this.#o.set(c,[u]);let d=t.slug??(Yor(a)?a.urlSlug:this.apiSection.slug??CT(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:c,type:"apiPackage",children:o,title:t.title??(Yor(a)?a.displayName??nJt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(a7i(t.package,this.#e.subpackageLocators));let u=t.slug??CT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,c);return{id:this.#c.get(i??`${this.apiDefinitionId}:${CT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),c=t.referencedSubpackages.map(l=>{let b=this.#e.getSubpackageByIdOrLocator(l),g=b!=null?n7i.getSubpackageId(b):void 0;if(g===void 0){this.taskContext.logger.error(a7i(l,this.#e.subpackageLocators));return}return{subpackageId:g,locator:l}}).filter(l=>l!=null).filter(yy);this.#o.set(u,c.map(l=>l.subpackageId)),c.forEach(l=>{this.#a.has(l.subpackageId)&&this.taskContext.logger.error(jon(l.locator)),this.#a.add(l.subpackageId)});let d=t.slug??CT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(R_(t));if(n!=null){let a=n7i.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(jon(t)),this.#a.add(a),this.#o.set(u,[a]);let c=Yor(n)?n.urlSlug:"",d=i.apply({urlSlug:c});return{id:u,type:"apiPackage",children:[],title:Yor(n)?n.displayName??nJt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.endpoints.get(h2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let c=this.#e.getEndpointId(n);if(c==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(c)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${c}`),this.#t.add(c);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"endpoint",method:n.method,endpointId:c,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??PB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webSockets.get(h2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let c=this.#e.getWebSocketId(a);if(c==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(c)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${c}`),this.#r.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webSocket",webSocketId:c,title:t.title??a.name??PB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webhooks.get(h2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Do.V1.WebhookId(t.endpoint));if(u!=null){let c=this.#e.getWebhookId(u);if(c==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(c)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${c}`),this.#n.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webhook",webhookId:c,method:u.method,title:t.title??u.name??Fb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return $hu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>PB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return sVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??PB(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:void 0,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??PB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??PB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??nJt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Yor(a)?r.apply(a):r,c=this.#m(n,u);c.length>0&&i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:c,title:Yor(a)?a.displayName??nJt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(a7i(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Hhu(t)}mergeEndpointPairs(t){return CXn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>PB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Jhu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[R_(r).toLowerCase()]=i,this.#e[`subpackage_${R_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Fb(a.baseUrl,PB(i.path))}`]=i,this.#r[`${n} ${Fb(a.baseUrl,K6e(i.path))}`]=i;let u=Whu(a);u!=null&&(this.#r[`${n} ${Fb(u,PB(i.path))}`]=i,this.#r[`${n} ${Fb(u,K6e(i.path))}`]=i)}),this.#r[`${i.method} ${PB(i.path)}`]=i,this.#r[`${i.method} ${K6e(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${PB(i.path)}`]=i,this.#n[`STREAM ${K6e(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function lVa({item:e,parentSlug:t}){return t.apply({urlSlug:CT(e.id.split(".").pop()??"")}).get()}var fVa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=c,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new Jhu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let l=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:l?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??CT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(b=>this.#w(b)),this.#m(this.#e,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>uVa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Do.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(yy)}#_(t,r){return Ghu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let c=t.slug??CT(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??nJt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(a7i(t.package,this.#t.subpackageLocators));let u=t.slug??CT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,c),s={id:this.#c.get(i??`${this.apiDefinitionId}:${CT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(Xor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(b=>{let g=this.#t.getSubpackageByLocator(b);if(g==null){this.taskContext.logger.error(a7i(b,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:b}}).filter(b=>b!=null).filter(yy),c=u.map(b=>b.subpackageId);this.#o.set(a,c),u.forEach(b=>{this.#a.has(b.subpackageId)&&this.taskContext.logger.error(jon(b.locator)),this.#a.add(b.subpackageId)});let d=t.slug??CT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),l={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return c.forEach(b=>{this.#l.set(b,l)}),l}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(jon(t)),this.#a.add(a),this.#o.set(u,[a]);let c=CT(n.name),d=i.apply({urlSlug:c}),s={id:u,type:"apiPackage",children:[],title:n.displayName??nJt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${Pon(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let c=t.slug!=null?i.append(t.slug).get():lVa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??PB(n.path),slug:c,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??PB(a.path),slug:t.slug!=null?i.append(t.slug).get():lVa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Fb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():lVa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return $hu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>PB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return sVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${Pon(a.method,a.path)}. Got undefined.`);return}!this.#r.has(Hq.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(Hq.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(Hq.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)}),i}#g(t,r,i){let n=Do.V1.SlugGenerator.init(i.get()).apply({urlSlug:CT(r.name)}),a=this.#E(t,n),u={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??nJt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=lVa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:Hq.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??PB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:Hq.WebSocketId(t),title:r.displayName??PB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:Hq.WebhookId(t),method:r.method,title:r.displayName??nJt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,c])=>t===this.#e.id?c.id.split(".").length===1:c.id!=null&&c.id.includes(t)&&c.id!==t&&c.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Hq.api.v1.SubpackageId(t)));return{id:Hq.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(a7i(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Hhu(t)}mergeEndpointPairs(t){return CXn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>PB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var cX_=ui(require("crypto"),1);function WgM(e){return cX_.default.createHash("sha256").update(e).digest("hex")}var Khu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),WgM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Do.V1.NodeId(this.#n(t))}};function Yhu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Xhu=ui(NAe(),1);var U6c=ui(NAe(),1);function lX_({auth:e,ir:t,playgroundConfig:r,context:i}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix,description:e.docs};case"oauth":{let a=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(u=>u.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:U6c.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:U6c.FernRegistry.JqString(a),headerName:n.configuration.tokenHeader,tokenPrefix:n.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{n.tokenEndpoint.authenticatedRequestHeaders.length>1&&i.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let a=n.tokenEndpoint.authenticatedRequestHeaders.find(c=>c.headerName.toLowerCase()==="authorization");if(a)return a.responseProperty.propertyPath!=null&&a.responseProperty.propertyPath.length>0&&i.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:a.responseProperty.property.name.wireValue,description:e.docs};let u=n.tokenEndpoint.authenticatedRequestHeaders[0];return u?{type:"header",headerWireValue:u.headerName,prefix:u.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ao(n)}}}var Hm=ui(NAe(),1);var o7i=ui(NAe(),1);function dX_(e){return e._visit({alias:t=>({type:"alias",value:hM(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:g2(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>o7i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:o7i.FernRegistry.PropertyKey(r.name.wireValue),valueType:hM(r.valueType),availability:g2(r.availability),propertyAccess:r.propertyAccess})),extraProperties:GgM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:o7i.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g2(i.availability):void 0,additionalProperties:Hs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[o7i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:o7i.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:hM(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function hM(e){return e._visit({container:t=>Hs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:hM(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:hM(r),valueType:hM(i)}),optional:r=>({type:"optional",itemType:hM(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:hM(r)}),set:r=>({type:"set",itemType:hM(r)}),literal:r=>Hs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:o7i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Hs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>$gM(t.v2),float:()=>fX_(t.v2),double:()=>fX_(t.v2),string:()=>HgM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function HgM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function $gM(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 fX_(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 GgM(e){return typeof e=="boolean"?e?ol.unknown():void 0:typeof e=="string"?{type:"id",value:o7i.FernRegistry.TypeId(e),default:void 0}:hM(e)}function W6c(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?JgM(r,t):[],webhooks:i!=null?QgM(i):[],websockets:n!=null?[KgM(n,t)]:[],types:e.types.map(a=>Hm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>Hm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?Hm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function QgM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:Hm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??cZi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),payload:tOM(t.payload),examples:r}})}function JgM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.values(d).map(b=>b.response?.statusCode).filter((b,g,O)=>O.indexOf(b)!==g).length>0;for(let[b,g]of Object.entries(d))c=hX_({shouldUseExampleName:o,exampleName:g.displayName??b,example:g,irEndpoint:i}),c!=null&&a.push(c);let l=Object.values(s).map(b=>b.response?.statusCode).filter((b,g,O)=>O.indexOf(b)!==g).length>0;for(let[b,g]of Object.entries(s))c=hX_({shouldUseExampleName:l,exampleName:g.displayName??b,example:g,irEndpoint:i}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>V6c({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yy));else if(n!=null){let c=V6c({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=PQn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=V6c({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:g2(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:kgM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?YgM({environmentsConfig:t.environments,endpoint:i}):void 0,id:Hm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??cZi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...BXn(i.basePath),...BXn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...t.basePath!=null?BXn(t.basePath):[],...BXn(e.basePath),...BXn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),request:i.requestBody!=null?pX_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(pX_).filter(yy)},response:i.response!=null?_X_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(_X_).filter(yy)},errors:void 0,errorsV2:eOM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}})};r.push(u)}return r}function KgM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[Hm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:g2(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?XgM({environmentsConfig:t.environments,channel:e}):[],id:Hm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??cZi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.originalName),type:hM(i.valueType),availability:void 0})),parts:BXn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:hM(i.valueType),description:i.docs,availability:g2(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),messages:e.messages.map(i=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:rOM(i.body),description:i.docs,availability:g2(i.availability)})),examples:r}}function g2(e){if(e!=null)switch(e.status){case"DEPRECATED":return Hm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return Hm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return Hm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return Hm.FernRegistry.Availability.Beta;default:Ao(e.status)}}function YgM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(c=>{let d=c.urls[u];if(d==null)throw new Error(`Expected environment ${c.id} to contain url for ${u}`);return{id:Hm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,c,d)=>c===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:Ao(r)}}function XgM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:ZgM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ao(r)}}function ZgM(e,t){return e.replace(/^[^:]+/,t)}function kgM(e){return Hs.http.HttpMethod._visit(e,{get:()=>Hm.FernRegistry.HttpMethod.Get,post:()=>Hm.FernRegistry.HttpMethod.Post,put:()=>Hm.FernRegistry.HttpMethod.Put,patch:()=>Hm.FernRegistry.HttpMethod.Patch,delete:()=>Hm.FernRegistry.HttpMethod.Delete,head:()=>Hm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function BXn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:Hm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function pX_(e){let t=Hs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Iq.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>Hm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Iq.APPLICATION_JSON,shape:{type:"reference",value:hM(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:Hm.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:g2(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yy)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function _X_(e){if(e.body==null)return;let t,r=Hs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:hM(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function eOM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:hM(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:iOM(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:hM(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function hX_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Tw(r.request.requestBody)){let c=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=c[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let l=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:l}}},bodyProperty:s=>{if(s.style==="exploded"){let o=c[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:c[s.name.wireValue]}},_other:P3e})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yy)}}function V6c({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d=c.valueType.type==="container"&&c.valueType.container.type==="literal"?c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:c.name,value:{jsonExample:d,shape:Hs.ExampleTypeReferenceShape.primitive(Hs.ExamplePrimitive.string({original:d}))}}}).filter(yy),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[Hm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),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:c=>{if(a.request==null)return;let d={};if(Tw(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of c.properties)o._visit({file:l=>{let b=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(l.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[l.key.wireValue]={type:"filenames",value:g}}},bodyProperty:l=>{if(l.style==="exploded"){let b=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:P3e})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Hs.http.ExampleResponse._visit(a.response,{ok:c=>c._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: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(c=>LAe._visit(c,{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(yy)}}function tOM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:hM(e.payloadType)},description:e.docs};default:Ao(e)}}function rOM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:hM(e.bodyType)};default:Ao(e)}}function iOM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function Kee({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:W6c(e.rootPackage,e),auth:lX_({auth:e.auth,ir:e,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:g2(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:hM(a.valueType)})),navigation:void 0};for(let[a,u]of Object.entries(e.types))n.types[Xhu.FernRegistry.TypeId(a)]={description:u.docs??void 0,name:u.name.name.originalName,shape:dX_(u.shape),availability:g2(u.availability),displayName:u.name.displayName};for(let[a,u]of Object.entries(e.subpackages)){let c=u.service!=null?e.services[u.service]:void 0;n.subpackages[Xhu.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:Xhu.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??u.displayName,name:u.name.originalName,description:u.docs??void 0,...W6c(u,e)}}return n}var H6c=ui(NAe(),1);async function $6c({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let c=gx({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new vx(r,t)}),d=Nen({token:i.value}),s=Kee({ir:c,snippetsConfig:a,playgroundConfig:u,context:r}),o=await d.api.v1.register.registerApiDefinition({orgId:H6c.FernRegistry.OrgId(e),apiId:H6c.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:c};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 nOM=new fon({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function dVa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return IUa(TUa(Kee({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r,context:i}),h2.ApiDefinitionId(t),nOM))}var Bh={};Na(Bh,{AlgoliaSearchIndex:()=>yX_,ApiDefinitionId:()=>RX_,ApiId:()=>UX_,Availability:()=>rZ_,DocsConfigId:()=>VX_,EndpointId:()=>HX_,EndpointPathLiteral:()=>eZ_,EnvironmentId:()=>WX_,FileId:()=>KX_,HttpMethod:()=>tZ_,IndexSegmentId:()=>vX_,JqString:()=>XX_,OrgId:()=>FX_,PageId:()=>JX_,PayloadLocation:()=>AZ_,PropertyKey:()=>ZX_,PullRequestState:()=>wZ_,RoleId:()=>kX_,TokenId:()=>LX_,TypeId:()=>QX_,Url:()=>YX_,VersionId:()=>NX_,WebSocketId:()=>$X_,WebhookId:()=>GX_,algolia:()=>G6c,api:()=>rFc,commons:()=>iFc,diff:()=>iZ_,docs:()=>dFc,generators:()=>_Fc,git:()=>hFc,navigation:()=>bFc,sdks:()=>OFc,snippets:()=>EZ_,snippetsFactory:()=>MZ_,templates:()=>mFc,tokens:()=>qZ_});var G6c={};Na(G6c,{AlgoliaSearchIndex:()=>yX_,IndexSegmentId:()=>vX_});function yX_(e){return e}function vX_(e){return e}var rFc={};Na(rFc,{latest:()=>K6c,v1:()=>tFc});var K6c={};Na(K6c,{AuthSchemeId:()=>bX_,WebhookHttpMethod:()=>PX_,auth:()=>Q6c,commons:()=>gX_,endpoint:()=>OX_,type_:()=>mX_,webhook:()=>J6c,websocket:()=>jX_});var Q6c={};Na(Q6c,{AuthSchemeId:()=>bX_});function bX_(e){return e}var gX_={};var OX_={};var mX_={};var J6c={};Na(J6c,{WebhookHttpMethod:()=>PX_});var PX_={Get:"GET",Post:"POST"};var jX_={};var tFc={};Na(tFc,{SubpackageId:()=>BX_,WebSocketMessageId:()=>IX_,WebSocketMessageOrigin:()=>zX_,WebhookHttpMethod:()=>xX_,commons:()=>eFc,db:()=>Y6c,read:()=>Z6c,register:()=>k6c});var Y6c={};Na(Y6c,{endpoint:()=>wX_});var wX_={};var Z6c={};Na(Z6c,{SupportedLanguage:()=>SX_,endpoint:()=>X6c,type_:()=>DX_,webhook:()=>EX_,websocket:()=>MX_});var X6c={};Na(X6c,{SupportedLanguage:()=>SX_});var SX_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var DX_={};var EX_={};var MX_={};var k6c={};Na(k6c,{SourceId:()=>aOM,endpoint:()=>AX_,type_:()=>qX_,webhook:()=>TX_,websocket:()=>CX_});var AX_={};var qX_={};var TX_={};var CX_={};function aOM(e){return e}var eFc={};Na(eFc,{SubpackageId:()=>BX_,WebSocketMessageId:()=>IX_,WebSocketMessageOrigin:()=>zX_,WebhookHttpMethod:()=>xX_});function BX_(e){return e}function IX_(e){return e}var zX_={Client:"client",Server:"server"};var xX_={Get:"GET",Post:"POST"};var iFc={};Na(iFc,{ApiDefinitionId:()=>RX_,ApiId:()=>UX_,Availability:()=>rZ_,DocsConfigId:()=>VX_,EndpointId:()=>HX_,EndpointPathLiteral:()=>eZ_,EnvironmentId:()=>WX_,FileId:()=>KX_,HttpMethod:()=>tZ_,JqString:()=>XX_,OrgId:()=>FX_,PageId:()=>JX_,PropertyKey:()=>ZX_,RoleId:()=>kX_,TokenId:()=>LX_,TypeId:()=>QX_,Url:()=>YX_,VersionId:()=>NX_,WebSocketId:()=>$X_,WebhookId:()=>GX_});function RX_(e){return e}function NX_(e){return e}function FX_(e){return e}function LX_(e){return e}function UX_(e){return e}function VX_(e){return e}function WX_(e){return e}function HX_(e){return e}function $X_(e){return e}function GX_(e){return e}function QX_(e){return e}function JX_(e){return e}function KX_(e){return e}function YX_(e){return e}function XX_(e){return e}function ZX_(e){return e}function kX_(e){return e}function eZ_(e){return e}var tZ_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var rZ_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var iZ_={};var dFc={};Na(dFc,{latest:()=>oFc,v1:()=>lFc,v2:()=>fFc});var oFc={};Na(oFc,{Layout:()=>aZ_,MdxEngine:()=>oOM,TwitterCardSetting:()=>oZ_,commons:()=>nZ_,frontmatter:()=>nFc,seo:()=>aFc});var oOM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var nZ_={};var nFc={};Na(nFc,{Layout:()=>aZ_});var aZ_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var aFc={};Na(aFc,{TwitterCardSetting:()=>oZ_});var oZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var lFc={};Na(lFc,{commons:()=>cFc,db:()=>uZ_,read:()=>sZ_,write:()=>uFc});var uZ_={};var sZ_={};var uFc={};Na(uFc,{DocsRegistrationId:()=>sOM,FilePath:()=>uOM});function uOM(e){return e}function sOM(e){return e}var cFc={};Na(cFc,{ContentAlignment:()=>dZ_,FontDisplay:()=>vZ_,FontStyle:()=>yZ_,HeaderPosition:()=>pZ_,JsScriptStrategy:()=>hZ_,ProgrammingLanguage:()=>cZ_,SearchbarPlacement:()=>lZ_,TabsPlacement:()=>fZ_,TwitterCardSetting:()=>_Z_,commons:()=>sFc});var sFc={};Na(sFc,{ContentAlignment:()=>dZ_,FontDisplay:()=>vZ_,FontStyle:()=>yZ_,HeaderPosition:()=>pZ_,JsScriptStrategy:()=>hZ_,ProgrammingLanguage:()=>cZ_,SearchbarPlacement:()=>lZ_,TabsPlacement:()=>fZ_,TwitterCardSetting:()=>_Z_});var cZ_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var lZ_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var fZ_={Header:"HEADER",Sidebar:"SIDEBAR"};var dZ_={Center:"CENTER",Left:"LEFT"};var pZ_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var _Z_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var hZ_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var yZ_={Normal:"normal",Italic:"italic"};var vZ_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var fFc={};Na(fFc,{read:()=>bZ_,write:()=>gZ_});var bZ_={};var gZ_={};var _Fc={};Na(_Fc,{ChangelogEntryType:()=>mZ_,GeneratorId:()=>cOM,GeneratorLanguage:()=>lOM,ReleaseType:()=>PZ_,cli:()=>OZ_,commons:()=>pFc,versions:()=>jZ_});var OZ_={};var pFc={};Na(pFc,{ChangelogEntryType:()=>mZ_,ReleaseType:()=>PZ_});var mZ_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var PZ_={Ga:"GA",Rc:"RC"};var jZ_={};function cOM(e){return e}var lOM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var hFc={};Na(hFc,{PullRequestState:()=>wZ_});var wZ_={Open:"open",Closed:"closed",Merged:"merged"};var bFc={};Na(bFc,{latest:()=>yFc,v1:()=>vFc});var yFc={};Na(yFc,{NodeId:()=>pOM,ProductId:()=>_OM,Slug:()=>fOM,TabId:()=>dOM});function fOM(e){return e}function dOM(e){return e}function pOM(e){return e}function _OM(e){return e}var vFc={};Na(vFc,{NavigationV1Availability:()=>gOM,NodeId:()=>vOM,ProductId:()=>bOM,Slug:()=>hOM,TabId:()=>yOM});function hOM(e){return e}function yOM(e){return e}function vOM(e){return e}function bOM(e){return e}var gOM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var OFc={};Na(OFc,{Language:()=>SZ_,VersionBump:()=>DZ_,versions:()=>gFc});var gFc={};Na(gFc,{Language:()=>SZ_,VersionBump:()=>DZ_});var SZ_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var DZ_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var EZ_={};var MZ_={};var mFc={};Na(mFc,{PayloadLocation:()=>AZ_});var AZ_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var qZ_={};var IXn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function sp(e){return e!=null}var CZ_=ui(Z2n(),1);var TZ_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function Zor(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,CZ_.default)(e,{special:TZ_}).replace(/V\s(\d)/g,"V$1")}function Zhu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],c=Bh.api.v1.SubpackageId(u.join("."));r[c]={id:c,name:a,displayName:Zor(a)},n.push(a)})}),r}var khu=class{errors=new IXn},zXn=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function BZ_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var eyu=class extends khu{},A_=class extends zXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,c)=>u===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${BZ_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},X6=class extends A_{},rse=class extends X6{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var IZ_="x-fern-base-path",zZ_="x-fern-availability",tyu="x-fern-sdk-group-name",xZ_="x-fern-global-headers",RZ_="x-fern-sdk-method-name";var NZ_="x-fern-webhook",FZ_="x-fern-access-token-locator",LZ_="x-fern-basic",UZ_="x-fern-username-variable-name",VZ_="x-fern-password-variable-name",WZ_="x-fern-bearer",HZ_="x-fern-token-variable-name",$Z_="x-fern-header",GZ_="x-fern-header-variable-name",QZ_="x-fern-server-name",JZ_="x-fern-examples";var ryu=class extends A_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[QZ_]}convert(){if(this.serverName!=null)return this.serverName}};var iyu=class extends A_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Bh.EnvironmentId(t),baseUrl:this.url}}};function kor(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),u=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new iyu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function AD(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function R$(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(AD(n)&&(n=R$(n,t,r)),n)}function nyu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return AD(r)?R$(r,t,void 0):r}var _k_=ui(bx());var ayu=class extends A_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[LZ_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var oyu=class extends A_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[VZ_]}convert(){return this.passwordVariableName}};var uyu=class extends A_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[UZ_]}convert(){return this.usernameVariableName}};var syu=class extends A_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[WZ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var cyu=class extends A_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[HZ_]}convert(){return this.tokenVariableName}};function KZ_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var YZ_="x-bearer-format",XZ_="x-code-samples",ZZ_="x-codeSamples";var lyu=class extends A_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[YZ_]}convert(){return this.bearerFormat}};var fyu=class extends A_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[$Z_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var dyu=class extends A_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[GZ_]}convert(){return this.headerVariableName}};function kZ_(e){return e.type==="apiKey"}var xXn=class extends A_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){kZ_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function pyu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function _yu(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function hyu(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:u?c==='"'||c==="'"?a=c:c==="]"?(u=!1,t.push(n),n=""):n+=c:c==="["?(u=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function pVa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(Kpu(t))return r;let i=e[t];return i===void 0?pyu(t)?pVa(e,hyu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=_yu(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return OOM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),Kpu(t))return r;let i=e[t];return i===void 0?r:i}}}function OOM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||Kpu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function ek_(e){return function(t){return pVa(t,e)}}function tk_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function PFc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function rk_(e,t,r){return typeof r!="function"?RXn(e,t):jFc(e,t,function i(n,a,u,c,d,s){let o=r(n,a,u,c,d,s);return o!==void 0?!!o:jFc(n,a,i,s)},new Map)}function jFc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return mOM(e,t,r,i);case"function":return Object.keys(t).length>0?jFc(e,{...t},r,i):PFc(e,t);default:return tk_(e)?typeof t=="string"?t==="":!0:PFc(e,t)}}function mOM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return ik_(e,t,r,i);if(t instanceof Map)return POM(e,t,r,i);if(t instanceof Set)return jOM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i&&i.has(t))return i.get(t)===e;i&&i.set(t,e);try{for(let a=0;a<n.length;a++){let u=n[a];if(!Wpu(e)&&!(u in e)||t[u]===void 0&&e[u]!==void 0||t[u]===null&&e[u]!==null||!r(e[u],t[u],u,e,t,i))return!1}return!0}finally{i&&i.delete(t)}}function POM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let u=e.get(n);if(r(u,a,n,e,t,i)===!1)return!1}return!0}function ik_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let u=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],o=!1;if(r(s,u,a,e,t,i)&&(o=!0),o){n.add(d),c=!0;break}}if(!c)return!1}return!0}function jOM(e,t,r,i){return t.size===0?!0:e instanceof Set?ik_([...e],[...t],r,i):!1}function RXn(e,t){return rk_(e,t,()=>{})}function nk_(e){return e=qV_(e),t=>RXn(t,e)}function ak_(e,t){return AV_(e,(r,i,n,a)=>{let u=t?.(r,i,n,a);if(u!==void 0)return u;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case Gpu:case $pu:case Qpu:{let c=new e.constructor(e?.valueOf());return HNi(c,e),c}case Jpu:{let c={};return HNi(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function ok_(e){return ak_(e)}var wOM=/^(?:0|[1-9]\d*)$/;function uk_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return wOM.test(e)}}function sk_(e){return e!==null&&typeof e=="object"&&Hpu(e)==="[object Arguments]"}function ck_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&pyu(t)&&e?.[t]==null?r=hyu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||sk_(i))&&uk_(a)&&a<i.length))return!1;i=i[a]}return!0}function lk_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=_yu(e);break}}return t=ok_(t),function(r){let i=pVa(r,e);return i===void 0?ck_(r,e):t===void 0?i===void 0:RXn(i,t)}}function fk_(e){if(e==null)return uhu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?lk_(e[0],e[1]):nk_(e);case"string":case"symbol":case"number":return ek_(e)}}function wFc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(wFc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function yyu(e,t=uhu){return e==null?{}:I$(e,fk_(t))}function dk_(e){return typeof e!="string"&&(e=wFc(e)),e.replace(/['\u2019]/g,"")}function aJt(e){return CV_(dk_(e))}function pq(e){if(e!=null)return Array.isArray(e)?e:[e]}function vyu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${SOM(u)}${DOM(e)}.${EOM(i,n,a,c)}`}function SOM(e){return e?"webhook_":"endpoint_"}function DOM(e){return e!=null?pq(e)?.map(t=>aJt(t)).join("/"):""}function EOM(e,t,r,i){return e||t||aJt(r??"")||aJt(i??"")}function pk_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var byu=class extends A_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[FZ_],this.accessTokenLocator!=null&&(pk_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var gyu=class extends A_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new xXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=vyu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Bh.EndpointId(r),accessTokenLocator:Bh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var NXn=class extends A_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new uyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new syu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{KZ_(this.input)?(this.authScheme="header",this.headerAuthNode=new xXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new gyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new _k_.UnreachableCaseError(this.authScheme);return}}};var FXn=class extends A_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=nyu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new NXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(sp))}};var Oyu=class extends A_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[IZ_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function hk_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function yk_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function LXn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>pq(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!hk_(n))&&(u=yk_(u,u.type==="enum"?u.default:void 0)),{key:Bh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(sp)).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function myu(e,t){return AD(e)?R$(e,t,void 0):e}function u7i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function vk_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function bk_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var gk_=ui(bx());var SFc=["decimal","decimal128","double-int","double","float","sf-decimal"],DFc=["int16","int32","int64","int8","sf-integer","uint8"],EFc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],MFc=["beta","pre-release","in-development","generally-available","deprecated"];function Z6(e,t){return AD(e)?R$(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var X6e=class extends A_{availability;constructor(t){super(t),this.safeParse()}parse(){if(Z6(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[zZ_];r!=null&&(MFc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${MFc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Bh.Availability.Beta;case"in-development":return Bh.Availability.InDevelopment;case"generally-available":return Bh.Availability.GenerallyAvailable;case"deprecated":return Bh.Availability.Deprecated;case void 0:return;default:new gk_.UnreachableCaseError(this.availability);return}}};var jyu=ui(bx());function Ok_(e){return typeof e=="object"&&e!=null&&"language"in e}function mk_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Pk_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function jk_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Pyu(e){return typeof e=="object"&&e!=null&&"event"in e}function AFc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Pyu)}function s7i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function wk_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var wyu=class extends A_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[JZ_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return s7i(u)?[n,{type:"filenameWithData",filename:u.filename,data:Bh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(c=>s7i(c)))return[n,{type:"filenamesWithData",value:u.map(c=>({filename:c.filename,data:Bh.FileId(c.data)}))}];if(u.every(c=>typeof c=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new jyu.UnreachableCaseError(a.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=wk_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new jyu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Pk_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{AFc(r.response)&&(u={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!AFc(r.response)&&jk_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new jyu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Ok_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):mk_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,b])=>[Bh.PropertyKey(l),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,b])=>[Bh.PropertyKey(l),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([l,b])=>[Bh.PropertyKey(l),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:c}}))}};var _Va=class extends A_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[tyu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Bh.api.v1.SubpackageId(aJt(r)))}};var Syu=class extends A_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[RZ_]}convert(){return this.sdkMethodName}};var Dyu=class extends A_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[NZ_]}convert(){return this.isWebhook}};var Eyu=class extends A_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[XZ_]??[],...this.input[ZZ_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Bh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var won=ui(bx());function qFc(e,t){return AD(e)?R$(e,t,void 0):e}function Sk_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var RU="",eur=class extends A_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(s7i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>s7i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new won.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=qFc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=qFc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new won.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Pyu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new won.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return s7i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Bh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>s7i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Bh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new won.UnreachableCaseError(i.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new won.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new won.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,c])=>[u,c.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Sk_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Zor(this.name):this.summary!=null?Zor(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Dk_(e,t){return AD(e)?R$(e,t,void 0):e}var Fk_=ui(bx());var Ek_="#/components/schemas/";function UXn(e){if(e.$ref.startsWith(Ek_))return e.$ref.replace(Ek_,"")}function UPi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function c7i(e){return typeof e.type=="string"&&e.type==="array"}function Mk_(e){return e.type==="boolean"}function Ak_(e){return e.type==="integer"}function l7i(e){return!Array.isArray(e.type)&&!c7i(e)}function qk_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||l7i(t)||c7i(t))}function Tk_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ck_(e){return e.type==="null"}function Bk_(e){return e.type==="number"}function TFc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Ik_(e){return e.type==="string"}var Myu=class extends rse{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new $T({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return pq(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Ayu=class extends X6{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var qyu=class extends rse{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new $T({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(sp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>pq(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(sp).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(c=>[...u,c]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(UPi).filter(sp):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Tyu(e){return e!=null&&e.length>0?e:[void 0]}var VXn=class extends rse{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new $T({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(AD(t))return UXn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new $T({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(sp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return LXn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:pq(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(sp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Tyu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Bh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=Z6(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new $T({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var Cyu=class extends rse{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>Z6(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>Z6(t,this.context.document)?.type!=="null"?new $T({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(sp);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=Z6({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new $T({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(sp);return this.isNullable&&n!=null?n.map(UPi).filter(sp):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Bh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>pq(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??Zor(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(sp)).filter(sp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>pq(n.convert())?.map(u=>{if(u==null)return;t+=1;let c=u.type==="object"?Zor(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?Zor(u.value.id):c),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(sp)).filter(sp)}:void 0,i=this.isNullable?UPi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var Byu=class extends X6{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var f7i=class extends X6{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(AD(r)){let n=Z6(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(sp),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var zk_=ui(bx());function MOM(e){return DFc.includes(e)}var Iyu=class extends X6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(MOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${DFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new zk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var zyu=class extends X6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UPi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var xk_=ui(bx());function AOM(e){return SFc.includes(e)}var xyu=class extends X6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(AOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${SFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new xk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Rk_=ui(bx());function qOM(e){return EFc.includes(e)}var Ryu=class extends X6{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new Rk_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(qOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${EFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new f7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var Nk_=ui(bx());var Nyu=class extends X6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Nk_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Son=class extends rse{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=UXn(this.input);let t=Z6(this.input,this.context.document);t?.enum!=null&&l7i(t)&&(this.maybeEnumConverterNode=new f7i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Bh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=Z6(this.input,this.context.document);if(r!=null)return new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var $T=class e extends rse{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),l7i(this.input)&&Tk_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),AD(this.input)){let t=UXn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Son({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(qk_(this.input))this.typeShapeNode=new qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(l7i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new Cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(TFc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new VXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(l7i(this.input)&&this.input.enum!=null)this.typeShapeNode=new f7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":TFc(this.input)&&(this.typeShapeNode=new VXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":c7i(this.input)&&(this.typeShapeNode=new Myu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Mk_(this.input)&&(this.typeShapeNode=new Byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Ak_(this.input)&&(this.typeShapeNode=new Iyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Bk_(this.input)&&(this.typeShapeNode=new xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Ik_(this.input)&&(this.typeShapeNode=new Ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Ck_(this.input)&&(this.typeShapeNode=new zyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new Fk_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new VXn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Nyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!AD(this.input)&&(!c7i(this.input)&&this.input==null||c7i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=pq(t)?.map(i=>this.nullable?UPi(i):i).filter(sp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function d7i(e){if(e!=null)return LXn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(sp))}var tur=class extends X6{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;AD(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new X6e({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Dk_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function Lk_(e,t){return AD(e)?R$(e,t,void 0):e}var CFc=ui(bx());function Fyu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Bh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var Uk_=ui(sHs(),1),WXn=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=Uk_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function TOM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var HXn=class extends A_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new $T({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),TOM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(AD(r)?n=nyu(r.$ref,this.context.document):n=r,n!=null)return[t,new NXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(sp)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Bh.api.latest.AuthSchemeId(t),i]}).filter(sp)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=pq(r.convert());return n==null?[t,void 0]:[Bh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>sp(r))):void 0}}};var Lyu=class extends $T{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=Z6(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${AD(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=Z6(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var Uyu=class extends A_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=Z6(this.input.schema,this.context.document);this.availability=new X6e({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=AD(this.input.schema)?new Son({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=WXn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Lyu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(sp))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[RU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[RU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:pq(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=aJt([this.method,this.path,this.contentType,"request"].join("_"));return Fyu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new CFc.UnreachableCaseError(n);return}}).filter(sp)}convert(){if(this.schema instanceof Son)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=pq(n.convert()),u=n.multipartType;return a?.map(c=>({type:u,key:Bh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new CFc.UnreachableCaseError(n.multipartType),[]}}).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var Vyu=class extends A_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Lk_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new Uyu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>pq(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(sp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>pq(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(sp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var Vk_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function Wk_(e,t){if(AD(e)){let r=R$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Wyu=ui(bx());var Hk_="application/json";var $k_="application/octet-stream";function Gk_(e,t){return e===t||t===RU||e===RU}var hVa=class extends A_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)Gk_(c,a)&&(i.add(c),this.examples?.push(new eur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,u7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,c]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new eur({input:{requestExample:o,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,u7i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new eur({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,u7i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new eur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,u7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[RU];if(a!=null)for(let u of a)this.examples?.push(new eur({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,u7i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=WXn.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=Hk_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=$k_,this.contentSubtype=Z6(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new $T({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=yyu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[RU]??=[],r[RU]=[{value:this.input.example}]);let i=Z6(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=yyu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[RU]??=[],r[RU]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[RU]??=[],r[RU]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==RU).map(([d,s])=>[c,d,s]));let u=Object.entries(r).filter(([c,d])=>!n.has(c)&&sp(d)&&c!==RU);Object.keys(r).every(c=>c===RU)||this.matchExamplesByIndex(a,u),!n.has(RU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return pq(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Wyu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return pq(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=aJt([this.method,this.path,this.statusCode,"response"].join("_"));return Fyu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Wyu.UnreachableCaseError(i);return}}).filter(sp)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Wyu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var yVa=class extends A_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=Wk_(this.input,this.context.document);if(r==null){this.context.errors.error({message:AD(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new tur({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new hVa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new hVa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(sp)}};var Hyu=class extends A_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new yVa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new yVa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return Tyu(d7i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(c=>c.convert()).filter(sp))})))}).filter(sp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=pq(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??Vk_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(sp)})).filter(sp)})).filter(sp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var p7i=class extends A_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new eur({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,u7i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new X6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=kor(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(AD(i)){let a=myu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new tur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new Eyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Vyu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Hyu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new FXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new _Va({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new _Va({input:{[tyu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Syu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>vyu({namespace:pq(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(sp),this.xFernExamplesNode=new wyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(sp)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Bh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(sp),n=bk_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:vk_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Bh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:d7i(this.queryParameters)?.flat(),headers:d7i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(sp)}}).filter(sp);let a=this.servers?.map(o=>o.convert()).filter(sp),u=this.convertPathToPathParts();if(u==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(sp);return this.endpointIds.map((o,l)=>({id:Bh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(b=>Bh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:c?.map(b=>Bh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:d7i(this.pathParameters)?.flat(),queryParameters:d7i(this.queryParameters)?.flat(),requestHeaders:d7i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var $Xn=class extends A_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=kor(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new p7i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new p7i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new p7i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new p7i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new p7i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(sp)}};function $yu(e){return"payloads"in e}var Gyu=class extends A_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new $Xn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:kor(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(sp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{$yu(a)?r[Bh.WebhookId(a.id)]=a:t[Bh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Qyu=class extends A_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[xZ_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||myu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new tur({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return LXn(this.globalHeaders,this.requiredProperties)?.flat()}};function Qk_(e,t){if(AD(e)){let r=R$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Jyu=class extends A_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=Qk_(a,this.context.document);if(u!=null)return new $Xn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(sp)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{$yu(i)&&(t[Bh.WebhookId(i.id)]=i)}),t),{})}};var Kyu=class extends A_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=kor(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new FXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Gyu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Jyu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new HXn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yue(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=Zhu({endpoints:i,webhookEndpoints:n}),{types:u,auths:c}=this.components?.convert()??{};return{id:Bh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var GXn=class extends zXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function Z6e(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function oJt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(Z6e(n)&&(n=oJt(n,t,r)),n)}function Jk_(e,t){return Z6e(e)?oJt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var Zk_=ui(bx());function VPi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=VPi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VPi(t)):[VPi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return VPi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VPi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VPi(r));return t}}function vVa(e,t){return Z6e(e)?oJt(e,t,{name:"",schema:{type:"object"}}):e}function Kk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}function Yk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}function Xk_(e,t){return Z6e(e)?oJt(e,t,void 0):e}var COM={key:Bh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},Yyu=class extends GXn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?vVa(this.method.result,this.context.openrpc):void 0,r=t?new $T({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(c=>vVa(c,this.context.openrpc)).filter(sp)?.map(c=>{let d=new $T({input:c.schema,context:this.context,accessPath:this.accessPath,pathId:["params",c.name],seenSchemas:new Set,nullable:void 0,schemaName:c.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:Bh.PropertyKey(c.name),valueShape:c.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:c.description,availability:void 0}}).filter(sp),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(c=>{let d=Yk_(c,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=Kk_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(sp))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(sp)??[];if(u.length<=0){let c=VPi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=vVa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:c},responseStatusCode:200,responseBody:{type:"json",value:VPi(vVa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:Bh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:Bh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[COM],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(sp):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(c=>c.convert()).filter(sp),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=Xk_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[Bh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=pq(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new Zk_.UnreachableCaseError(u);return}}).filter(sp)[0];if(n)return{statusCode:200,body:n,description:r}}};var bVa=class extends GXn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=kor(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=Jk_(t,this.context.openrpc);r!=null&&this.methods.push(new Yyu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new HXn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=yue(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(sp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=Zhu({endpoints:n});return{id:Bh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var gVa=class extends eyu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function OVa(e,t){if(e instanceof Por){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let r=new GQt(e.absoluteFilePath),i=await V6e({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let c={document:u.value,logger:t.logger,errors:new IXn,generatedTypes:{}},d=new Kyu({input:u.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=wHs(a,d.convert())}return a}var kk_=require("fs/promises");async function eeh(e,t){let r=await(0,kk_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new gVa({openrpc:i,logger:t.logger});return new bVa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function BOM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function IOM(e){return/^(https?:)?\/\//.test(e)}async function zOM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||IOM(e))return;let r=$v(t,za.of(e));if(await Cf(r))return r}async function QXn({iconPath:e,filepaths:t,docsWorkspace:r}){if(BOM(e)){let i=await zOM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function teh({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await BFc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function BFc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>mVa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await QXn({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>mVa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await mVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await BFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await mVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await BFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function mVa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>mVa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await QXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function reh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){ROM(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await IFc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await IFc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function IFc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await Ver(e,{alphabetized:Ko,api:Ko,apiName:Ko,audiences:Ko,displayErrors:Ko,snippets:Ko,summary:Ko,title:Ko,layout:Ko,icon:Ko,slug:Ko,hidden:Ko,skipSlug:Ko,paginated:Ko,playground:Ko,flattened:Ko,path:Ko,page:Ko,featureFlag:Ko,openrpc:Ko,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await IFc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Ko,orphaned:Ko}),xOM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function xOM(e){return e.api!=null}function ROM(e){return e[0]?.tab!=null}function Yee(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ieh.default.extend(neh.default);var NOM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Xyu=0,FOM=async({ir:e})=>(Xyu++,`${e.apiName.snakeCase.unsafeName}-${Xyu}`),LOM=async({api:e})=>(Xyu++,`${e.id}-${Xyu}`),uJt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,c=NOM,d=FOM,s=LOM){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=c,this.registerApi=d,this.registerApiV2=s}#e=Khu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await RZs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[za.of(o)]=l;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await reh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=IT(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents,this.rawMarkdownFiles[za.of(g)]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await oRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await aRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await teh({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=San(l,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[za.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=nRc(l,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let c={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,l])=>{let b=UOM(this.editThisPage,o),g=this.rawMarkdownFiles[za.of(o)];c[ZQt.PageId(o)]={markdown:l,editThisPageUrl:b?ZQt.Url(b):void 0,rawMarkdown:g}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async l=>{let b=$v(this.docsWorkspace.absoluteFilePath,l);(await(0,Zyu.stat)(b)).isDirectory()?(await $ae(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async l=>{let b=this.toRelativeFilepath(l),g=(await(0,Zyu.readFile)(l)).toString();return[b,g]})))}return{config:d,pages:c,jsFiles:s}}resolveFilepath(t){if(t!=null)return $v(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return IT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,zFc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,zFc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Do.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Do.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Do.isPage(n))return;let u=Do.getPageId(n);if(u==null)return;let c=Bu(this.docsWorkspace.absoluteFilePath,za.of(u));t[c]=a}),t}getDocsBasePath(){return new URL(Yee(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?ZQt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:ZQt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:ZQt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Do.V1.SlugGenerator.init(Do.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Do.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return _8n(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),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Do.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??CT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??CT(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ao(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Do.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??CT(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Do.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?VOM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild(n,c,i))),u=[];return a.forEach(c=>{if(c.type==="apiReference"){u.push(c);return}if(c.type==="section"&&!c.collapsed){u.push(c);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return _8n(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=$v(this.docsWorkspace.absoluteFilePath,za.of(t.openrpc));if(!await Cf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await eeh(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:Yhu(t.snippetsConfiguration)}),new fVa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=Yhu(t.snippetsConfiguration),O=await OVa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new fVa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=Yhu(t.snippetsConfiguration),a,u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),c=this.parsedDocsConfig.experimental?.openapiParserV3;if(c==null||c)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(a=gx({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new vx(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:u}),o=dVa({ir:a,apiDefinitionId:s,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new Qhu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Do.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=Do.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??CT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?Do.PageId(a):void 0,c=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??CT(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:c,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(l=>this.toNavigationChild(c,l,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return _8n(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new FPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Do.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??CT(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):ZQt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yy),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:ZQt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return _8n(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:ZQt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function UOM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${Yee(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function VOM(e){switch(e){case"beta":return Do.V1.NavigationV1Availability.Beta;case"deprecated":return Do.V1.NavigationV1Availability.Deprecated;case"ga":return Do.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Do.V1.NavigationV1Availability.Stable;default:Ao(e)}}async function N$(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof D3?t:null))).filter(yy)}async function xFc(e,t,r){if(e instanceof Por){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return Kee({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var blh=ui(FFc(),1),glh=ui(Avu(),1),Olh=ui(require("http"),1),mlh=ui(require("path"),1);var Inh=require("events"),Ivu=ui(require("fs"),1),Ion=ui(require("path"),1);var ynh=ui(require("os"),1),vnh=300,g7i=20,WVa=1e7,bnh=ynh.default.platform();var SEM=bnh==="darwin",z4c=bnh==="win32",O7i=SEM||z4c,gnh=3e3,Onh=2e4,x4c=1250;var aur;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(aur||(aur={}));var Bon;(function(e){e.CHANGE="change",e.RENAME="rename"})(Bon||(Bon={}));var HVa;(function(e){e.CHANGE="change",e.ERROR="error"})(HVa||(HVa={}));var F0;(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"})(F0||(F0={}));var kee;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(kee||(kee={}));var DEM=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,c,d=0,s=0,o=()=>{let E=Date.now(),C=E-d,z=E-s,G=C>=t||z>=a;return[E,G]},l=E=>{if(s=E,!u)return;let C=u;u=void 0,e.apply(void 0,C)},b=()=>{A(0)},g=()=>{c&&(b(),l(Date.now()))},O=E=>{if(s=E,i)return l(E)},m=E=>{if(n&&u)return l(E);u=void 0},P=()=>{c=void 0;let[E,C]=o();return C?m(E):D(E)},D=E=>{let C=E-d,z=E-s,G=t-C,I=a-z,N=Math.min(G,I);return A(N)},A=E=>{c&&clearTimeout(c),!(E<=0)&&(c=setTimeout(P,E))},M=(...E)=>{let[C,z]=o(),G=!!c;if(u=E,d=C,(z||!c)&&A(t),z)return G?l(C):O(C)};return M.cancel=b,M.flush=g,M},qvu=DEM;var L4c=ui(require("fs"),1),Cvu=ui(require("path"),1);var LM=ui(require("fs"),1),F$=require("util");var WPi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},our=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var R4c=ui(require("process"),1),mnh=R4c.default.getuid?!R4c.default.getuid():!1,Pnh=1e4,ase=()=>{};var $Va={isChangeErrorOk:e=>{if(!$Va.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mnh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!$Va.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(!$Va.isNodeError(e))throw e;if(!$Va.isChangeErrorOk(e))throw e}},k6=$Va;var N4c=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Pnh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},jnh=new N4c;var HPi=(e,t)=>function(i){return function n(...a){return jnh.schedule().then(u=>{let c=s=>(u(),s),d=s=>{if(u(),Date.now()>=i)throw s;if(t(s)){let o=Math.round(100*Math.random());return new Promise(b=>setTimeout(b,o)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},$Pi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var EEM={attempt:{chmod:WPi((0,F$.promisify)(LM.default.chmod),k6.onChangeError),chown:WPi((0,F$.promisify)(LM.default.chown),k6.onChangeError),close:WPi((0,F$.promisify)(LM.default.close),ase),fsync:WPi((0,F$.promisify)(LM.default.fsync),ase),mkdir:WPi((0,F$.promisify)(LM.default.mkdir),ase),realpath:WPi((0,F$.promisify)(LM.default.realpath),ase),stat:WPi((0,F$.promisify)(LM.default.stat),ase),unlink:WPi((0,F$.promisify)(LM.default.unlink),ase),chmodSync:our(LM.default.chmodSync,k6.onChangeError),chownSync:our(LM.default.chownSync,k6.onChangeError),closeSync:our(LM.default.closeSync,ase),existsSync:our(LM.default.existsSync,ase),fsyncSync:our(LM.default.fsync,ase),mkdirSync:our(LM.default.mkdirSync,ase),realpathSync:our(LM.default.realpathSync,ase),statSync:our(LM.default.statSync,ase),unlinkSync:our(LM.default.unlinkSync,ase)},retry:{close:HPi((0,F$.promisify)(LM.default.close),k6.isRetriableError),fsync:HPi((0,F$.promisify)(LM.default.fsync),k6.isRetriableError),open:HPi((0,F$.promisify)(LM.default.open),k6.isRetriableError),readFile:HPi((0,F$.promisify)(LM.default.readFile),k6.isRetriableError),rename:HPi((0,F$.promisify)(LM.default.rename),k6.isRetriableError),stat:HPi((0,F$.promisify)(LM.default.stat),k6.isRetriableError),write:HPi((0,F$.promisify)(LM.default.write),k6.isRetriableError),writeFile:HPi((0,F$.promisify)(LM.default.writeFile),k6.isRetriableError),closeSync:$Pi(LM.default.closeSync,k6.isRetriableError),fsyncSync:$Pi(LM.default.fsyncSync,k6.isRetriableError),openSync:$Pi(LM.default.openSync,k6.isRetriableError),readFileSync:$Pi(LM.default.readFileSync,k6.isRetriableError),renameSync:$Pi(LM.default.renameSync,k6.isRetriableError),statSync:$Pi(LM.default.statSync,k6.isRetriableError),writeSync:$Pi(LM.default.writeSync,k6.isRetriableError),writeFileSync:$Pi(LM.default.writeFileSync,k6.isRetriableError)}},wnh=EEM;var Tvu=ui(require("fs"),1),GVa=ui(require("path"),1);var F4c=()=>{};var MEM=()=>{let e=F4c,t=F4c,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=o=>(r=!0,d(o)),t=o=>(i=!0,s(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},Snh=MEM;var AEM=()=>{let{promise:e,resolve:t,isPending:r}=Snh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},Dnh=AEM;var Enh={then:e=>{e()}};var Mnh=e=>Array.isArray(e)?e:[e],Anh=e=>typeof e=="function";var qEM=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Mnh(a).map(De=>Anh(De)?De:Ae=>De.test(Ae)),c=De=>u.some(Ae=>Ae(De)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),o=[],l=new Set,b={},g=[],O=new Set,m={},P=[],D=new Set,A={},M={},E=new Set,C={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},z={directories:o,directoriesNames:l,directoriesNamesToPaths:b,files:g,filesNames:O,filesNamesToPaths:m,symlinks:P,symlinksNames:D,symlinksNamesToPaths:A,map:M},{promise:G,increment:I,decrement:N}=Dnh(),U=0,Y=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.directories.push(Ae),De.directoriesNames.add(Ct),o.push(Ae),l.add(Ct),b.propertyIsEnumerable(Ct)||(b[Ct]=[]),b[Ct].push(Ae),E.add(Ae),!(Pe>=i)&&(U>=n||me(Ae,Pe+1)))},J=(De,Ae,Ct)=>{E.has(Ae)||U>=n||(U+=1,De.files.push(Ae),De.filesNames.add(Ct),g.push(Ae),O.add(Ct),m.propertyIsEnumerable(Ct)||(m[Ct]=[]),m[Ct].push(Ae),E.add(Ae))},X=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.symlinks.push(Ae),De.symlinksNames.add(Ct),P.push(Ae),D.add(Ct),A.propertyIsEnumerable(Ct)||(A[Ct]=[]),A[Ct].push(Ae),E.add(Ae),r&&(Pe>=i||U>=n||Le(Ae,Pe+1)))},oe=(De,Ae,Ct,Pe,St)=>{d.aborted||c(Ae)||(Pe.isDirectory()?Y(De,Ae,Ct,St):Pe.isFile()?J(De,Ae,Ct):Pe.isSymbolicLink()&&X(De,Ae,Ct,St))},pe=(De,Ae,Ct,Pe)=>{if(d.aborted)return;let St=Ae===GVa.default.sep?"":GVa.default.sep,at=Ct.name,Oe=`${Ae}${St}${at}`;c(Oe)||(Ct.isDirectory()?Y(De,Oe,at,Pe):Ct.isFile()?J(De,Oe,at):Ct.isSymbolicLink()&&X(De,Oe,at,Pe))},de=(De,Ae,Ct,Pe)=>{for(let St=0,at=Ct.length;St<at;St++)pe(De,Ae,Ct[St],Pe)},me=(De,Ae)=>{d.aborted||Ae>i||U>=n||(I(),Tvu.default.readdir(De,{withFileTypes:!0},(Ct,Pe)=>{if(Ct||d.aborted||!Pe.length)return N();(s(Pe)||Enh).then(()=>{let at=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};de(at,De,Pe,Ae),N()})}))},Le=(De,Ae)=>{I(),Tvu.default.realpath(De,(Ct,Pe)=>{if(Ct||d.aborted)return N();Tvu.default.stat(Pe,(St,at)=>{if(St||d.aborted)return N();let Oe=GVa.default.basename(Pe),je=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};oe(je,Pe,Oe,at,Ae),N()})})};return(async(De,Ae=1)=>(De=GVa.default.normalize(De),E.add(De),me(De,Ae),await G,d.aborted?C:z))(e)},qnh=qEM;var uur={lang:{debounce:qvu,attempt:e=>{try{return e()}catch(t){return uur.lang.castError(t)}},castArray:e=>uur.lang.isArray(e)?e:[e],castError:e=>uur.lang.isError(e)?e:uur.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(uur.lang.isNaN(e))return uur.lang.isNaN(t);if(uur.lang.isPrimitive(e)||uur.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(Cvu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?L4c.default.realpathSync.native(e):L4c.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Cvu.default.sep&&t.length-e.length>Cvu.default.sep.length,poll:(e,t=Onh)=>wnh.retry.stat(t)(e,{bigint:!0}).catch(uur.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await qnh(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},sP=uur;var Bvu=ui(require("path"),1);var U4c=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||sP.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=vnh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...o]);this.onTargetEvents(l)},u=sP.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,c=r[u];return a===c||a===F0.CHANGE&&c===F0.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===F0.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===F0.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??g7i:Math.min(1,this.options.depth??g7i),u=this.options.limit??WVa,[c,d]=await sP.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())sP.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(F0.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!O7i&&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(F0.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(F0.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Bvu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Bvu.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(F0.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===F0.ADD?this.onTargetAdd(i):r===F0.ADD_DIR?this.onTargetAddDir(i):r===F0.CHANGE?this.onTargetChange(i):r===F0.UNLINK?this.onTargetUnlink(i):r===F0.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Bon.CHANGE,r){if(this.watcher.isClosed())return;let i=Bvu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){z4c&&t.code==="EPERM"?this.onWatcherChange(Bon.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(HVa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(HVa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Bon.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&O7i&&this.options.native!==!1?this.options.depth??g7i:Math.min(1,this.options.depth??g7i),i=this.options.limit??WVa,[n,a]=await sP.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Bon.CHANGE,c,t)}))}}},Tnh=U4c;var ete={interval:100,intervalId:void 0,fns:new Map,init:()=>{ete.intervalId||(ete.intervalId=setInterval(ete.resolve,ete.interval))},reset:()=>{ete.intervalId&&(clearInterval(ete.intervalId),delete ete.intervalId)},add:(e,t)=>{ete.fns.set(e,Date.now()+t),ete.init()},remove:e=>{ete.fns.delete(e)},resolve:()=>{if(!ete.fns.size)return ete.reset();let e=Date.now();for(let[t,r]of ete.fns)r>=e||(ete.remove(t),t())}},QVa=ete;var JVa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=x4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,b=>b!==n);if(l&&l!==n){if(sP.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{u.add.delete(i),QVa.remove(s)},s=()=>{d(),c()};QVa.add(s,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;d();let b=l();n===b?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,b,n)};u.add.set(i,o),o()}getLockUnlink(t,r=x4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{u.unlink.delete(i),QVa.remove(s)},s=()=>{d(),c()};QVa.add(s,r);let o=()=>(d(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,F0.ADD,aur.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,F0.ADD_DIR,aur.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK,aur.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK_DIR,aur.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};JVa.DIR_EVENTS={add:F0.ADD_DIR,rename:F0.RENAME_DIR,unlink:F0.UNLINK_DIR};JVa.FILE_EVENTS={add:F0.ADD,change:F0.CHANGE,rename:F0.RENAME,unlink:F0.UNLINK};var Cnh=JVa;var V4c=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(sP.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(sP.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return sP.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);sP.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},W4c=V4c;var H4c=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}},Bnh=H4c;var $4c=class{constructor(){this.inos={},this.paths=new W4c,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await sP.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Bnh(i)}reset(){this.inos={},this.paths=new W4c,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,F0.ADD,n),[F0.ADD];if(n.isDirectory())return this.updateIno(t,F0.ADD_DIR,n),[F0.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,F0.UNLINK,i),[F0.UNLINK];if(i.isDirectory())return this.updateIno(t,F0.UNLINK_DIR,i),[F0.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,F0.CHANGE,n),[F0.CHANGE]);if(n.isDirectory())return this.updateIno(t,F0.UNLINK,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK,F0.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD,n),[F0.UNLINK_DIR,F0.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK_DIR,F0.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?aur.FILE:aur.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},G4c=$4c;var Q4c=class e extends Inh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(kee.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(kee.CLOSE,n)),this._readyWait=new Promise(n=>this.on(kee.READY,n)),this._locker=new Cnh(this),this._roots=new Set,this._poller=new G4c,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(sP.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(kee.CLOSE))}error(t){if(this.isClosed())return!1;let r=sP.lang.castError(t);return this.emit(kee.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(kee.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(kee.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)sP.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new Tnh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=sP.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let u=Ion.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[u]?.find(o=>(c===1||o.options.recursive&&c<=(o.options.depth??g7i))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&O7i&&o.options.native!==!1)))return!0;if(!O7i)break;let s=Ion.default.dirname(t);if(u===s)break;u=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=sP.lang.uniq(t).sort();let u;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||O7i&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Ivu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||c)){let g={...r,ignoreInitial:!0,recursive:!1},O=Ion.default.dirname(c),m=c;await this.watchDirectories([O],g,i,m,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||O7i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??g7i,c=r.limit??WVa,[d]=await sP.fs.readdir(t,r.ignore,u,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let o=sP.fs.getDepth(t);for(let l of d){let b=sP.fs.getDepth(l),g=Math.max(0,u-(b-o)),O={...r,depth:g};await this.watchDirectories([l],O,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,o)=>{o===t&&(d(),i())},u=new e(a),c=()=>{this._subwatchers.add(n),this.on(kee.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(kee.CLOSE,d),u.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Ion.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new G4c,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return sP.lang.noop;if(this.pollerExists(t,r))return sP.lang.noop;let n={...r,interval:r.pollingInterval??gnh},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(kee.CLOSE,c),Ivu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(kee.CLOSE,c),Ivu.default.unwatchFile(t,i)};return sP.lang.attempt(u),()=>sP.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=sP.lang.uniq(t).sort(),t.every((a,u)=>t.every((c,d)=>d===u||!sP.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Ion.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await sP.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Ion.default.dirname(t);return(await sP.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=sP.lang.noop){if(sP.lang.isFunction(t))return this.watch([],{},t);if(sP.lang.isUndefined(t))return this.watch([],r,i);if(sP.lang.isFunction(r))return this.watch(t,{},r);if(sP.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=sP.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==sP.lang.noop&&this.on(kee.ALL,i),r.readdirMap=void 0,this.ready())}},zvu=Q4c;var KMM=ui(Aah(),1),YMM=ui(n2c(),1),XMM=ui(u2c(),1),iWa=ui(Qvu(),1),nWa=ui(Nah(),1);var kch=ui(wbu(),1),rte=require("fs/promises"),elh=require("os"),tlh=ui(Gk(),1),rlh=ui(Zch(),1),Ubu=process.platform==="win32",cCM="etag",lCM="preview",fCM="app-preview",dCM="bundle",pCM=".next",_CM="standalone",hCM=".fern",yCM="packages/fern-docs/bundle/.next/server/instrumentation.js",vCM=".npmrc",bCM=".pnpmfile.cjs",gCM="pnpm-workspace.yaml",OCM='Cannot find matching keyid: {"signatures":';function mCM(){return Bu($c.of((0,elh.homedir)()),za.of(hCM))}function Vbu({app:e=!1}){return Bu(mCM(),za.of(e?fCM:lCM))}function M7i({app:e=!1}){return Bu(Vbu({app:e}),za.of(e?pCM:dCM))}function wWa({app:e=!1}){return Bu(M7i({app:e}),za.of(_CM))}function PCM({app:e=!1}){return Bu(wWa({app:e}),za.of(yCM))}function jCM({app:e=!1}){return Bu(wWa({app:e}),za.of(gCM))}function wCM({app:e=!1}){return Bu(wWa({app:e}),za.of(bCM))}function SCM({app:e=!1}){return Bu(wWa({app:e}),za.of(vCM))}function $on(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function DCM({app:e=!1}){return Bu(Vbu({app:e}),za.of(cCM))}var ECM=`packages:
2332
2332
  - "packages/**"
2333
2333
  - "!**/dist"
2334
2334
  `,MCM=`module.exports = {
@@ -2392,11 +2392,11 @@ More information: https://mdxjs.com/docs/troubleshooting-mdx`);return n.stack=""
2392
2392
  ${o}
2393
2393
  ${l}`)}async function kzM(e){await yx(void 0,"docker",["pull",e],{all:!0,doNotPipeOutput:!0})}var B7i=ui(require("path"),1),Kon="/fern",j5c="output",w5c="config.json",S5c="ir.json",exM="snippet.json",txM="snippet-templates.json",rxM="generators",ixM="sources",I0u=B7i.default.join(Kon,j5c),NWa=B7i.default.join(Kon,w5c),z0u=B7i.default.join(Kon,S5c),x0u=B7i.default.join(Kon,exM),R0u=B7i.default.join(Kon,txM),VNL=B7i.default.join(Kon,rxM),_ph=B7i.default.join(Kon,ixM),N0u="9229";var FWa=class{dockerImage;keepDocker;constructor({dockerImage:t,keepDocker:r}){this.dockerImage=t,this.keepDocker=r}async execute({generatorName:t,irPath:r,configPath:i,outputPath:n,snippetPath:a,snippetTemplatePath:u,context:c,inspect:d,runner:s}){c.logger.info(`Executing generator ${t} using Docker image: ${this.dockerImage}`);let o=[`${i}:${NWa}:ro`,`${r}:${z0u}:ro`,`${n}:${I0u}`];a&&o.push(`${a}:${x0u}`),u&&o.push(`${u}:${R0u}`);let l={},b={};d&&(l.NODE_OPTIONS=`--inspect-brk=0.0.0.0:${N0u}`,b[N0u]=N0u),await P5c({logger:c.logger,imageName:this.dockerImage,args:[NWa],binds:o,envVars:l,ports:b,removeAfterCompletion:!this.keepDocker,runner:s})}};var Pbw=ui(od(),1),YIn=require("fs/promises"),mwa=require("path"),jbw=ui(Gk(),1);var I0h=ui(JO(),1),P2=ui(T0h(),1),uTe=ui(WC(),1),z0h=ui(require("fs"),1),cji=ui(require("path"),1),b2M="0.0.1";function g2M(e,t){if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let r=e.raw.github;if(r.license!=null){if(typeof r.license=="string"){if(r.license==="MIT"||r.license==="Apache-2.0")return P2.FernGeneratorExec.LicenseConfig.basic({id:r.license==="MIT"?P2.FernGeneratorExec.LicenseId.Mit:P2.FernGeneratorExec.LicenseId.Apache2})}else if(typeof r.license=="object"&&"custom"in r.license)return P2.FernGeneratorExec.LicenseConfig.custom({filename:cji.basename(r.license.custom)})}}if(e.raw?.metadata?.license!=null){let r=e.raw.metadata.license;if(typeof r=="string"){if(r==="MIT"||r==="Apache-2.0")return P2.FernGeneratorExec.LicenseConfig.basic({id:r==="MIT"?P2.FernGeneratorExec.LicenseId.Mit:P2.FernGeneratorExec.LicenseId.Apache2})}else if(typeof r=="object"&&"custom"in r)return P2.FernGeneratorExec.LicenseConfig.custom({filename:cji.basename(r.custom)})}}function C0h(e){return e!=null?I0h.GithubPublishInfo._visit(e,{npm:t=>P2.FernGeneratorExec.GithubPublishInfo.npm({registryUrl:t.registryUrl,packageName:t.packageName,tokenEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.token??"")}),maven:t=>P2.FernGeneratorExec.GithubPublishInfo.maven({registryUrl:t.registryUrl,coordinate:t.coordinate,usernameEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.credentials?.username??""),passwordEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.credentials?.password??""),signature:t.signature!=null?{keyIdEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.signature.keyId??""),passwordEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.signature.password??""),secretKeyEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.signature.secretKey??"")}:void 0}),pypi:t=>P2.FernGeneratorExec.GithubPublishInfo.pypi({registryUrl:t.registryUrl,packageName:t.packageName,usernameEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.credentials?.username??""),passwordEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.credentials?.password??"")}),rubygems:t=>P2.FernGeneratorExec.GithubPublishInfo.rubygems({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.apiKey??"")}),postman:t=>P2.FernGeneratorExec.GithubPublishInfo.postman({apiKeyEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.apiKey??""),workspaceIdEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.workspaceId??"")}),nuget:t=>P2.FernGeneratorExec.GithubPublishInfo.nuget({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,uTe.EnvironmentVariable)(t.apiKey??"")}),_other:()=>{}}):void 0}function x0h({generatorInvocation:e,customConfig:t,workspaceName:r,organization:i,outputVersion:n=b2M,absolutePathToSnippet:a,absolutePathToSnippetTemplates:u,absolutePathToFernConfig:c,writeUnitTests:d,generateOauthClients:s,generatePaginatedClients:o,paths:l}){let b=t,g=g2M(e,c);if(g!=null&&g.type==="custom"){let M;if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let E=e.raw.github;if(E.license!=null&&typeof E.license=="object"&&"custom"in E.license){let C=E.license.custom;try{let z=c?cji.dirname(c):process.cwd(),G=cji.isAbsolute(C)?C:cji.resolve(z,C),N=z0h.readFileSync(G,"utf-8").split(`
2394
2394
  `).find(U=>U.trim().length>0)||"Custom License";N=N.trim().replace(/^#+\s*/,""),N=N.replace(/[.:;]+$/,"").trim(),M=N}catch{}}}M!=null&&(b={...t,_fernLicenseName:M})}let{snippetPath:O,snippetTemplatePath:m,irPath:P,outputDirectory:D}=l,A=e.outputMode._visit({publish:M=>({...B0h(n,M,e,l),snippetFilepath:O,publishingMetadata:e.publishMetadata}),publishV2:M=>({...B0h(n,M,e,l),snippetFilepath:O,publishingMetadata:e.publishMetadata}),downloadFiles:()=>({mode:P2.FernGeneratorExec.OutputMode.downloadFiles(),path:D,snippetFilepath:O,publishingMetadata:e.publishMetadata}),github:M=>{let E={mode:P2.FernGeneratorExec.OutputMode.github({repoUrl:`https://github.com/${M.owner}/${M.repo}`,version:n,publishInfo:C0h(M.publishInfo),installationToken:void 0}),path:D,publishingMetadata:e.publishMetadata};return a!==void 0&&(E.snippetFilepath=O),u!==void 0&&(E.snippetTemplateFilepath=m),E},githubV2:M=>{let E=M._visit({commitAndRelease:z=>`https://github.com/${z.owner}/${z.repo}`,push:z=>`https://github.com/${z.owner}/${z.repo}`,pullRequest:z=>`https://github.com/${z.owner}/${z.repo}`,_other:()=>{throw new Error("Encountered unknown github mode")}}),C={mode:P2.FernGeneratorExec.OutputMode.github({repoUrl:E,version:n,publishInfo:C0h(M.publishInfo)}),path:D,publishingMetadata:e.publishMetadata};return a!==void 0&&(C.snippetFilepath=O),u!==void 0&&(C.snippetTemplateFilepath=m),C},_other:()=>{throw new Error("Output type did not match any of the types supported by Fern")}});return{irFilepath:P,output:A,publish:void 0,customConfig:b,workspaceName:r,organization:i,environment:P2.FernGeneratorExec.GeneratorEnvironment.local(),dryRun:!1,whitelabel:!1,writeUnitTests:d,generateOauthClients:s,generatePaginatedClients:o,license:g}}function B0h(e,t,r,i){let{outputDirectory:n}=i,a;"registryOverrides"in t?a=t.registryOverrides.maven??t.registryOverrides.npm:a!=null&&(a=t._visit({mavenOverride:c=>c,npmOverride:c=>c,pypiOverride:c=>c,rubyGemsOverride:c=>c,postman:c=>c,nugetOverride:c=>c,_other:()=>{}}));let u="";return r.raw?.github!=null&&(f3a(r.raw.github)?u=r.raw.github.uri:u=r.raw?.github.repository),{mode:P2.FernGeneratorExec.OutputMode.github({repoUrl:u,version:e}),path:n}}var Ne=Symbol(),ar=Symbol();var R0h={laterVersion:"v2",earlierVersion:"v1",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.246",[$.TYPESCRIPT_EXPRESS]:"0.0.264",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.STOPLIGHT]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({apiName:e.apiName,auth:e.auth,headers:e.headers,types:e.types,services:e.services,constants:e.constants,constantsV2:e.constantsV2,defaultEnvironment:e.defaultEnvironment,environments:e.environments,errorDiscriminant:e.errorDiscriminant,errorDiscriminationStrategy:e.errorDiscriminationStrategy,sdkConfig:e.sdkConfig,errors:e.errors.map(t=>({name:t.name,docs:t.docs,discriminantValue:{originalValue:t.discriminantValueV4.name.unsafeName.originalValue,camelCase:t.discriminantValueV4.name.unsafeName.camelCase,pascalCase:t.discriminantValueV4.name.unsafeName.pascalCase,snakeCase:t.discriminantValueV4.name.unsafeName.snakeCase,screamingSnakeCase:t.discriminantValueV4.name.unsafeName.screamingSnakeCase,wireValue:t.discriminantValueV4.wireValue},discriminantValueV2:t.discriminantValueV2,discriminantValueV3:t.discriminantValueV3,discriminantValueV4:t.discriminantValueV4,type:t.type,typeV2:t.typeV2,typeV3:t.typeV3,http:t.http,statusCode:t.statusCode}))})};var ve={};Na(ve,{V1:()=>Ggx,V10:()=>tOx,V11:()=>rOx,V12:()=>iOx,V13:()=>nOx,V14:()=>aOx,V15:()=>oOx,V16:()=>uOx,V17:()=>sOx,V18:()=>cOx,V19:()=>lOx,V2:()=>Qgx,V20:()=>fOx,V21:()=>dOx,V22:()=>pOx,V23:()=>RUO.FernIrV23,V24:()=>NUO.FernIrV24,V25:()=>FUO.FernIrV25,V26:()=>LUO.FernIrV26,V27:()=>UUO.FernIrV27,V28:()=>VUO.FernIrV28,V29:()=>WUO.FernIrV29,V3:()=>Jgx,V30:()=>HUO.FernIrV30,V31:()=>$UO.FernIrV31,V32:()=>GUO.FernIrV32,V33:()=>QUO.FernIrV33,V34:()=>JUO.FernIrV34,V35:()=>KUO.FernIrV35,V36:()=>YUO.FernIrV36,V37:()=>XUO.FernIrV37,V38:()=>ZUO.FernIrV38,V39:()=>kUO.FernIrV39,V4:()=>Kgx,V40:()=>eVO.FernIrV40,V41:()=>tVO.FernIrV41,V42:()=>rVO.FernIrV42,V43:()=>iVO.FernIrV43,V44:()=>nVO.FernIrV44,V45:()=>aVO.FernIrV45,V46:()=>oVO.FernIrV46,V47:()=>uVO.FernIrV47,V48:()=>sVO.FernIrV48,V49:()=>cVO.FernIrV49,V5:()=>Ygx,V50:()=>lVO.FernIrV50,V51:()=>fVO.FernIrV51,V52:()=>dVO.FernIrV52,V53:()=>pVO.FernIrV53,V54:()=>_VO.FernIrV54,V55:()=>hVO.FernIrV55,V56:()=>yVO.FernIrV56,V57:()=>vVO.FernIrV57,V58:()=>bVO.FernIrV58,V59:()=>Hs,V6:()=>Xgx,V7:()=>Zgx,V8:()=>kgx,V9:()=>eOx});var Ggx=ui(Cwh(),1),Qgx=ui(EAh(),1),Jgx=ui(yxh(),1),Kgx=ui(_4h(),1),Ygx=ui(kLh(),1),Xgx=ui(uQh(),1),Zgx=ui(hkh(),1),kgx=ui(way(),1),eOx=ui(Yfy(),1),tOx=ui(vby(),1),rOx=ui(Ujy(),1),iOx=ui(NAy(),1),nOx=ui(zxy(),1),aOx=ui(C4y(),1),oOx=ui(AVy(),1),uOx=ui(UKy(),1),sOx=ui(krv(),1),cOx=ui(flv(),1),lOx=ui(Dvv(),1),fOx=ui(rwv(),1),dOx=ui(zqv(),1),pOx=ui(_3v(),1),RUO=ui(BFv(),1),NUO=ui(y9v(),1),FUO=ui(iHv(),1),LUO=ui(JJv(),1),UUO=ui(Wkv(),1),VUO=ui(Fnb(),1),WUO=ui(zcb(),1),HUO=ui(R_b(),1),$UO=ui(F0b(),1),GUO=ui(Yjb(),1),QUO=ui(rdl(),1),JUO=ui(gIb(),1),KUO=ui(_7b(),1),YUO=ui(c5b(),1),XUO=ui(oHb(),1),ZUO=ui(oYb(),1),kUO=ui(jr0(),1),eVO=ui(Ls0(),1),tVO=ui(ah0(),1),rVO=ui(MO0(),1),iVO=ui(kS0(),1),nVO=ui(SC0(),1),aVO=ui(dN0(),1),oVO=ui(a50(),1),uVO=ui(r$0(),1),sVO=ui(kX0(),1),cVO=ui(kng(),1),lVO=ui(sdg(),1),fVO=ui(E0g(),1),dVO=ui(X1g(),1),pVO=ui(Sxg(),1),_VO=ui(uLg(),1),hVO=ui(KXg(),1),yVO=ui(NcO(),1),vVO=ui(EMO(),1),bVO=ui(xUO(),1);function gVO({inlinedRequest:e,allTypes:t}){let r=new Set,i=t.reduce((n,a)=>({...n,[Lzl(a.name)]:a}),{});for(let n of e.extends)OVO({typeName:n,typeNameToDeclaration:i,referencedTypes:r});for(let n of e.properties)Qna({reference:n.valueType,typeNameToDeclaration:i,referencedTypes:r});return[...r].reduce((n,a)=>{let u=i[a];if(u==null)throw new Error("Cannot find declaration for ID: "+a);return[...n,u.name]},[])}function Qna({reference:e,typeNameToDeclaration:t,referencedTypes:r}){ve.V2.types.TypeReference._visit(e,{primitive:Ko,container:i=>{_Ox({container:i,typeNameToDeclaration:t,referencedTypes:r})},named:i=>{OVO({typeName:i,typeNameToDeclaration:t,referencedTypes:r})},unknown:Ko,void:Ko,_unknown:()=>{throw new Error("Unknown TypeReference: "+e._type)}})}function _Ox({container:e,typeNameToDeclaration:t,referencedTypes:r}){ve.V2.types.ContainerType._visit(e,{list:i=>{Qna({reference:i,typeNameToDeclaration:t,referencedTypes:r})},set:i=>{Qna({reference:i,typeNameToDeclaration:t,referencedTypes:r})},optional:i=>{Qna({reference:i,typeNameToDeclaration:t,referencedTypes:r})},map:({keyType:i,valueType:n})=>{Qna({reference:i,typeNameToDeclaration:t,referencedTypes:r}),Qna({reference:n,typeNameToDeclaration:t,referencedTypes:r})},literal:Ko,_unknown:()=>{throw new Error("Unknown ContainerType: "+e._type)}})}function OVO({typeName:e,typeNameToDeclaration:t,referencedTypes:r}){let i=Lzl(e);r.add(i);let n=t[i];if(n==null)throw new Error("Cannot locate type: "+i);for(let a of n.referencedTypes)r.add(Lzl(a))}function Lzl(e){return[...e.fernFilepathV2.map(t=>t.unsafeName.originalValue),e.nameV3.unsafeName.originalValue].join(".")}var mVO={laterVersion:"v3",earlierVersion:"v2",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.249",[$.TYPESCRIPT_EXPRESS]:"0.0.264",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.0.134-3-g97d4964",[$.JAVA_SDK]:"0.0.134-3-g97d4964",[$.JAVA_SPRING]:"0.0.134-3-g97d4964",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.STOPLIGHT]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>{let t=[...e.types];return{apiName:e.apiName,auth:e.auth,headers:e.headers,types:t,errors:e.errors,constants:e.constants,constantsV2:e.constantsV2,defaultEnvironment:e.defaultEnvironment,environments:e.environments,errorDiscriminant:e.errorDiscriminant,errorDiscriminationStrategy:e.errorDiscriminationStrategy,sdkConfig:e.sdkConfig,services:{websocket:e.services.websocket,http:e.services.http.map(r=>({availability:r.availability,docs:r.docs,name:r.name,basePath:r.basePath,basePathV2:r.basePathV2,headers:r.headers,pathParameters:r.pathParameters,endpoints:r.endpoints.map(i=>hOx(r,i,e.types,n=>{t.push(n)}))}))}}}};function hOx(e,t,r,i){return{docs:t.docs,availability:t.availability,id:t.id,name:t.name,nameV2:t.nameV2,method:t.method,headers:t.headers,path:t.path,pathParameters:t.pathParameters,queryParameters:t.queryParameters,request:yOx(t,e,r,i),response:t.response,errors:t.errors,errorsV2:t.errorsV2,auth:t.auth}}function yOx(e,t,r,i){let n=e.requestBody;return n==null?{docs:void 0,type:ve.V2.types.TypeReference.void(),typeV2:void 0}:ve.V3.services.http.HttpRequestBody._visit(n,{reference:a=>({docs:a.docs,type:a.requestBodyType,typeV2:a.requestBodyType}),inlinedRequestBody:a=>{let u={fernFilepath:t.name.fernFilepath,fernFilepathV2:t.name.fernFilepathV2,name:a.name.unsafeName.originalValue,nameV2:{originalValue:a.name.unsafeName.originalValue,camelCase:a.name.unsafeName.camelCase,pascalCase:a.name.unsafeName.pascalCase,snakeCase:a.name.unsafeName.snakeCase,screamingSnakeCase:a.name.unsafeName.screamingSnakeCase},nameV3:a.name},c=ve.V2.types.Type.object({extends:a.extends,properties:a.properties.map(s=>({availability:e.availability,docs:s.docs,name:{originalValue:s.name.name.unsafeName.originalValue,camelCase:s.name.name.unsafeName.camelCase,pascalCase:s.name.name.unsafeName.pascalCase,snakeCase:s.name.name.unsafeName.snakeCase,screamingSnakeCase:s.name.name.unsafeName.screamingSnakeCase,wireValue:s.name.wireValue},nameV2:s.name,valueType:s.valueType}))});i({docs:void 0,availability:e.availability,name:u,shape:c,referencedTypes:gVO({inlinedRequest:a,allTypes:r}),examples:[]});let d=ve.V2.types.TypeReference.named(u);return{docs:void 0,type:d,typeV2:d}},_unknown:()=>{throw new Error("Unknown HttpRequestBody type: "+n.type)}})}var wVO={laterVersion:"v4",earlierVersion:"v3",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:"0.0.264",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI]:"0.0.11-4-g1c29f6c",[$.POSTMAN]:"0.0.32-rc0",[$.STOPLIGHT]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({apiName:e.apiName,auth:e.auth,headers:e.headers,types:e.types.map(t=>({docs:t.docs,availability:t.availability,name:t.name,shape:t.shape,examples:t.examples.map(r=>SVO(r.shape)),referencedTypes:t.referencedTypes})),errors:e.errors,constants:e.constants,constantsV2:e.constantsV2,defaultEnvironment:e.defaultEnvironment,environments:e.environments,errorDiscriminant:e.errorDiscriminant,errorDiscriminationStrategy:e.errorDiscriminationStrategy,sdkConfig:e.sdkConfig,services:{...e.services,http:e.services.http.map(t=>({...t,endpoints:t.endpoints.map(r=>({...r,examples:r.examples.map(i=>mOx(i))}))}))}})};function SVO(e){return ve.V4.types.ExampleTypeShape._visit(e,{object:t=>ve.V3.types.ExampleType.object(vOx(t)),union:t=>ve.V3.types.ExampleType.union(gOx(t)),alias:t=>ve.V3.types.ExampleType.alias(OOx(t)),enum:ve.V3.types.ExampleType.enum,_unknown:()=>{throw new Error("Unknown ExampleTypeShape: "+e.type)}})}function vOx(e){return{properties:e.properties.map(t=>({wireKey:t.wireKey,value:Kre(t.value),originalTypeDeclaration:t.originalTypeDeclaration}))}}function Kre(e){return ve.V4.types.ExampleTypeReferenceShape._visit(e.shape,{primitive:ve.V3.types.ExampleTypeReference.primitive,container:t=>ve.V3.types.ExampleTypeReference.container(bOx(t)),named:t=>ve.V3.types.ExampleTypeReference.named(DVO(t)),unknown:ve.V3.types.ExampleTypeReference.unknown,_unknown:()=>{throw new Error("Unknown ExampleTypeReference: "+e.shape.type)}})}function bOx(e){return ve.V4.types.ExampleContainer._visit(e,{list:t=>ve.V3.types.ExampleContainer.list(t.map(Kre)),set:t=>ve.V3.types.ExampleContainer.set(t.map(Kre)),optional:t=>ve.V3.types.ExampleContainer.optional(t!=null?Kre(t):void 0),map:t=>ve.V3.types.ExampleContainer.map(t.map(r=>({key:Kre(r.key),value:Kre(r.value)}))),_unknown:()=>{throw new Error("Unknown ExampleContainer: "+e.type)}})}function DVO(e){return{typeName:e.typeName,shape:SVO(e.shape)}}function gOx(e){return{wireDiscriminantValue:e.wireDiscriminantValue,properties:ve.V4.types.ExampleSingleUnionTypeProperties._visit(e.properties,{samePropertiesAsObject:t=>ve.V3.types.ExampleSingleUnionTypeProperties.samePropertiesAsObject(DVO(t)),singleProperty:t=>ve.V3.types.ExampleSingleUnionTypeProperties.singleProperty(Kre(t)),noProperties:()=>ve.V3.types.ExampleSingleUnionTypeProperties.noProperties(),_unknown:()=>{throw new Error("Unknown ExampleSingleUnionTypeProperties: "+e.properties.type)}})}}function OOx(e){return{value:Kre(e.value)}}function mOx(e){return{servicePathParameters:e.servicePathParameters.map(t=>PVO(t)),endpointPathParameters:e.servicePathParameters.map(t=>PVO(t)),serviceHeaders:e.serviceHeaders.map(t=>jVO(t)),endpointHeaders:e.endpointHeaders.map(t=>jVO(t)),queryParameters:e.queryParameters.map(t=>POx(t)),request:e.request!=null?jOx(e.request):void 0,response:SOx(e.response)}}function PVO(e){return{key:e.key,value:Kre(e.value)}}function jVO(e){return{key:e.wireKey,value:Kre(e.value)}}function POx(e){return{key:e.wireKey,value:Kre(e.value)}}function jOx(e){return ve.V4.services.http.ExampleRequestBody._visit(e,{inlinedRequestBody:t=>ve.V3.services.http.ExampleRequestBody.inlinedRequestBody({properties:t.properties.map(r=>wOx(r))}),reference:t=>ve.V3.services.http.ExampleRequestBody.reference(Kre(t)),_unknown:()=>{throw new Error("Unknown ExampleRequestBody: "+e.type)}})}function wOx(e){return{wireKey:e.wireKey,value:Kre(e.value),originalTypeDeclaration:e.originalTypeDeclaration}}function SOx(e){return ve.V4.services.http.ExampleResponse._visit(e,{ok:t=>ve.V3.services.http.ExampleResponse.ok({body:t.body!=null?Kre(t.body):void 0}),error:t=>ve.V3.services.http.ExampleResponse.error({error:t.error,body:t.body!=null?Kre(t.body):void 0}),_unknown:()=>{throw new Error("Unknown ExampleResponse: "+e.type)}})}function lYt(e){return{originalValue:e.originalName,camelCase:e.camelCase.unsafeName,pascalCase:e.pascalCase.unsafeName,snakeCase:e.snakeCase.unsafeName,screamingSnakeCase:e.screamingSnakeCase.unsafeName}}function QCe(e){return{...lYt(e.name),wireValue:e.wireValue}}function K5(e){return{safeName:{originalValue:e.originalName,camelCase:e.camelCase.safeName,pascalCase:e.pascalCase.safeName,snakeCase:e.snakeCase.safeName,screamingSnakeCase:e.screamingSnakeCase.safeName},unsafeName:{originalValue:e.originalName,camelCase:e.camelCase.unsafeName,pascalCase:e.pascalCase.unsafeName,snakeCase:e.snakeCase.unsafeName,screamingSnakeCase:e.screamingSnakeCase.unsafeName}}}function Y5(e){return{wireValue:e.wireValue,name:K5(e.name)}}function Jna(e){return ve.V5.types.ContainerType._visit(e,{list:t=>ve.V4.types.ContainerType.list(Z3(t)),set:t=>ve.V4.types.ContainerType.set(Z3(t)),map:({keyType:t,valueType:r})=>ve.V4.types.ContainerType.map({keyType:Z3(t),valueType:Z3(r)}),optional:t=>ve.V4.types.ContainerType.optional(Z3(t)),literal:t=>ve.V5.types.Literal._visit(t,{string:r=>ve.V4.types.ContainerType.literal(ve.V4.types.Literal.string(r)),_unknown:()=>{throw new Error("Unknown Literal: "+t.type)}}),_unknown:()=>{throw new Error("Unknown ContainerType: "+e._type)}})}function Ygn(e){return e.map(t=>lYt(t))}function Xgn(e){return e.map(t=>K5(t))}function DV(e){return{fernFilepath:Ygn(e.fernFilepath),fernFilepathV2:Xgn(e.fernFilepath),name:e.name.originalName,nameV2:lYt(e.name),nameV3:K5(e.name)}}function Z3(e){return ve.V5.types.TypeReference._visit(e,{named:t=>ve.V4.types.TypeReference.named(DV(t)),container:t=>ve.V4.types.TypeReference.container(Jna(t)),primitive:t=>ve.V4.types.TypeReference.primitive(t),unknown:ve.V4.types.TypeReference.unknown,_unknown:()=>{throw new Error("Unknown TypeReference: "+e._type)}})}function Zgn(e){return{name:QCe(e.name),nameV2:Y5(e.name),valueType:Z3(e.valueType),availability:e.availability,docs:e.docs}}function EVO(e){return{docs:e.docs,requirement:e.requirement,schemes:e.schemes.map(t=>DOx(t))}}function DOx(e){return ve.V5.auth.AuthScheme._visit(e,{basic:ve.V4.auth.AuthScheme.basic,bearer:ve.V4.auth.AuthScheme.bearer,header:t=>ve.V4.auth.AuthScheme.header(Zgn(t)),_unknown:()=>{throw new Error("Unknown AuthScheme: "+e._type)}})}function MVO(e){return{docs:e.docs,id:e.id,url:e.url,name:K5(e.name)}}function AVO({errorDeclaration:e,errorDiscriminationStrategy:t,typeReferenceResolver:r}){let i=e.type!=null?ve.V4.types.Type.alias({aliasOf:Z3(e.type),resolvedType:r.resolveTypeReference(e.type)}):void 0;return{docs:e.docs,name:{name:e.name.name.originalName,nameV2:lYt(e.name.name),nameV3:K5(e.name.name),fernFilepath:Ygn(e.name.fernFilepath),fernFilepathV2:Xgn(e.name.fernFilepath)},discriminantValueV2:Y5(e.discriminantValue),discriminantValueV3:ve.V5.ir.ErrorDiscriminationStrategy._visit(t,{statusCode:ve.V4.errors.ErrorDeclarationDiscriminantValue.statusCode,property:n=>ve.V4.errors.ErrorDeclarationDiscriminantValue.property(Y5(n.contentProperty)),_unknown:()=>{throw new Error("Unknown ErrorDiscriminationStrategy: "+t.type)}}),discriminantValueV4:Y5(e.discriminantValue),type:i??ve.V4.types.Type.alias({aliasOf:ve.V4.types.TypeReference.void(),resolvedType:ve.V4.types.ResolvedTypeReference.void()}),typeV2:i,typeV3:e.type!=null?Z3(e.type):e.type,http:{statusCode:e.statusCode},statusCode:e.statusCode}}function Yre(e){return{jsonExample:e.jsonExample,shape:qVO(e.shape)}}function qVO(e){return ve.V5.types.ExampleTypeReferenceShape._visit(e,{primitive:ve.V4.types.ExampleTypeReferenceShape.primitive,container:t=>ve.V4.types.ExampleTypeReferenceShape.container(MOx(t)),unknown:ve.V4.types.ExampleTypeReferenceShape.unknown,named:t=>ve.V4.types.ExampleTypeReferenceShape.named(EOx(t)),_unknown:()=>{throw new Error("Unknown ExampleTypeReferenceShape: "+e.type)}})}function EOx(e){return{typeName:DV(e.typeName),shape:ETu(e.shape)}}function MOx(e){return ve.V5.types.ExampleContainer._visit(e,{list:t=>ve.V4.types.ExampleContainer.list(t.map(r=>Yre(r))),set:t=>ve.V4.types.ExampleContainer.set(t.map(r=>Yre(r))),optional:t=>ve.V4.types.ExampleContainer.optional(t!=null?Yre(t):void 0),map:t=>ve.V4.types.ExampleContainer.map(t.map(r=>({key:Yre(r.key),value:Yre(r.value)}))),_unknown:()=>{throw new Error("Unknown ExampleContainer: "+e.type)}})}function ETu(e){return ve.V5.types.ExampleTypeShape._visit(e,{alias:t=>ve.V4.types.ExampleTypeShape.alias({value:Yre(t.value)}),object:t=>ve.V4.types.ExampleTypeShape.object({properties:t.properties.map(r=>({wireKey:r.wireKey,value:Yre(r.value),originalTypeDeclaration:DV(r.originalTypeDeclaration)}))}),union:t=>ve.V4.types.ExampleTypeShape.union({wireDiscriminantValue:t.wireDiscriminantValue,properties:ve.V5.types.ExampleSingleUnionTypeProperties._visit(t.properties,{samePropertiesAsObject:r=>ve.V4.types.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeName:DV(r.typeName),shape:ETu(r.shape)}),singleProperty:r=>ve.V4.types.ExampleSingleUnionTypeProperties.singleProperty({jsonExample:r.jsonExample,shape:qVO(r.shape)}),noProperties:ve.V4.types.ExampleSingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown ExampleSingleUnionTypeProperties: "+t.properties.type)}})}),enum:t=>ve.V4.types.ExampleTypeShape.enum({wireValue:t.wireValue}),_unknown:()=>{throw new Error("Unknown ExampleTypeShape: "+e.type)}})}function BVO({service:e,errorResolver:t}){return{docs:e.docs,availability:e.availability,displayName:e.displayName,name:AOx(e.name),basePath:qOx(e.basePath),basePathV2:e.basePath,endpoints:e.endpoints.map(r=>TOx({endpoint:r,errorResolver:t})),headers:e.headers.map(r=>Zgn(r)),pathParameters:e.pathParameters.map(r=>IVO(r))}}function AOx(e){return{name:e.name.pascalCase.unsafeName,fernFilepath:Ygn(e.fernFilepath),fernFilepathV2:Xgn(e.fernFilepath)}}function qOx(e){return e.parts.reduce((t,r)=>t+`{${r.pathParameter}}`+r.tail,e.head)}function TOx({endpoint:e,errorResolver:t}){return{docs:e.docs,availability:e.availability,id:e.name.originalName,name:lYt(e.name),nameV2:K5(e.name),displayName:e.displayName,method:e.method,headers:e.headers.map(r=>Zgn(r)),path:e.path,pathParameters:e.pathParameters.map(r=>IVO(r)),queryParameters:e.queryParameters.map(r=>COx(r)),requestBody:e.requestBody!=null?BOx(e.requestBody):void 0,sdkRequest:e.sdkRequest!=null?IOx(e.sdkRequest):void 0,response:zOx(e.response),errors:e.errors.map(r=>xOx(r)),errorsV2:ROx({responseErrors:e.errors,errorResolver:t}),auth:e.auth,examples:e.examples.map(r=>LOx(r))}}function IVO(e){return{docs:e.docs,availability:e.availability,name:lYt(e.name),nameV2:K5(e.name),valueType:Z3(e.valueType)}}function COx(e){return{docs:e.docs,availability:e.availability,name:QCe(e.name),nameV2:Y5(e.name),valueType:Z3(e.valueType),allowMultiple:e.allowMultiple}}function BOx(e){return ve.V5.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V4.services.http.HttpRequestBody.inlinedRequestBody({name:K5(t.name),extends:t.extends.map(r=>DV(r)),properties:t.properties.map(r=>({docs:r.docs,name:Y5(r.name),valueType:Z3(r.valueType)}))}),reference:t=>ve.V4.services.http.HttpRequestBody.reference({docs:t.docs,requestBodyType:Z3(t.requestBodyType)}),_unknown:()=>{throw new Error("Unknown HttpRequestBody type: "+e.type)}})}function IOx(e){return{requestParameterName:K5(e.requestParameterName),shape:ve.V5.http.SdkRequestShape._visit(e.shape,{justRequestBody:t=>ve.V4.services.http.SdkRequestShape.justRequestBody({docs:t.docs,requestBodyType:Z3(t.requestBodyType)}),wrapper:t=>ve.V4.services.http.SdkRequestShape.wrapper({wrapperName:K5(t.wrapperName),bodyKey:K5(t.bodyKey)}),_unknown:()=>{throw new Error("Unknown SdkRequestShape type: "+e.shape.type)}})}}function zOx(e){let t=e.type!=null?Z3(e.type):void 0;return{docs:e.docs,type:t??ve.V4.types.TypeReference.void(),typeV2:t}}function xOx(e){return{docs:e.docs,error:Uzl(e.error)}}function ROx({responseErrors:e,errorResolver:t}){return{discriminant:{originalValue:"errorName",camelCase:"errorName",snakeCase:"error_name",pascalCase:"ErrorName",screamingSnakeCase:"ERROR_NAME",wireValue:"errorName"},types:e.map(r=>NOx({responseError:r,errorResolver:t}))}}function NOx({responseError:e,errorResolver:t}){let r=t.getDeclaration(e.error);return{docs:e.docs,discriminantValue:QCe(r.discriminantValue),shape:FOx({responseError:e,declaration:r})}}function FOx({responseError:e,declaration:t}){return t.type==null?ve.V4.services.commons.ResponseErrorShape.noProperties():ve.V4.services.commons.ResponseErrorShape.singleProperty({name:{originalValue:"content",camelCase:"content",snakeCase:"content",pascalCase:"Content",screamingSnakeCase:"CONTENT",wireValue:"content"},error:Uzl(e.error)})}function Uzl(e){return{name:e.name.originalName,nameV2:lYt(e.name),nameV3:K5(e.name),fernFilepath:Ygn(e.fernFilepath),fernFilepathV2:Xgn(e.fernFilepath)}}function LOx(e){return{docs:e.docs,name:e.name?.originalName,servicePathParameters:e.servicePathParameters.map(t=>TVO(t)),endpointPathParameters:e.endpointPathParameters.map(t=>TVO(t)),serviceHeaders:e.serviceHeaders.map(t=>CVO(t)),endpointHeaders:e.endpointHeaders.map(t=>CVO(t)),queryParameters:e.queryParameters.map(t=>UOx(t)),request:e.request!=null?VOx(e.request):void 0,response:HOx(e.response)}}function TVO(e){return{key:e.key,value:Yre(e.value)}}function CVO(e){return{wireKey:e.wireKey,value:Yre(e.value)}}function UOx(e){return{wireKey:e.wireKey,value:Yre(e.value)}}function VOx(e){return ve.V5.http.ExampleRequestBody._visit(e,{inlinedRequestBody:t=>ve.V4.services.http.ExampleRequestBody.inlinedRequestBody({jsonExample:t.jsonExample,properties:t.properties.map(r=>WOx(r))}),reference:t=>ve.V4.services.http.ExampleRequestBody.reference(Yre(t)),_unknown:()=>{throw new Error("Unknown ExampleRequestBody: "+e.type)}})}function WOx(e){return{wireKey:e.wireKey,value:Yre(e.value),originalTypeDeclaration:e.originalTypeDeclaration!=null?DV(e.originalTypeDeclaration):void 0}}function HOx(e){return ve.V5.http.ExampleResponse._visit(e,{ok:t=>ve.V4.services.http.ExampleResponse.ok({body:t.body!=null?Yre(t.body):void 0}),error:t=>ve.V4.services.http.ExampleResponse.error({error:Uzl(t.error),body:t.body!=null?Yre(t.body):void 0}),_unknown:()=>{throw new Error("Unknown ExampleResponse: "+e.type)}})}function zVO(e){return{docs:e.docs,availability:e.availability,name:DV(e.name),shape:$Ox(e.shape),examples:e.examples.map(t=>GOx(t)),referencedTypes:e.referencedTypes.map(t=>DV(t))}}function $Ox(e){return ve.V5.types.Type._visit(e,{alias:({aliasOf:t,resolvedType:r})=>ve.V4.types.Type.alias({aliasOf:Z3(t),resolvedType:QOx(r)}),enum:t=>ve.V4.types.Type.enum({values:t.values.map(r=>({docs:r.docs,availability:r.availability,name:QCe(r.name),nameV2:Y5(r.name),value:r.name.wireValue}))}),object:t=>ve.V4.types.Type.object({extends:t.extends.map(r=>DV(r)),properties:t.properties.map(r=>({docs:r.docs,availability:r.availability,name:QCe(r.name),nameV2:Y5(r.name),valueType:Z3(r.valueType)}))}),union:t=>ve.V4.types.Type.union({discriminant:t.discriminant.wireValue,discriminantV2:QCe(t.discriminant),discriminantV3:Y5(t.discriminant),types:t.types.map(r=>({docs:r.docs,discriminantValue:QCe(r.discriminantValue),discriminantValueV2:Y5(r.discriminantValue),valueType:ve.V5.types.SingleUnionTypeProperties._visit(r.shape,{samePropertiesAsObject:i=>ve.V4.types.TypeReference.named(DV(i)),singleProperty:i=>Z3(i.type),noProperties:ve.V4.types.TypeReference.void,_unknown:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+r.shape._type)}}),shape:ve.V5.types.SingleUnionTypeProperties._visit(r.shape,{samePropertiesAsObject:i=>ve.V4.types.SingleUnionTypeProperties.samePropertiesAsObject(DV(i)),singleProperty:i=>ve.V4.types.SingleUnionTypeProperties.singleProperty({name:QCe(i.name),nameV2:Y5(i.name),type:Z3(i.type)}),noProperties:ve.V4.types.SingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+r.shape._type)}})}))}),_unknown:()=>{throw new Error("Unknown shape: "+e._type)}})}function GOx(e){return{docs:e.docs,jsonExample:e.jsonExample,name:e.name?.originalName,shape:ETu(e.shape)}}function QOx(e){return ve.V5.types.ResolvedTypeReference._visit(e,{named:t=>ve.V4.types.ResolvedTypeReference.named({name:DV(t.name),shape:JOx(t.shape)}),container:t=>ve.V4.types.ResolvedTypeReference.container(Jna(t)),primitive:ve.V4.types.ResolvedTypeReference.primitive,unknown:ve.V4.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Unknown ResolvedTypeReference: "+e._type)}})}function JOx(e){return ve.V5.types.ShapeType._visit(e,{enum:()=>ve.V5.types.ShapeType.Enum,object:()=>ve.V5.types.ShapeType.Object,union:()=>ve.V5.types.ShapeType.Union,_unknown:()=>{throw new Error("Unknown ShapeType: "+e)}})}var MTu=class{errors;constructor(t){this.errors=t.errors.reduce((r,i)=>({...r,[xVO(i.name)]:i}),{})}getDeclaration(t){let r=xVO(t),i=this.errors[r];if(i==null)throw new Error("Error does not exist: "+r);return i}};function xVO(e){return`${e.fernFilepath.join("/")}:${e.name.originalName}`}var ATu=class{types;constructor(t){this.types=t.types.reduce((r,i)=>({...r,[RVO(i.name)]:i}),{})}resolveTypeReference(t){return ve.V5.types.TypeReference._visit(t,{container:r=>ve.V4.types.ResolvedTypeReference.container(Jna(r)),named:r=>{let i=this.getTypeDeclaration(r);return i.shape._type==="alias"?this.resolveTypeReference(i.shape.aliasOf):ve.V4.types.ResolvedTypeReference.named({name:DV(r),shape:KOx(i.shape._type)})},primitive:ve.V4.types.ResolvedTypeReference.primitive,unknown:ve.V4.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Unknown TypeReference: "+t._type)}})}getTypeDeclaration(t){let r=RVO(t),i=this.types[r];if(i==null)throw new Error("Type does not exist: "+i);return i}};function RVO(e){return`${e.fernFilepath.join("/")}:${e.name.originalName}`}function KOx(e){switch(e){case"object":return ve.V4.types.ShapeType.Object;case"union":return ve.V4.types.ShapeType.Union;case"enum":return ve.V4.types.ShapeType.Enum;default:Ao(e)}}var NVO={laterVersion:"v5",earlierVersion:"v4",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.257-2-g46fe4ff",[$.TYPESCRIPT_EXPRESS]:"0.0.264",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.0.33-9-gf683b5e",[$.PYTHON_PYDANTIC]:"0.0.33-9-gf683b5e",[$.OPENAPI]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.STOPLIGHT]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>{let t=new ATu(e),r=new MTu(e);return{apiName:e.apiName.originalName,apiDisplayName:e.apiDisplayName,apiDocs:e.apiDocs,auth:EVO(e.auth),headers:e.headers.map(i=>Zgn(i)),types:e.types.map(i=>zVO(i)),services:{http:e.services.map(i=>BVO({service:i,errorResolver:r})),websocket:[]},errors:e.errors.map(i=>AVO({errorDeclaration:i,errorDiscriminationStrategy:e.errorDiscriminationStrategy,typeReferenceResolver:t})),constants:{errorDiscriminant:"_error",errorInstanceIdKey:"_errorInstanceId",unknownErrorDiscriminantValue:"_unknown"},constantsV2:{errors:{errorInstanceIdKey:QCe(e.constants.errorInstanceIdKey),errorDiscriminant:{originalValue:"error",camelCase:"error",snakeCase:"error",pascalCase:"Error",screamingSnakeCase:"ERROR",wireValue:"error"},errorContentKey:{originalValue:"content",camelCase:"content",snakeCase:"content",pascalCase:"Content",screamingSnakeCase:"CONTENT",wireValue:"content"}},errorsV2:{errorInstanceIdKey:Y5(e.constants.errorInstanceIdKey),errorDiscriminant:{name:{unsafeName:{originalValue:"error",camelCase:"error",snakeCase:"error",pascalCase:"Error",screamingSnakeCase:"ERROR"},safeName:{originalValue:"error",camelCase:"error",snakeCase:"error",pascalCase:"Error",screamingSnakeCase:"ERROR"}},wireValue:"error"},errorContentKey:{name:{unsafeName:{originalValue:"content",camelCase:"content",snakeCase:"content",pascalCase:"Content",screamingSnakeCase:"CONTENT"},safeName:{originalValue:"content",camelCase:"content",snakeCase:"content",pascalCase:"Content",screamingSnakeCase:"CONTENT"}},wireValue:"content"}}},defaultEnvironment:e.defaultEnvironment,environments:e.environments.map(i=>MVO(i)),errorDiscriminant:e.errorDiscriminationStrategy.type==="property"?K5(e.errorDiscriminationStrategy.discriminant.name):void 0,errorDiscriminationStrategy:ve.V5.ir.ErrorDiscriminationStrategy._visit(e.errorDiscriminationStrategy,{statusCode:ve.V4.ir.ErrorDiscriminationStrategy.statusCode,property:i=>ve.V4.ir.ErrorDiscriminationStrategy.property({discriminant:Y5(i.discriminant),contentProperty:Y5(i.contentProperty)}),_unknown:()=>{throw new Error("Unknown ErrorDiscriminationStrategy: "+e.errorDiscriminationStrategy.type)}}),sdkConfig:e.sdkConfig}}};var FVO={laterVersion:"v6",earlierVersion:"v5",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.257-4-ge56e5d2",[$.TYPESCRIPT_EXPRESS]:"0.0.264",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.0.35-1-g071a04a",[$.PYTHON_PYDANTIC]:"0.0.35-1-g071a04a",[$.OPENAPI]:"0.0.16-1-ga2c0ada",[$.STOPLIGHT]:ar,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>({...e,defaultEnvironment:e.environments?.defaultEnvironment,environments:e.environments!=null?ve.V6.environment.Environments._visit(e.environments.environments,{singleBaseUrl:i=>i.environments,multipleBaseUrls:()=>t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support specifying multiple URLs for a single environment. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains a multiple URls for a single environment."),_unknown:()=>{throw new Error("Unknown Environments: "+e.environments?.environments.type)}}):[]})};var LVO={laterVersion:"v7",earlierVersion:"v6",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.268",[$.TYPESCRIPT_EXPRESS]:"0.0.268",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:ar,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.OPENAPI_PYTHON_CLIENT]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({...e,services:e.services.map(t=>{let r=t.name.fernFilepath[t.name.fernFilepath.length-1],i=r!=null?`${r.pascalCase.safeName}Service`:"Service",n=r!=null?`${r.camelCase.unsafeName}Service`:"Service",a=r!=null?`${r.snakeCase.unsafeName}_service`:"service",u=a.toUpperCase(),c=QB(n);return{...t,name:{name:{originalName:i,camelCase:{safeName:n,unsafeName:n},snakeCase:{safeName:a,unsafeName:a},screamingSnakeCase:{safeName:u,unsafeName:u},pascalCase:{safeName:c,unsafeName:c}},fernFilepath:t.name.fernFilepath}}})})};var WVO={laterVersion:"v8",earlierVersion:"v7",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.0.273-5-g1b00245b",[$.TYPESCRIPT_EXPRESS]:"0.0.273-5-g1b00245b",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.0.45-1-g8bb600f",[$.PYTHON_PYDANTIC]:"0.0.45-1-g8bb600f",[$.OPENAPI_PYTHON_CLIENT]:"0.0.0",[$.OPENAPI]:"0.0.20-1-gbbeb9bd",[$.STOPLIGHT]:ar,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({...e,auth:YOx(e.auth),headers:e.headers.map(t=>qTu(t)),types:e.types.map(t=>XOx(t)),errors:e.errors.map(t=>nmx(t)),services:e.services.map(t=>amx(t))})};function Vzl(e){return e.allParts}function YOx(e){return{docs:e.docs,requirement:e.requirement,schemes:e.schemes.map(t=>t._type!=="header"?t:ve.V7.auth.AuthScheme.header(qTu(t)))}}function qTu(e){return{docs:e.docs,availability:e.availability,name:e.name,valueType:cX(e.valueType)}}function cX(e){return ve.V8.types.TypeReference._visit(e,{container:t=>ve.V7.types.TypeReference.container(HVO(t)),named:t=>ve.V7.types.TypeReference.named(fYt(t)),primitive:ve.V7.types.TypeReference.primitive,unknown:ve.V7.types.TypeReference.unknown,_unknown:()=>{throw new Error("Unknown type reference: "+e._type)}})}function HVO(e){return ve.V8.types.ContainerType._visit(e,{list:t=>ve.V7.types.ContainerType.list(cX(t)),optional:t=>ve.V7.types.ContainerType.optional(cX(t)),set:t=>ve.V7.types.ContainerType.set(cX(t)),map:({keyType:t,valueType:r})=>ve.V7.types.ContainerType.map({keyType:cX(t),valueType:cX(r)}),literal:ve.V7.types.ContainerType.literal,_unknown:()=>{throw new Error("Unknown ContainerType: "+e._type)}})}function fYt(e){return{name:e.name,fernFilepath:Vzl(e.fernFilepath)}}function XOx(e){return{docs:e.docs,availability:e.availability,name:fYt(e.name),shape:ZOx(e.shape),examples:e.examples.map(t=>rmx(t)),referencedTypes:e.referencedTypes.map(t=>fYt(t))}}function ZOx(e){return ve.V8.types.Type._visit(e,{alias:t=>ve.V7.types.Type.alias({aliasOf:cX(t.aliasOf),resolvedType:kOx(t.resolvedType)}),enum:ve.V7.types.Type.enum,object:t=>ve.V7.types.Type.object({extends:t.extends.map(r=>fYt(r)),properties:t.properties.map(r=>({docs:r.docs,availability:r.availability,name:r.name,valueType:cX(r.valueType)}))}),union:t=>ve.V7.types.Type.union({discriminant:t.discriminant,types:t.types.map(r=>emx(r))}),_unknown:()=>{throw new Error("Unknown Type shape: "+e._type)}})}function kOx(e){return ve.V8.types.ResolvedTypeReference._visit(e,{container:t=>ve.V7.types.ResolvedTypeReference.container(HVO(t)),named:t=>ve.V7.types.ResolvedTypeReference.named({name:fYt(t.name),shape:t.shape}),primitive:ve.V7.types.ResolvedTypeReference.primitive,unknown:ve.V7.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Unknown ResolvedTypeReference: "+e._type)}})}function emx(e){return{docs:e.docs,discriminantValue:e.discriminantValue,shape:tmx(e.shape)}}function tmx(e){return ve.V8.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V7.types.SingleUnionTypeProperties.samePropertiesAsObject(fYt(t)),singleProperty:t=>ve.V7.types.SingleUnionTypeProperties.singleProperty({name:t.name,type:cX(t.type)}),noProperties:ve.V7.types.SingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+e._type)}})}function rmx(e){return{jsonExample:e.jsonExample,docs:e.docs,name:e.name,shape:Wzl(e.shape)}}function Wzl(e){return ve.V8.types.ExampleTypeShape._visit(e,{alias:t=>ve.V7.types.ExampleTypeShape.alias({value:Sle(t.value)}),enum:ve.V7.types.ExampleTypeShape.enum,object:t=>ve.V7.types.ExampleTypeShape.object({properties:t.properties.map(r=>({wireKey:r.wireKey,value:Sle(r.value),originalTypeDeclaration:fYt(r.originalTypeDeclaration)}))}),union:t=>ve.V7.types.ExampleTypeShape.union({wireDiscriminantValue:t.wireDiscriminantValue,properties:imx(t.properties)}),_unknown:()=>{throw new Error("Unknown ExampleTypeShape: "+e.type)}})}function Sle(e){return{jsonExample:e.jsonExample,shape:$VO(e.shape)}}function $VO(e){return ve.V8.types.ExampleTypeReferenceShape._visit(e,{named:t=>ve.V7.types.ExampleTypeReferenceShape.named({typeName:fYt(t.typeName),shape:Wzl(t.shape)}),container:t=>ve.V7.types.ExampleTypeReferenceShape.container(ve.V8.types.ExampleContainer._visit(t,{list:r=>ve.V7.types.ExampleContainer.list(r.map(i=>Sle(i))),set:r=>ve.V7.types.ExampleContainer.set(r.map(i=>Sle(i))),optional:r=>ve.V7.types.ExampleContainer.optional(r!=null?Sle(r):void 0),map:r=>ve.V7.types.ExampleContainer.map(r.map(i=>({key:Sle(i.key),value:Sle(i.value)}))),_unknown:()=>{throw new Error("Unknown ExampleContainer: "+t.type)}})),primitive:ve.V7.types.ExampleTypeReferenceShape.primitive,unknown:ve.V7.types.ExampleTypeReferenceShape.unknown,_unknown:()=>{throw new Error("Unknown ExampleTypeReferenceShape: "+e.type)}})}function imx(e){return ve.V8.types.ExampleSingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V7.types.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeName:fYt(t.typeName),shape:Wzl(t.shape)}),singleProperty:t=>ve.V7.types.ExampleSingleUnionTypeProperties.singleProperty({jsonExample:t.jsonExample,shape:$VO(t.shape)}),noProperties:ve.V7.types.ExampleSingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown ExampleSingleUnionTypeProperties: "+e.type)}})}function nmx(e){return{docs:e.docs,name:Hzl(e.name),discriminantValue:e.discriminantValue,type:e.type!=null?cX(e.type):void 0,statusCode:e.statusCode}}function Hzl(e){return{name:e.name,fernFilepath:Vzl(e.fernFilepath)}}function amx(e){return{docs:e.docs,availability:e.availability,name:{fernFilepath:Vzl(e.name.fernFilepath)},displayName:e.displayName,basePath:e.basePath,baseUrl:e.baseUrl,pathParameters:e.pathParameters.map(t=>GVO(t)),headers:e.headers.map(t=>qTu(t)),endpoints:e.endpoints.map(t=>omx(t))}}function GVO(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:cX(e.valueType)}}function omx(e){return{docs:e.docs,availability:e.availability,name:e.name,displayName:e.displayName,errors:e.errors.map(t=>umx(t)),auth:e.auth,method:e.method,path:e.path,pathParameters:e.pathParameters.map(t=>GVO(t)),sdkRequest:e.sdkRequest!=null?cmx(e.sdkRequest):void 0,requestBody:e.requestBody!=null?fmx(e.requestBody):void 0,response:dmx(e.response),headers:e.headers.map(t=>qTu(t)),queryParameters:e.queryParameters.map(t=>smx(t)),examples:e.examples.map(t=>pmx(t))}}function umx(e){return{docs:e.docs,error:Hzl(e.error)}}function smx(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:cX(e.valueType),allowMultiple:e.allowMultiple}}function cmx(e){return{requestParameterName:e.requestParameterName,shape:lmx(e.shape)}}function lmx(e){return ve.V8.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V7.http.SdkRequestShape.justRequestBody({docs:t.docs,requestBodyType:cX(t.requestBodyType)}),wrapper:ve.V7.http.SdkRequestShape.wrapper,_unknown:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function fmx(e){return ve.V8.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V7.http.HttpRequestBody.inlinedRequestBody({name:t.name,extends:t.extends.map(r=>fYt(r)),properties:t.properties.map(r=>({docs:r.docs,name:r.name,valueType:cX(r.valueType)}))}),reference:t=>ve.V7.http.HttpRequestBody.reference({docs:t.docs,requestBodyType:cX(t.requestBodyType)}),_unknown:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function dmx(e){return{docs:e.docs,type:e.type!=null?cX(e.type):void 0}}function pmx(e){return{name:e.name,docs:e.docs,servicePathParameters:e.servicePathParameters.map(t=>UVO(t)),endpointPathParameters:e.endpointPathParameters.map(t=>UVO(t)),queryParameters:e.queryParameters.map(t=>_mx(t)),serviceHeaders:e.serviceHeaders.map(t=>VVO(t)),endpointHeaders:e.endpointHeaders.map(t=>VVO(t)),request:e.request!=null?hmx(e.request):void 0,response:ymx(e.response)}}function UVO(e){return{key:e.key,value:Sle(e.value)}}function _mx(e){return{wireKey:e.wireKey,value:Sle(e.value)}}function VVO(e){return{wireKey:e.wireKey,value:Sle(e.value)}}function hmx(e){return ve.V8.http.ExampleRequestBody._visit(e,{inlinedRequestBody:t=>ve.V7.http.ExampleRequestBody.inlinedRequestBody({jsonExample:t.jsonExample,properties:t.properties.map(r=>({wireKey:r.wireKey,value:Sle(r.value),originalTypeDeclaration:r.originalTypeDeclaration!=null?fYt(r.originalTypeDeclaration):void 0}))}),reference:t=>ve.V7.http.ExampleRequestBody.reference(Sle(t)),_unknown:()=>{throw new Error("Unknown ExampleRequestBody: "+e.type)}})}function ymx(e){return ve.V8.http.ExampleResponse._visit(e,{ok:t=>ve.V7.http.ExampleResponse.ok({body:t.body!=null?Sle(t.body):void 0}),error:t=>ve.V7.http.ExampleResponse.error({error:Hzl(t.error),body:t.body!=null?Sle(t.body):void 0}),_unknown:()=>{throw new Error("Unknown ExampleResponse: "+e.type)}})}var QVO={laterVersion:"v9",earlierVersion:"v8",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.3.0-2-g85e8aa08",[$.TYPESCRIPT_EXPRESS]:"0.3.0-2-g85e8aa08",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.0.134-4-gef1ec4f",[$.JAVA_SDK]:"0.0.134-4-gef1ec4f",[$.JAVA_SPRING]:"0.0.134-4-gef1ec4f",[$.PYTHON_FASTAPI]:"0.0.51-1-g977dd1f",[$.PYTHON_PYDANTIC]:"0.0.51-1-g977dd1f",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:ar,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>{for(let[i,n]of Object.entries(e.types))n.shape._type==="union"&&n.shape.baseProperties.length>0&&t.failWithoutThrowing(r!=null?`Type ${n.name.name.originalName} uses base-properties. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains a union with base-properties.");return t.getResult()===BI.Failure&&t.failAndThrow(),{...e,types:Object.values(e.types),errors:Object.values(e.errors),services:Object.values(e.services)}}};var JVO={laterVersion:"v10",earlierVersion:"v9",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.STOPLIGHT]:ar,[$.OPENAPI]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>{let t=Sd(e.services,r=>({docs:void 0,...r}));for(let r of Object.values(e.subpackages))if(r.docs!=null&&r.service!=null){let i=t[r.service];if(i==null)throw new Error("Service does not exist: "+r.service);i.docs=r.docs}return{...e,services:t}}};var KVO={laterVersion:"v11",earlierVersion:"v10",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.0-rc0-1-g83a12940",[$.TYPESCRIPT_EXPRESS]:"0.5.0-rc0-1-g83a12940",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.0.134-15-ge1ac358",[$.JAVA_SDK]:"0.0.134-15-ge1ac358",[$.JAVA_SPRING]:"0.0.134-15-ge1ac358",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.STOPLIGHT]:ar,[$.OPENAPI]:Ne,[$.POSTMAN]:"0.0.40-1-g9aa2117",[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,t)=>({...e,auth:vmx(e.auth,t)})};function vmx(e,t){return{...e,schemes:e.schemes.map(r=>bmx(r,t))}}function bmx(e,{taskContext:t,targetGenerator:r}){return ve.V11.auth.AuthScheme._visit(e,{bearer:ve.V10.auth.AuthScheme.bearer,basic:ve.V10.auth.AuthScheme.basic,header:i=>i.prefix!=null?t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support specifying an auth header prefix. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains an auth header prefix."):ve.V10.auth.AuthScheme.header({docs:i.docs,availability:{status:ve.V10.commons.AvailabilityStatus.GeneralAvailability,message:void 0},name:{name:i.name,wireValue:i.header},valueType:i.valueType}),_unknown:()=>{throw new Error("Unknown auth scheme: "+e._type)}})}var XVO={laterVersion:"v12",earlierVersion:"v11",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.0-rc0-6-g80f89f98",[$.TYPESCRIPT_EXPRESS]:"0.5.0-rc0-6-g80f89f98",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.1.0-1-gdb5c636",[$.JAVA_SDK]:"0.1.0-1-gdb5c636",[$.JAVA_SPRING]:"0.1.0-1-gdb5c636",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.STOPLIGHT]:"0.0.23-8-g479c860",[$.OPENAPI]:"0.0.22-1-g1c86b58",[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>{let i=Sd(e.types,n=>({...n,shape:ve.V12.types.Type._visit(n.shape,{union:ve.V11.types.Type.union,enum:ve.V11.types.Type.enum,object:ve.V11.types.Type.object,alias:a=>ve.V11.types.Type.alias({aliasOf:a.aliasOf,resolvedType:ve.V12.types.ResolvedTypeReference._visit(a.resolvedType,{container:ve.V11.types.ResolvedTypeReference.container,primitive:ve.V11.types.ResolvedTypeReference.primitive,named:u=>u.shape==="UNDISCRIMINATED_UNION"?t.failAndThrow(YVO({taskContext:t,targetGenerator:r})):ve.V11.types.ResolvedTypeReference.named({shape:u.shape,name:u.name}),unknown:ve.V11.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Encountered unknown alias")}})}),undiscriminatedUnion:()=>t.failAndThrow(YVO({taskContext:t,targetGenerator:r})),_unknown:()=>{throw new Error("Encountered unknown shape")}})}));return{...e,types:i,services:Sd(e.services,n=>gmx(n,{taskContext:t,targetGenerator:r}))}}};function YVO(e){return e.targetGenerator!=null?`Generator ${e.targetGenerator.name}@${e.targetGenerator.version} does not support undiscriminated unions If you'd like to use this feature, please upgrade ${e.targetGenerator.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains an undiscriminated union."}function gmx(e,t){return{...e,endpoints:e.endpoints.map(r=>Omx(r,t))}}function Omx(e,{taskContext:t,targetGenerator:r}){return e.streamingResponse!=null?t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support streaming responses. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains a streaming response."):{...e,requestBody:e.requestBody!=null?ve.V12.http.HttpRequestBody._visit(e.requestBody,{inlinedRequestBody:ve.V11.http.HttpRequestBody.inlinedRequestBody,reference:ve.V11.http.HttpRequestBody.reference,fileUpload:()=>t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support file upload requests. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains a file upload request."),_unknown:()=>{throw new Error("Unknown HttpRequestBody type: "+e.requestBody?.type)}}):void 0,response:e.response!=null?{docs:e.response.docs,type:e.response.responseBodyType}:{docs:void 0,type:void 0}}}var ZVO={laterVersion:"v13",earlierVersion:"v12",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({...e,types:Sd(e.types,t=>t.shape._type!=="undiscriminatedUnion"?{...t,shape:t.shape}:{...t,shape:ve.V12.types.Type.undiscriminatedUnion({docs:void 0,members:t.shape.members})}),auth:{...e.auth,schemes:e.auth.schemes.map(t=>t._type!=="header"?t:{...t,name:t.name.name,header:t.name.wireValue})}})};var kVO={laterVersion:"v14",earlierVersion:"v13",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:ar,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>{let t=Sd(e.types,r=>({...r,shape:ve.V14.types.Type._visit(r.shape,{union:i=>ve.V13.types.Type.union({discriminant:i.discriminant,baseProperties:i.baseProperties.map(n=>({...n,valueType:AF(n.valueType)})),types:i.types.map(n=>jmx(n))}),enum:ve.V13.types.Type.enum,object:i=>ve.V13.types.Type.object({...i,properties:i.properties.map(n=>({...n,valueType:AF(n.valueType)}))}),alias:i=>ve.V13.types.Type.alias({aliasOf:AF(i.aliasOf),resolvedType:Smx(i.resolvedType)}),undiscriminatedUnion:i=>ve.V13.types.Type.undiscriminatedUnion(Dmx(i)),_unknown:()=>{throw new Error("Encountered unknown shape")}})}));return{...e,auth:mmx(e.auth),headers:e.headers.map(r=>Qzl(r)),types:t,services:Sd(e.services,r=>Emx(r)),errors:Sd(e.errors,r=>Imx(r))}}};function mmx(e){return{docs:e.docs,requirement:e.requirement,schemes:e.schemes.map(t=>t._type!=="header"?t:ve.V13.auth.AuthScheme.header(Pmx(t)))}}function Pmx(e){return{docs:e.docs,prefix:e.prefix,name:e.name,valueType:AF(e.valueType)}}function Qzl(e){return{docs:e.docs,availability:e.availability,name:e.name,valueType:AF(e.valueType)}}function AF(e){return ve.V14.types.TypeReference._visit(e,{container:t=>ve.V13.types.TypeReference.container(eWO(t)),primitive:t=>t==="DATE"?ve.V13.types.TypeReference.primitive(ve.V13.types.PrimitiveType.String):ve.V13.types.TypeReference.primitive(t),named:ve.V13.types.TypeReference.named,unknown:ve.V13.types.TypeReference.unknown,_unknown:()=>{throw new Error("Unknown type reference: "+e._type)}})}function eWO(e){return ve.V14.types.ContainerType._visit(e,{list:t=>ve.V13.types.ContainerType.list(AF(t)),optional:t=>ve.V13.types.ContainerType.optional(AF(t)),set:t=>ve.V13.types.ContainerType.set(AF(t)),map:({keyType:t,valueType:r})=>ve.V13.types.ContainerType.map({keyType:AF(t),valueType:AF(r)}),literal:ve.V13.types.ContainerType.literal,_unknown:()=>{throw new Error("Unknown ContainerType: "+e._type)}})}function jmx(e){return{docs:e.docs,discriminantValue:e.discriminantValue,shape:wmx(e.shape)}}function wmx(e){return ve.V14.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V13.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V13.types.SingleUnionTypeProperties.singleProperty({name:t.name,type:AF(t.type)}),noProperties:ve.V13.types.SingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+e._type)}})}function Smx(e){return ve.V14.types.ResolvedTypeReference._visit(e,{container:t=>ve.V13.types.ResolvedTypeReference.container(eWO(t)),named:ve.V13.types.ResolvedTypeReference.named,primitive:t=>t==="DATE"?ve.V13.types.ResolvedTypeReference.primitive(ve.V13.types.PrimitiveType.String):ve.V13.types.ResolvedTypeReference.primitive(t),unknown:ve.V13.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Unknown ResolvedTypeReference: "+e._type)}})}function Dmx(e){return{members:e.members.map(t=>({...t,type:AF(t.type)}))}}function Emx(e){return{availability:e.availability,name:e.name,displayName:e.displayName,basePath:e.basePath,baseUrl:e.baseUrl,pathParameters:e.pathParameters.map(t=>tWO(t)),headers:e.headers.map(t=>Qzl(t)),endpoints:e.endpoints.map(t=>Mmx(t))}}function tWO(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:AF(e.valueType)}}function Mmx(e){return{docs:e.docs,availability:e.availability,name:e.name,displayName:e.displayName,errors:e.errors,auth:e.auth,method:e.method,path:e.path,pathParameters:e.pathParameters.map(t=>tWO(t)),sdkRequest:e.sdkRequest!=null?qmx(e.sdkRequest):void 0,requestBody:e.requestBody!=null?Cmx(e.requestBody):void 0,response:e.response!=null?$zl(e.response):void 0,headers:e.headers.map(t=>Qzl(t)),queryParameters:e.queryParameters.map(t=>Amx(t)),examples:e.examples,streamingResponse:e.streamingResponse!=null?Gzl(e.streamingResponse):void 0,sdkResponse:e.sdkResponse!=null?Bmx(e.sdkResponse):void 0}}function Amx(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:AF(e.valueType),allowMultiple:e.allowMultiple}}function qmx(e){return{requestParameterName:e.requestParameterName,shape:Tmx(e.shape)}}function Tmx(e){return ve.V14.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V13.http.SdkRequestShape.justRequestBody({docs:t.docs,requestBodyType:AF(t.requestBodyType)}),wrapper:ve.V13.http.SdkRequestShape.wrapper,_unknown:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function Cmx(e){return ve.V14.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V13.http.HttpRequestBody.inlinedRequestBody({name:t.name,extends:t.extends,properties:t.properties.map(r=>({docs:r.docs,name:r.name,valueType:AF(r.valueType)}))}),reference:t=>ve.V13.http.HttpRequestBody.reference({docs:t.docs,requestBodyType:AF(t.requestBodyType)}),fileUpload:t=>ve.V13.http.HttpRequestBody.fileUpload({name:t.name,properties:t.properties.map(r=>r.type==="bodyProperty"?{...r,valueType:AF(r.valueType)}:r)}),_unknown:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function $zl(e){return{docs:e.docs,responseBodyType:AF(e.responseBodyType)}}function Gzl(e){return{dataEventType:AF(e.dataEventType),terminator:e.terminator}}function Bmx(e){return ve.V14.http.SdkResponse._visit(e,{streaming:t=>ve.V13.http.SdkResponse.streaming(Gzl(t)),nonStreaming:t=>ve.V13.http.SdkResponse.nonStreaming($zl(t)),maybeStreaming:t=>ve.V13.http.SdkResponse.maybeStreaming({condition:t.condition,nonStreaming:$zl(t.nonStreaming),streaming:Gzl(t.streaming)}),_unknown:()=>{throw new Error("Encountered unknown sdk response")}})}function Imx(e){return{docs:e.docs,name:e.name,discriminantValue:e.discriminantValue,type:e.type!=null?AF(e.type):void 0,statusCode:e.statusCode}}var rWO={laterVersion:"v15",earlierVersion:"v14",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.0.52-3-gd9df38df",[$.PYTHON_PYDANTIC]:"0.0.52-3-gd9df38df",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.0.52-3-gd9df38df",[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>{let t=Sd(e.types,r=>({...r,shape:ve.V15.types.Type._visit(r.shape,{union:i=>ve.V14.types.Type.union({discriminant:i.discriminant,baseProperties:i.baseProperties.map(n=>({...n,valueType:qF(n.valueType)})),types:i.types.map(n=>Rmx(n))}),enum:ve.V14.types.Type.enum,object:i=>ve.V14.types.Type.object({...i,properties:i.properties.map(n=>({...n,valueType:qF(n.valueType)}))}),alias:i=>ve.V14.types.Type.alias({aliasOf:qF(i.aliasOf),resolvedType:Fmx(i.resolvedType)}),undiscriminatedUnion:i=>ve.V14.types.Type.undiscriminatedUnion(Lmx(i)),_unknown:()=>{throw new Error("Encountered unknown shape")}})}));return{...e,auth:zmx(e.auth),headers:e.headers.map(r=>Yzl(r)),types:t,services:Sd(e.services,r=>Umx(r)),errors:Sd(e.errors,r=>Jmx(r))}}};function zmx(e){return{docs:e.docs,requirement:e.requirement,schemes:e.schemes.map(t=>t._type!=="header"?t:ve.V14.auth.AuthScheme.header(xmx(t)))}}function xmx(e){return{docs:e.docs,prefix:e.prefix,name:e.name,valueType:qF(e.valueType)}}function Yzl(e){return{docs:e.docs,availability:e.availability,name:e.name,valueType:qF(e.valueType)}}function qF(e){return ve.V15.types.TypeReference._visit(e,{container:t=>ve.V14.types.TypeReference.container(iWO(t)),primitive:t=>t==="BASE_64"?ve.V14.types.TypeReference.primitive(ve.V14.types.PrimitiveType.String):ve.V14.types.TypeReference.primitive(t),named:ve.V14.types.TypeReference.named,unknown:ve.V14.types.TypeReference.unknown,_unknown:()=>{throw new Error("Unknown type reference: "+e._type)}})}function iWO(e){return ve.V15.types.ContainerType._visit(e,{list:t=>ve.V14.types.ContainerType.list(qF(t)),optional:t=>ve.V14.types.ContainerType.optional(qF(t)),set:t=>ve.V14.types.ContainerType.set(qF(t)),map:({keyType:t,valueType:r})=>ve.V14.types.ContainerType.map({keyType:qF(t),valueType:qF(r)}),literal:ve.V14.types.ContainerType.literal,_unknown:()=>{throw new Error("Unknown ContainerType: "+e._type)}})}function Rmx(e){return{docs:e.docs,discriminantValue:e.discriminantValue,shape:Nmx(e.shape)}}function Nmx(e){return ve.V15.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V14.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V14.types.SingleUnionTypeProperties.singleProperty({name:t.name,type:qF(t.type)}),noProperties:ve.V14.types.SingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+e._type)}})}function Fmx(e){return ve.V15.types.ResolvedTypeReference._visit(e,{container:t=>ve.V14.types.ResolvedTypeReference.container(iWO(t)),named:ve.V14.types.ResolvedTypeReference.named,primitive:t=>t==="BASE_64"?ve.V14.types.ResolvedTypeReference.primitive(ve.V14.types.PrimitiveType.String):ve.V14.types.ResolvedTypeReference.primitive(t),unknown:ve.V14.types.ResolvedTypeReference.unknown,_unknown:()=>{throw new Error("Unknown ResolvedTypeReference: "+e._type)}})}function Lmx(e){return{members:e.members.map(t=>({...t,type:qF(t.type)}))}}function Umx(e){return{availability:e.availability,name:e.name,displayName:e.displayName,basePath:e.basePath,baseUrl:e.baseUrl,pathParameters:e.pathParameters.map(t=>nWO(t)),headers:e.headers.map(t=>Yzl(t)),endpoints:e.endpoints.map(t=>Vmx(t))}}function nWO(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:qF(e.valueType)}}function Vmx(e){return{docs:e.docs,availability:e.availability,name:e.name,displayName:e.displayName,errors:e.errors,auth:e.auth,method:e.method,path:e.path,pathParameters:e.pathParameters.map(t=>nWO(t)),sdkRequest:e.sdkRequest!=null?Hmx(e.sdkRequest):void 0,requestBody:e.requestBody!=null?Gmx(e.requestBody):void 0,response:e.response!=null?Jzl(e.response):void 0,headers:e.headers.map(t=>Yzl(t)),queryParameters:e.queryParameters.map(t=>Wmx(t)),examples:e.examples,streamingResponse:e.streamingResponse!=null?Kzl(e.streamingResponse):void 0,sdkResponse:e.sdkResponse!=null?Qmx(e.sdkResponse):void 0}}function Wmx(e){return{availability:e.availability,docs:e.docs,name:e.name,valueType:qF(e.valueType),allowMultiple:e.allowMultiple}}function Hmx(e){return{requestParameterName:e.requestParameterName,shape:$mx(e.shape)}}function $mx(e){return ve.V15.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V14.http.SdkRequestShape.justRequestBody({docs:t.docs,requestBodyType:qF(t.requestBodyType)}),wrapper:ve.V14.http.SdkRequestShape.wrapper,_unknown:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function Gmx(e){return ve.V15.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V14.http.HttpRequestBody.inlinedRequestBody({name:t.name,extends:t.extends,properties:t.properties.map(r=>({docs:r.docs,name:r.name,valueType:qF(r.valueType)}))}),reference:t=>ve.V14.http.HttpRequestBody.reference({docs:t.docs,requestBodyType:qF(t.requestBodyType)}),fileUpload:t=>ve.V14.http.HttpRequestBody.fileUpload({name:t.name,properties:t.properties.map(r=>r.type==="bodyProperty"?{...r,valueType:qF(r.valueType)}:r)}),_unknown:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function Jzl(e){return{docs:e.docs,responseBodyType:qF(e.responseBodyType)}}function Kzl(e){return{dataEventType:qF(e.dataEventType),terminator:e.terminator}}function Qmx(e){return ve.V15.http.SdkResponse._visit(e,{streaming:t=>ve.V14.http.SdkResponse.streaming(Kzl(t)),nonStreaming:t=>ve.V14.http.SdkResponse.nonStreaming(Jzl(t)),maybeStreaming:t=>ve.V14.http.SdkResponse.maybeStreaming({condition:t.condition,nonStreaming:Jzl(t.nonStreaming),streaming:Kzl(t.streaming)}),_unknown:()=>{throw new Error("Encountered unknown sdk response")}})}function Jmx(e){return{docs:e.docs,name:e.name,discriminantValue:e.discriminantValue,type:e.type!=null?qF(e.type):void 0,statusCode:e.statusCode}}var aWO={laterVersion:"v16",earlierVersion:"v15",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.4-1-g4e69d312",[$.TYPESCRIPT_EXPRESS]:"0.5.4-1-g4e69d312",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.3.8-rc6-1-gcf4b372",[$.JAVA_SDK]:"0.3.8-rc6-1-gcf4b372",[$.JAVA_SPRING]:"0.3.8-rc6-1-gcf4b372",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>e.basePath!=null?t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support specifying a base-path in api.yml. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains a root base-path."):{...e,services:Sd(e.services,i=>({...i,pathParameters:Xzl(i.pathParameters),endpoints:i.endpoints.map(n=>({...n,allPathParameters:Xzl(n.allPathParameters),pathParameters:Xzl(n.pathParameters)}))}))}};function Xzl(e){return e.map(t=>Kmx(t))}function Kmx(e){return{...e,availability:{status:ve.V15.commons.AvailabilityStatus.GeneralAvailability,message:void 0}}}var oWO={laterVersion:"v17",earlierVersion:"v16",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>{for(let[i,n]of Object.entries(e.types))if(n.shape._type==="union"&&n.shape.extends.length>0)return t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support union types with extensions. See ${i} in file ${n.name.fernFilepath.allParts.join("/")}. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains union types with extensions.");return{...e}}};var uWO={laterVersion:"v18",earlierVersion:"v17",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.14-1-ga6817141",[$.TYPESCRIPT_EXPRESS]:"0.5.14-1-ga6817141",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.3.0-3-ge125e311",[$.PYTHON_PYDANTIC]:"0.3.0-3-ge125e311",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.3.0-3-ge125e311",[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,{taskContext:t,targetGenerator:r})=>({...e,services:Sd(e.services,i=>{let n=i.endpoints[0]?.baseUrl;return i.endpoints.some(a=>a.baseUrl!==n)?t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support endpoint-level server URLs. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains endpoint-level server URLs."):{...i,baseUrl:n}})})};var cWO={laterVersion:"v19",earlierVersion:"v18",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:ar,[$.TYPESCRIPT_BROWSER_SDK]:ar,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.19-1-gef223230",[$.TYPESCRIPT_EXPRESS]:"0.5.19-1-gef223230",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.3.4-rc0-9-ge815162f",[$.PYTHON_PYDANTIC]:"0.3.4-rc0-9-ge815162f",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:"0.0.44-1-gbf4b0f3",[$.PYTHON_SDK]:"0.3.4-rc0-9-ge815162f",[$.GO_FIBER]:ar,[$.GO_MODEL]:ar,[$.GO_SDK]:ar,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,t)=>({...e,services:Sd(e.services,r=>Ymx(r,t)),types:Sd(e.types,r=>rPx(r,t))})};function Ymx(e,t){return{...e,endpoints:e.endpoints.map(r=>Xmx(r,t))}}function Xmx(e,t){return{...e,examples:e.examples.map(r=>Zmx(r,t))}}function Zmx(e,t){return{docs:e.docs,name:e.name,url:e.url,rootPathParameters:e.rootPathParameters.map(r=>Zzl(r,t)),servicePathParameters:e.servicePathParameters.map(r=>Zzl(r,t)),endpointPathParameters:e.endpointPathParameters.map(r=>Zzl(r,t)),serviceHeaders:e.serviceHeaders.map(r=>sWO(r,t)),endpointHeaders:e.endpointHeaders.map(r=>sWO(r,t)),queryParameters:e.queryParameters.map(r=>kmx(r,t)),request:e.request!=null?ePx(e.request,t):void 0,response:tPx(e.response,t)}}function Zzl(e,t){return{key:e.key,value:Dle(e.value,t)}}function sWO(e,t){return{wireKey:e.wireKey,value:Dle(e.value,t)}}function kmx(e,t){return{wireKey:e.wireKey,value:Dle(e.value,t)}}function ePx(e,t){return ve.V19.http.ExampleRequestBody._visit(e,{inlinedRequestBody:r=>ve.V18.http.ExampleRequestBody.inlinedRequestBody({jsonExample:r.jsonExample,properties:r.properties.map(i=>({wireKey:i.wireKey,value:Dle(i.value,t),originalTypeDeclaration:i.originalTypeDeclaration}))}),reference:r=>ve.V18.http.ExampleRequestBody.reference(Dle(r,t)),_unknown:()=>{throw new Error("Unknown ExampleRequestBody: "+e.type)}})}function tPx(e,t){return ve.V19.http.ExampleResponse._visit(e,{ok:r=>ve.V18.http.ExampleResponse.ok({body:r.body!=null?Dle(r.body,t):void 0}),error:r=>ve.V18.http.ExampleResponse.error({error:r.error,body:r.body!=null?Dle(r.body,t):void 0}),_unknown:()=>{throw new Error("Unknown ExampleResponse: "+e.type)}})}function rPx(e,t){return{...e,examples:e.examples.map(r=>iPx(r,t))}}function iPx(e,t){return{...e,shape:kzl(e.shape,t)}}function kzl(e,t){return ve.V19.types.ExampleTypeShape._visit(e,{alias:r=>ve.V18.types.ExampleTypeShape.alias({value:Dle(r.value,t)}),object:r=>ve.V18.types.ExampleTypeShape.object({properties:r.properties.map(i=>({wireKey:i.wireKey,value:Dle(i.value,t),originalTypeDeclaration:i.originalTypeDeclaration}))}),union:r=>ve.V18.types.ExampleTypeShape.union({wireDiscriminantValue:r.wireDiscriminantValue,properties:ve.V19.types.ExampleSingleUnionTypeProperties._visit(r.properties,{singleProperty:i=>ve.V18.types.ExampleSingleUnionTypeProperties.singleProperty({jsonExample:i.jsonExample,shape:lWO(i.shape,t)}),samePropertiesAsObject:i=>ve.V18.types.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeName:i.typeName,shape:kzl(i.shape,t)}),noProperties:ve.V18.types.ExampleSingleUnionTypeProperties.noProperties,_unknown:()=>{throw new Error("Unknown ExampleSingleUnionTypeProperties: "+r.properties.type)}})}),enum:ve.V18.types.ExampleTypeShape.enum,_unknown:()=>{throw new Error("Unknown ExampleTypeShape: "+e.type)}})}function Dle(e,t){return{jsonExample:e.jsonExample,shape:lWO(e.shape,t)}}function lWO(e,t){return ve.V19.types.ExampleTypeReferenceShape._visit(e,{primitive:r=>ve.V18.types.ExampleTypeReferenceShape.primitive(nPx(r,t)),named:r=>ve.V18.types.ExampleTypeReferenceShape.named({typeName:r.typeName,shape:kzl(r.shape,t)}),container:r=>ve.V18.types.ExampleTypeReferenceShape.container(ve.V19.types.ExampleContainer._visit(r,{list:i=>ve.V18.types.ExampleContainer.list(i.map(n=>Dle(n,t))),set:i=>ve.V18.types.ExampleContainer.set(i.map(n=>Dle(n,t))),optional:i=>ve.V18.types.ExampleContainer.optional(i!=null?Dle(i,t):void 0),map:i=>ve.V18.types.ExampleContainer.map(i.map(n=>({key:Dle(n.key,t),value:Dle(n.value,t)}))),_unknown:()=>{throw new Error("Unknown ExampleContainer: "+r.type)}})),unknown:ve.V18.types.ExampleTypeReferenceShape.unknown,_unknown:()=>{throw new Error("Unknown ExampleTypeReferenceShape: "+e.type)}})}function nPx(e,{taskContext:t,targetGenerator:r}){return e.type==="date"?t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support examples for dates. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains date examples."):e}var fWO={laterVersion:"v20",earlierVersion:"v19",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.5.26-rc0-3-gdfabd674",[$.TYPESCRIPT_BROWSER_SDK]:"0.5.26-rc0-3-gdfabd674",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.5.26-rc0-3-gdfabd674",[$.TYPESCRIPT_EXPRESS]:"0.5.20-3-g2505487f",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.3.10-rc2-1-g1c0d853",[$.JAVA_SDK]:"0.3.10-rc2-1-g1c0d853",[$.JAVA_SPRING]:"0.3.10-rc2-1-g1c0d853",[$.PYTHON_FASTAPI]:"0.3.6-rc1-2-g6050f7f8",[$.PYTHON_PYDANTIC]:"0.3.6-rc1-2-g6050f7f8",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.3.6-rc1-2-g6050f7f8",[$.GO_FIBER]:ar,[$.GO_MODEL]:"0.0.0",[$.GO_SDK]:"0.0.0",[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,t)=>({...e,services:Sd(e.services,r=>aPx(r,t))})};function aPx(e,t){return{...e,endpoints:e.endpoints.map(r=>oPx(r,t))}}function oPx(e,t){return{...e,response:e.response!=null?dWO(e.response,t):void 0,sdkResponse:e.sdkResponse!=null?uPx(e.sdkResponse,t):void 0}}function dWO(e,t){return ve.V20.http.HttpResponse._visit(e,{fileDownload:()=>pWO(t),json:r=>r,_unknown:()=>{throw new Error("Unknown HttpResponse: "+e.type)}})}function uPx(e,t){return ve.V20.http.SdkResponse._visit(e,{fileDownload:()=>pWO(t),streaming:ve.V19.http.SdkResponse.streaming,maybeStreaming:r=>ve.V19.http.SdkResponse.maybeStreaming({condition:r.condition,streaming:r.streaming,nonStreaming:dWO(r.nonStreaming,t)}),json:ve.V19.http.SdkResponse.nonStreaming,_unknown:()=>{throw new Error("Unknown SdkResponse: "+e.type)}})}function pWO({targetGenerator:e,taskContext:t}){return t.failAndThrow(e!=null?`Generator ${e.name}@${e.version} does not support file download. If you'd like to use this feature, please upgrade ${e.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains file download.")}var _WO={laterVersion:"v21",earlierVersion:"v20",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:ar,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,t)=>({...e,services:Sd(e.services,r=>sPx(r,t))})};function sPx(e,t){return{...e,endpoints:e.endpoints.map(r=>cPx(r,t))}}function cPx(e,t){return{...e,streamingResponse:e.streamingResponse!=null?exl(e.streamingResponse,t):void 0,sdkResponse:e.sdkResponse!=null?lPx(e.sdkResponse,t):void 0}}function exl(e,{taskContext:t,targetGenerator:r}){return{dataEventType:ve.V21.http.StreamingResponseChunkType._visit(e.dataEventType,{json:i=>i,text:()=>t.failAndThrow(r!=null?`Generator ${r.name}@${r.version} does not support streaming text responses. If you'd like to use this feature, please upgrade ${r.name} to a compatible version.`:"Cannot backwards-migrate IR because this IR contains streaming text responses."),_unknown:()=>{throw new Error("Unknown StreamingResponseChunkType: "+e.dataEventType.type)}}),terminator:e.terminator}}function lPx(e,t){return ve.V21.http.SdkResponse._visit(e,{fileDownload:ve.V20.http.SdkResponse.fileDownload,streaming:r=>ve.V20.http.SdkResponse.streaming(exl(r,t)),maybeStreaming:r=>ve.V20.http.SdkResponse.maybeStreaming({condition:r.condition,streaming:exl(r.streaming,t),nonStreaming:r.nonStreaming}),json:ve.V20.http.SdkResponse.json,_unknown:()=>{throw new Error("Unknown SdkResponse: "+e.type)}})}var hWO={laterVersion:"v22",earlierVersion:"v21",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.5.0-3-gac7ce7c",[$.GO_MODEL]:"0.0.14-8-g2fa39f7",[$.GO_SDK]:"0.0.14-8-g2fa39f7",[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:e=>({...e,services:Sd(e.services,t=>fPx(t))})};function fPx(e){return{...e,endpoints:e.endpoints.map(t=>dPx(t))}}function dPx(e){return{...e,...e.response!=null?ve.V22.http.HttpResponse._visit(e.response,{json:t=>({response:ve.V21.http.HttpResponse.json(t),streamingResponse:void 0,sdkResponse:ve.V21.http.SdkResponse.json(t)}),fileDownload:t=>({response:ve.V21.http.HttpResponse.fileDownload(t),streamingResponse:void 0,sdkResponse:ve.V21.http.SdkResponse.fileDownload(t)}),streaming:t=>({response:void 0,streamingResponse:t,sdkResponse:ve.V21.http.SdkResponse.streaming(t)}),_unknown:()=>{throw new Error("Unknown HttpResponse: "+e.response?.type)}}):{response:void 0,streamingResponse:void 0,sdkResponse:void 0}}}var bWO={laterVersion:"v23",earlierVersion:"v22",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.7.4-rc3-4-g6cf92f81",[$.TYPESCRIPT_BROWSER_SDK]:"0.7.4-rc3-4-g6cf92f81",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.7.4-rc3-4-g6cf92f81",[$.TYPESCRIPT_EXPRESS]:"0.7.4-rc3-4-g6cf92f81",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:"0.0.28-3-g112d3dd",[$.STOPLIGHT]:"0.0.28-3-g112d3dd",[$.POSTMAN]:"0.0.44-4-gddab2ae",[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>e,migrateBackwards:(e,t)=>{let r=[],i={};for(let[n,a]of Object.entries(e.services)){let u=[];for(let c of a.endpoints){let d=pPx(c);d==null?r.push(c):u.push(d)}i[n]={...a,endpoints:u,headers:a.headers.map(c=>rxl(c)),pathParameters:a.pathParameters.map(c=>TTu(c))}}return r.length>0&&(t.taskContext.logger.warn(`Generator ${t.targetGenerator?.name}@${t.targetGenerator?.version} does not support bytes requests. `),r.length===1&&r[0]!=null?t.taskContext.logger.warn(`Therefore, endpoint ${r[0].name.originalName} will be skipped.`):t.taskContext.logger.warn(`Therefore, endpoints ${r.map(n=>n.name.originalName).join(", ")} will be skipped.`)),{...e,auth:{...e.auth,schemes:e.auth.schemes.map(n=>hPx(n))},headers:e.headers.map(n=>rxl(n)),types:Sd(e.types,n=>yPx(n)),services:i,errors:Sd(e.errors,n=>PPx(n)),subpackages:e.subpackages,pathParameters:e.pathParameters.map(n=>TTu(n)),variables:e.variables.map(n=>jPx(n))}}};function pPx(e){let t;if(!(e.requestBody!=null&&(t=_Px(e.requestBody),t==null)))return{...e,headers:e.headers.map(r=>rxl(r)),pathParameters:e.pathParameters.map(r=>TTu(r)),allPathParameters:e.allPathParameters.map(r=>TTu(r)),queryParameters:e.queryParameters.map(r=>wPx(r)),requestBody:t,sdkRequest:e.sdkRequest!=null?{requestParameterName:e.sdkRequest.requestParameterName,shape:SPx(e.sdkRequest.shape)}:void 0,response:e.response!=null?DPx(e.response):void 0,examples:e.examples.map(r=>EPx(r))}}function _Px(e){switch(e.type){case"bytes":return;case"fileUpload":return ve.V22.http.HttpRequestBody.fileUpload({...e,properties:e.properties.map(t=>APx(t))});case"inlinedRequestBody":return ve.V22.http.HttpRequestBody.inlinedRequestBody({...e,properties:e.properties.map(t=>qPx(t))});case"reference":return ve.V22.http.HttpRequestBody.reference({...e,requestBodyType:TF(e.requestBodyType)});default:Ao(e)}}function rxl(e){return{...e,valueType:TF(e.valueType)}}function hPx(e){return e._visit({bearer:ve.V22.auth.AuthScheme.bearer,basic:ve.V22.auth.AuthScheme.basic,header:t=>ve.V22.auth.AuthScheme.header({...t,valueType:TF(t.valueType)}),_other:()=>{throw new Error("Unknown auth scheme: "+e.type)}})}function yPx(e){return{...e,shape:vPx(e.shape),examples:e.examples.map(t=>bPx(t))}}function vPx(e){return e._visit({alias:t=>ve.V22.types.Type.alias({...t,aliasOf:TF(t.aliasOf),resolvedType:OPx(t.resolvedType)}),enum:ve.V22.types.Type.enum,object:t=>ve.V22.types.Type.object({...t,properties:t.properties.map(r=>yWO(r))}),union:t=>ve.V22.types.Type.union({...t,baseProperties:t.baseProperties.map(r=>yWO(r)),types:t.types.map(r=>({...r,shape:mPx(r.shape)}))}),undiscriminatedUnion:t=>ve.V22.types.Type.undiscriminatedUnion({...t,members:t.members.map(r=>({...r,type:TF(r.type)}))}),_other:()=>{throw new Error("Unknown type shape: "+e.type)}})}function bPx(e){return{...e,shape:ixl(e.shape)}}function ixl(e){return e._visit({alias:t=>ve.V22.types.ExampleTypeShape.alias({...t,value:JCe(t.value)}),enum:ve.V22.types.ExampleTypeShape.enum,object:t=>ve.V22.types.ExampleTypeShape.object({...t,properties:t.properties.map(r=>({...r,value:JCe(r.value)}))}),union:t=>ve.V22.types.ExampleTypeShape.union({...t,properties:gPx(t.properties)}),_other:()=>{throw new Error("Unknown example type shape: "+e.type)}})}function JCe(e){return{...e,shape:nxl(e.shape)}}function nxl(e){return e._visit({primitive:t=>ve.V22.types.ExampleTypeReferenceShape.primitive(t._visit({integer:ve.V22.types.ExamplePrimitive.integer,double:ve.V22.types.ExamplePrimitive.double,string:ve.V22.types.ExamplePrimitive.string,boolean:ve.V22.types.ExamplePrimitive.boolean,long:ve.V22.types.ExamplePrimitive.long,datetime:r=>ve.V22.types.ExamplePrimitive.datetime(r.toISOString()),date:ve.V22.types.ExamplePrimitive.date,uuid:ve.V22.types.ExamplePrimitive.uuid,_other:()=>{throw new Error("Unknown example primitive: "+t.type)}})),named:t=>ve.V22.types.ExampleTypeReferenceShape.named({...t,shape:ixl(t.shape)}),container:t=>ve.V22.types.ExampleTypeReferenceShape.container(t._visit({list:r=>ve.V22.types.ExampleContainer.list(r.map(i=>JCe(i))),set:r=>ve.V22.types.ExampleContainer.set(r.map(i=>JCe(i))),optional:r=>ve.V22.types.ExampleContainer.optional(r!=null?JCe(r):void 0),map:r=>ve.V22.types.ExampleContainer.map(r.map(i=>({key:JCe(i.key),value:JCe(i.value)}))),_other:()=>{throw new Error("Unknown example container: "+t.type)}})),unknown:ve.V22.types.ExampleTypeReferenceShape.unknown,_other:()=>{throw new Error("Unknown example type reference shape: "+e.type)}})}function gPx(e){return e._visit({singleProperty:t=>ve.V22.types.ExampleSingleUnionTypeProperties.singleProperty({...t,shape:nxl(t.shape)}),noProperties:ve.V22.types.ExampleSingleUnionTypeProperties.noProperties,samePropertiesAsObject:t=>ve.V22.types.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...t,shape:ixl(t.shape)}),_other:()=>{throw new Error("Unknown example single union type properties: "+e.type)}})}function TF(e){return e._visit({container:t=>ve.V22.types.TypeReference.container(gWO(t)),primitive:ve.V22.types.TypeReference.primitive,named:ve.V22.types.TypeReference.named,unknown:ve.V22.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function gWO(e){return e._visit({list:t=>ve.V22.types.ContainerType.list(TF(t)),set:t=>ve.V22.types.ContainerType.set(TF(t)),optional:t=>ve.V22.types.ContainerType.optional(TF(t)),map:t=>ve.V22.types.ContainerType.map({keyType:TF(t.keyType),valueType:TF(t.valueType)}),literal:ve.V22.types.ContainerType.literal,_other:()=>{throw new Error("Unknown container type: "+e.type)}})}function OPx(e){return e._visit({container:t=>ve.V22.types.ResolvedTypeReference.container(gWO(t)),primitive:ve.V22.types.ResolvedTypeReference.primitive,named:ve.V22.types.ResolvedTypeReference.named,unknown:ve.V22.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown resolved type reference: "+e.type)}})}function yWO(e){return{...e,valueType:TF(e.valueType)}}function mPx(e){return e._visit({noProperties:ve.V22.types.SingleUnionTypeProperties.noProperties,singleProperty:t=>ve.V22.types.SingleUnionTypeProperties.singleProperty({...t,type:TF(t.type)}),samePropertiesAsObject:ve.V22.types.SingleUnionTypeProperties.samePropertiesAsObject,_other:()=>{throw new Error("Unknown single union type properties: "+e.propertiesType)}})}function PPx(e){return{...e,type:e.type!=null?TF(e.type):void 0}}function jPx(e){return{...e,type:TF(e.type)}}function TTu(e){return{...e,valueType:TF(e.valueType)}}function wPx(e){return{...e,valueType:TF(e.valueType)}}function SPx(e){return e._visit({justRequestBody:t=>ve.V22.http.SdkRequestShape.justRequestBody({...t,requestBodyType:TF(t.requestBodyType)}),wrapper:ve.V22.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SDK request shape: "+e.type)}})}function DPx(e){return e._visit({json:t=>ve.V22.http.HttpResponse.json({...t,responseBodyType:TF(t.responseBodyType)}),fileDownload:ve.V22.http.HttpResponse.fileDownload,streaming:t=>ve.V22.http.HttpResponse.streaming({...t,dataEventType:t.dataEventType._visit({json:r=>ve.V22.http.StreamingResponseChunkType.json(TF(r)),text:ve.V22.http.StreamingResponseChunkType.text,_other:()=>{throw new Error("Unknown streaming data event type: "+t.dataEventType.type)}})}),_other:()=>{throw new Error("Unknown response: "+e.type)}})}function EPx(e){return{...e,rootPathParameters:e.rootPathParameters.map(t=>txl(t)),servicePathParameters:e.servicePathParameters.map(t=>txl(t)),endpointPathParameters:e.endpointPathParameters.map(t=>txl(t)),serviceHeaders:e.serviceHeaders.map(t=>vWO(t)),endpointHeaders:e.endpointHeaders.map(t=>vWO(t)),queryParameters:e.queryParameters.map(t=>MPx(t)),request:e.request!=null?e.request._visit({inlinedRequestBody:t=>ve.V22.http.ExampleRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,value:JCe(r.value)}))}),reference:t=>ve.V22.http.ExampleRequestBody.reference({...t,shape:nxl(t.shape)}),_other:()=>{throw new Error("Unknown example request body: "+e.request?.type)}}):void 0,response:e.response._visit({ok:t=>ve.V22.http.ExampleResponse.ok({...t,body:t.body!=null?JCe(t.body):void 0}),error:t=>ve.V22.http.ExampleResponse.error({...t,body:t.body!=null?JCe(t.body):void 0}),_other:()=>{throw new Error("Unknown example response: "+e.response.type)}})}}function txl(e){return{...e,value:JCe(e.value)}}function MPx(e){return{...e,value:JCe(e.value)}}function vWO(e){return{...e,value:JCe(e.value)}}function APx(e){return e._visit({file:ve.V22.http.FileUploadRequestProperty.file,bodyProperty:t=>ve.V22.http.FileUploadRequestProperty.bodyProperty({...t,valueType:TF(t.valueType)}),_other:()=>{throw new Error("Unknown file upload request body property: "+e.type)}})}function qPx(e){return{...e,valueType:TF(e.valueType)}}var O_={};Na(O_,{V23:()=>dE4,V24:()=>pE4,V25:()=>_E4,V26:()=>hE4,V27:()=>yE4,V28:()=>vE4,V29:()=>bE4,V30:()=>gE4,V31:()=>OE4,V32:()=>mE4,V33:()=>PE4,V34:()=>jE4,V35:()=>wE4,V36:()=>SE4,V37:()=>DE4,V38:()=>EE4,V39:()=>ME4,V40:()=>AE4,V41:()=>qE4,V42:()=>TE4,V43:()=>CE4,V44:()=>BE4,V45:()=>IE4,V46:()=>zE4,V47:()=>xE4,V48:()=>RE4,V49:()=>NE4,V50:()=>FE4,V51:()=>LE4,V52:()=>UE4,V53:()=>VE4,V54:()=>WE4,V55:()=>HE4,V56:()=>$E4,V57:()=>GE4,V58:()=>QE4,V59:()=>Up});var dE4=ui(No(),1),pE4=ui(vo(),1),_E4=ui(oo(),1),hE4=ui(io(),1),yE4=ui(Qa(),1),vE4=ui(Ja(),1),bE4=ui(Ka(),1),gE4=ui(Ua(),1),OE4=ui(La(),1),mE4=ui(Da(),1),PE4=ui(Yn(),1),jE4=ui(Jn(),1),wE4=ui(zn(),1),SE4=ui(xn(),1),DE4=ui(Bn(),1),EE4=ui(An(),1),ME4=ui(pn(),1),AE4=ui(_n(),1),qE4=ui(ln(),1),TE4=ui(an(),1),CE4=ui(nn(),1),BE4=ui(tn(),1),IE4=ui(Ki(),1),zE4=ui(Vi(),1),xE4=ui(Ui(),1),RE4=ui(Fi(),1),NE4=ui(zi(),1),FE4=ui(Ai(),1),LE4=ui(Ei(),1),UE4=ui(gi(),1),VE4=ui($t(),1),WE4=ui(uv(),1),HE4=ui(Uy(),1),$E4=ui(Vy(),1),GE4=ui(ly(),1),QE4=ui(ly(),1);var Iyw={laterVersion:"v24",earlierVersion:"v23",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V23.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip"}),migrateBackwards:e=>({...e})};var zyw={laterVersion:"v25",earlierVersion:"v24",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.4.9-1-ge0997b3",[$.JAVA_SDK]:"0.4.9-1-ge0997b3",[$.JAVA_SPRING]:"0.4.9-1-ge0997b3",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V24.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip"}),migrateBackwards:(e,t)=>{let r=[],i=[],n={};for(let[a,u]of Object.entries(e.services)){let c=[];for(let d of u.endpoints){let s;if(d.sdkRequest!=null&&(s=JE4(d.sdkRequest),s==null)){r.push(d);continue}if(d.response!=null){let o=d.response._visit({fileDownload:l=>ve.V24.HttpResponse.fileDownload(l),json:l=>ve.V24.HttpResponse.json(l),streaming:l=>ve.V24.HttpResponse.streaming(l),text:()=>(i.push(d),ve.V24.HttpResponse.json({docs:void 0,responseBodyType:ve.V24.TypeReference.unknown()})),_other:()=>{throw new Error("Encountered unknown response type")}});c.push({...d,sdkRequest:s,response:o})}else c.push({...d,sdkRequest:s,response:void 0})}n[a]={...u,endpoints:c}}return i.length>0&&(t.taskContext.logger.warn(`Generator ${t.targetGenerator?.name}@${t.targetGenerator?.version} does not support text/plain responses. `),i.length===1&&i[0]!=null?t.taskContext.logger.warn(`Therefore, endpoint ${i[0].name.originalName} response type will be casted to unknown.`):t.taskContext.logger.warn(`Therefore, endpoints ${i.map(a=>a.name.originalName).join(", ")} response types will be casted to unknown.`)),r.length>0&&(t.taskContext.logger.warn(`Generator ${t.targetGenerator?.name}@${t.targetGenerator?.version} does not support bytes requests. `),r.length===1&&r[0]!=null?t.taskContext.logger.warn(`Therefore, endpoint ${r[0].name.originalName} will be skipped.`):t.taskContext.logger.warn(`Therefore, endpoints ${r.map(a=>a.name.originalName).join(", ")} will be skipped.`)),{...e,services:n}}};function JE4(e){let t=e.shape;if(t.type==="wrapper")return{shape:ve.V24.SdkRequestShape.wrapper({...t}),requestParameterName:e.requestParameterName};if(t.value.type==="typeReference")return{shape:ve.V24.SdkRequestShape.justRequestBody({...t.value}),requestParameterName:e.requestParameterName}}var Ryw={laterVersion:"v26",earlierVersion:"v25",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.5.0-rc2-16-g4177fafd",[$.PYTHON_PYDANTIC]:"0.5.0-rc2-16-g4177fafd",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.5.0-rc2-16-g4177fafd",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V25.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip"}),migrateBackwards:e=>({...e,types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,kE4(r)])),headers:e.headers.map(t=>VNs(t)),webhookGroups:Object.fromEntries(Object.entries(e.webhookGroups).map(([t,r])=>[t,r.map(i=>KE4(i))])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,YE4(r)]))})};function KE4(e){return{...e,headers:e.headers.map(t=>VNs(t)),availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function YE4(e){return{...e,endpoints:e.endpoints.map(t=>XE4(t)),headers:e.headers.map(t=>VNs(t)),availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function XE4(e){return{...e,headers:e.headers.map(t=>VNs(t)),queryParameters:e.queryParameters.map(t=>ZE4(t)),availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function VNs(e){return{...e,availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function ZE4(e){return{...e,availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function kE4(e){return{...e,shape:e.shape._visit({union:t=>ve.V25.Type.union({...t,baseProperties:t.baseProperties.map(r=>xyw(r))}),object:t=>ve.V25.Type.object({...t,properties:t.properties.map(r=>xyw(r))}),enum:t=>ve.V25.Type.enum({...t,values:t.values.map(r=>eM4(r))}),alias:t=>ve.V25.Type.alias(t),undiscriminatedUnion:t=>ve.V25.Type.undiscriminatedUnion(t),_other:()=>{throw new Error("Encountered unknown shape")}}),availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function xyw(e){return{...e,availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}function eM4(e){return{...e,availability:e.availability==null?{status:ve.V25.AvailabilityStatus.GeneralAvailability,message:void 0}:e.availability}}var Nyw={laterVersion:"v27",earlierVersion:"v26",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.6.1-3-g94ee67a",[$.GO_MODEL]:"0.6.1-3-g94ee67a",[$.GO_SDK]:"0.6.1-3-g94ee67a",[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V26.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip"}),migrateBackwards:e=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,tM4(r)]))})};function tM4(e){return{...e,endpoints:e.endpoints.map(t=>rM4(t))}}function rM4(e){return{...e,response:e.response!=null?iM4(e.response):void 0}}function iM4(e){if(e.type!=="json")return e;let t=e.value;return t.type==="response"?ve.V26.HttpResponse.json(t):ve.V26.HttpResponse.json({docs:t.docs,responseBodyType:t.responseBodyType})}var Fyw={laterVersion:"v28",earlierVersion:"v27",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.8.1-1-g0f40bf18",[$.TYPESCRIPT_BROWSER_SDK]:"0.8.1-1-g0f40bf18",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.8.1-1-g0f40bf18",[$.TYPESCRIPT_EXPRESS]:"0.8.1-1-g0f40bf18",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.9.0-2-g6b0be0e",[$.GO_MODEL]:"0.9.0-2-g6b0be0e",[$.GO_SDK]:"0.9.0-2-g6b0be0e",[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V27.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip"}),migrateBackwards:e=>({...e,auth:CM4(e.auth),headers:HNs(e.headers),types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,RM4(r)])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,pM4(r)])),webhookGroups:Object.fromEntries(Object.entries(e.webhookGroups).map(([t,r])=>[t,uM4(r)])),errors:Object.fromEntries(Object.entries(e.errors).map(([t,r])=>[t,oM4(r)])),pathParameters:WNs(e.pathParameters),variables:nM4(e.variables)})};function nM4(e){return e.map(t=>aM4(t))}function aM4(e){return{...e,type:B7(e.type)}}function oM4(e){return{...e,type:e.type!=null?B7(e.type):void 0}}function uM4(e){return e.map(t=>sM4(t))}function sM4(e){return{...e,headers:HNs(e.headers),payload:cM4(e.payload)}}function cM4(e){switch(e.type){case"inlinedPayload":return ve.V27.WebhookPayload.inlinedPayload(lM4(e));case"reference":return ve.V27.WebhookPayload.reference({...e,payloadType:B7(e.payloadType)})}}function lM4(e){return{...e,properties:fM4(e.properties)}}function fM4(e){return e.map(t=>dM4(t))}function dM4(e){return{...e,valueType:B7(e.valueType)}}function pM4(e){return{...e,endpoints:_M4(e.endpoints),headers:HNs(e.headers),pathParameters:WNs(e.pathParameters)}}function _M4(e){return e.map(t=>hM4(t))}function hM4(e){return{...e,headers:HNs(e.headers),pathParameters:WNs(e.pathParameters),allPathParameters:WNs(e.allPathParameters),queryParameters:qM4(e.queryParameters),requestBody:e.requestBody!=null?jM4(e.requestBody):void 0,sdkRequest:e.sdkRequest!=null?OM4(e.sdkRequest):void 0,response:e.response!=null?yM4(e.response):void 0}}function yM4(e){switch(e.type){case"json":return ve.V27.HttpResponse.json(gM4(e.value));case"fileDownload":return ve.V27.HttpResponse.fileDownload(e);case"text":return ve.V27.HttpResponse.text(e);case"streaming":return ve.V27.HttpResponse.streaming(vM4(e));default:Ao(e)}}function vM4(e){return{...e,dataEventType:bM4(e.dataEventType)}}function bM4(e){switch(e.type){case"json":return ve.V27.StreamingResponseChunkType.json(B7(e.json));case"text":return ve.V27.StreamingResponseChunkType.text();default:Ao(e)}}function gM4(e){switch(e.type){case"response":return ve.V27.JsonResponse.response({...e,responseBodyType:B7(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V27.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:B7(e.responseBodyType),responseProperty:e.responseProperty!=null?Wyw(e.responseProperty):void 0});default:Ao(e)}}function OM4(e){return{...e,shape:mM4(e.shape)}}function mM4(e){switch(e.type){case"justRequestBody":return ve.V27.SdkRequestShape.justRequestBody(PM4(e.value));case"wrapper":return ve.V27.SdkRequestShape.wrapper(e);default:Ao(e)}}function PM4(e){switch(e.type){case"typeReference":return ve.V27.SdkRequestBodyType.typeReference(Lyw(e));case"bytes":return ve.V27.SdkRequestBodyType.bytes(e);default:Ao(e)}}function jM4(e){switch(e.type){case"inlinedRequestBody":return ve.V27.HttpRequestBody.inlinedRequestBody(EM4(e));case"reference":return ve.V27.HttpRequestBody.reference(Lyw(e));case"fileUpload":return ve.V27.HttpRequestBody.fileUpload(wM4(e));case"bytes":return ve.V27.HttpRequestBody.bytes(e);default:Ao(e)}}function wM4(e){return{...e,properties:SM4(e.properties)}}function SM4(e){return e.map(t=>DM4(t))}function DM4(e){switch(e.type){case"file":return ve.V27.FileUploadRequestProperty.file(e);case"bodyProperty":return ve.V27.FileUploadRequestProperty.bodyProperty(Uyw(e));default:Ao(e)}}function Lyw(e){return{...e,requestBodyType:B7(e.requestBodyType)}}function EM4(e){return{...e,properties:MM4(e.properties)}}function MM4(e){return e.map(t=>Uyw(t))}function Uyw(e){return{...e,valueType:B7(e.valueType)}}function WNs(e){return e.map(t=>AM4(t))}function AM4(e){return{...e,valueType:B7(e.valueType)}}function qM4(e){return e.map(t=>TM4(t))}function TM4(e){return{...e,valueType:B7(e.valueType)}}function CM4(e){return{...e,schemes:BM4(e.schemes)}}function BM4(e){return e.map(t=>IM4(t))}function IM4(e){switch(e.type){case"basic":return ve.V27.AuthScheme.basic(e);case"bearer":return ve.V27.AuthScheme.bearer(e);case"header":return zM4(e);default:Ao(e)}}function zM4(e){return ve.V27.AuthScheme.header({...e,valueType:B7(e.valueType)})}function HNs(e){return e.map(t=>xM4(t))}function xM4(e){return{...e,valueType:B7(e.valueType)}}function RM4(e){return{...e,shape:NM4(e.shape)}}function NM4(e){switch(e.type){case"alias":return ve.V27.Type.alias(FM4(e));case"enum":return ve.V27.Type.enum(e);case"object":return ve.V27.Type.object(LM4(e));case"union":return ve.V27.Type.union(UM4(e));case"undiscriminatedUnion":return ve.V27.Type.undiscriminatedUnion(VM4(e));default:Ao(e)}}function FM4(e){return{aliasOf:B7(e.aliasOf),resolvedType:GM4(e.resolvedType)}}function LM4(e){return{...e,properties:Vyw(e.properties)}}function UM4(e){return{...e,types:WM4(e.types),baseProperties:Vyw(e.baseProperties)}}function VM4(e){return{members:$M4(e.members)}}function Vyw(e){return e.map(t=>Wyw(t))}function Wyw(e){return{...e,valueType:B7(e.valueType)}}function WM4(e){return e.map(t=>({...t,shape:HM4(t.shape)}))}function HM4(e){switch(e.propertiesType){case"samePropertiesAsObject":return ve.V27.SingleUnionTypeProperties.samePropertiesAsObject(e);case"singleProperty":return ve.V27.SingleUnionTypeProperties.singleProperty({name:e.name,type:B7(e.type)});case"noProperties":return ve.V27.SingleUnionTypeProperties.noProperties();default:Ao(e)}}function $M4(e){return e.map(t=>({...t,type:B7(t.type)}))}function GM4(e){switch(e.type){case"container":return e.container.type==="literal"?e.container.literal.type==="boolean"?ve.V27.ResolvedTypeReference.primitive(ve.V27.PrimitiveType.Boolean):ve.V27.ResolvedTypeReference.container(ve.V27.ContainerType.literal(ve.V27.Literal.string(e.container.literal.string))):ve.V27.ResolvedTypeReference.container(Hyw(e.container));case"named":return ve.V27.ResolvedTypeReference.named(e);case"primitive":return ve.V27.ResolvedTypeReference.primitive(e.primitive);case"unknown":return ve.V27.ResolvedTypeReference.unknown();default:Ao(e)}}function B7(e){switch(e.type){case"container":return e.container.type==="literal"?e.container.literal.type==="boolean"?ve.V27.TypeReference.primitive(ve.V27.PrimitiveType.Boolean):ve.V27.TypeReference.container(ve.V27.ContainerType.literal(ve.V27.Literal.string(e.container.literal.string))):ve.V27.TypeReference.container(Hyw(e.container));case"named":return ve.V27.TypeReference.named(e);case"primitive":return ve.V27.TypeReference.primitive(e.primitive);case"unknown":return ve.V27.TypeReference.unknown();default:Ao(e)}}function Hyw(e){switch(e.type){case"list":return ve.V27.ContainerType.list(B7(e.list));case"map":return ve.V27.ContainerType.map({keyType:B7(e.keyType),valueType:B7(e.valueType)});case"optional":return ve.V27.ContainerType.optional(B7(e.optional));case"set":return ve.V27.ContainerType.set(B7(e.set));case"literal":if(e.literal.type==="boolean")throw new Error("Internal error; failed to transform boolean literal between IR versions");return ve.V27.ContainerType.literal(ve.V27.Literal.string(e.literal.string));default:Ao(e)}}var Gyw={laterVersion:"v29",earlierVersion:"v28",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.8.6-1-g3d8d8591",[$.TYPESCRIPT_BROWSER_SDK]:"0.8.6-1-g3d8d8591",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.8.6-1-g3d8d8591",[$.TYPESCRIPT_EXPRESS]:"0.8.6-1-g3d8d8591",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.5.14-1-ge4bcd98",[$.JAVA_SDK]:"0.5.14-1-ge4bcd98",[$.JAVA_SPRING]:"0.5.14-1-ge4bcd98",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V28.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,types:Object.fromEntries(Object.keys(e.types).map(t=>[t,QM4({typeId:t,allTypes:e.types})]))})};function QM4({typeId:e,allTypes:t}){let r=$yw({typeId:e,allTypes:t});return{availability:r.availability,docs:r.docs,name:r.name,shape:r.shape,examples:r.examples,referencedTypes:Array.from(r.referencedTypes).map(i=>{let n=$yw({typeId:i,allTypes:t});return{typeId:i,fernFilepath:n.name.fernFilepath,name:n.name.name}})}}function $yw({typeId:e,allTypes:t}){let r=t[e];if(r==null)throw new Error(`Type definition for type id ${e} is undefined`);return r}var Qyw={laterVersion:"v30",earlierVersion:"v29",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.6.5-1-g0ef31b7a",[$.PYTHON_PYDANTIC]:"0.6.5-1-g0ef31b7a",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.6.5-1-g0ef31b7a",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V29.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=new iOd(e);return{...e,types:t.convertTypes(e.types),services:t.convertServices(e.services)}}},iOd=class{ir;constructor(t){this.ir=t}convertTypes(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,this.convertType(i)]))}convertServices(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,this.convertService(i)]))}convertService(t){return{...t,endpoints:this.convertEndpoints(t.endpoints)}}convertEndpoints(t){return t.map(r=>({...r,examples:this.convertExampleEndpointCalls(r.examples)}))}convertExampleEndpointCalls(t){return t.map(r=>({...r,rootPathParameters:this.convertExamplePathParameters(r.rootPathParameters),servicePathParameters:this.convertExamplePathParameters(r.servicePathParameters),endpointPathParameters:this.convertExamplePathParameters(r.endpointPathParameters),serviceHeaders:this.convertExampleHeaders(r.serviceHeaders),endpointHeaders:this.convertExampleHeaders(r.endpointHeaders),queryParameters:this.convertExampleQueryParameters(r.queryParameters),request:r.request!=null?this.convertExampleRequestBody(r.request):void 0,response:this.convertExampleResponse(r.response)}))}convertExamplePathParameters(t){return t.map(r=>({key:r.name.originalName,value:this.convertExampleTypeReference(r.value)}))}convertExampleHeaders(t){return t.map(r=>({wireKey:r.name.wireValue,value:this.convertExampleTypeReference(r.value)}))}convertExampleQueryParameters(t){return t.map(r=>({wireKey:r.name.wireValue,value:this.convertExampleTypeReference(r.value)}))}convertExampleRequestBody(t){switch(t.type){case"inlinedRequestBody":return ve.V29.ExampleRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,wireKey:r.name.wireValue,value:this.convertExampleTypeReference(r.value)}))});case"reference":return ve.V29.ExampleRequestBody.reference(this.convertExampleTypeReference(t));default:Ao(t)}}convertExampleResponse(t){switch(t.type){case"ok":return ve.V29.ExampleResponse.ok({body:t.body!=null?this.convertExampleTypeReference(t.body):void 0});case"error":return ve.V29.ExampleResponse.error({...t,body:t.body!=null?this.convertExampleTypeReference(t.body):void 0});default:Ao(t)}}convertType(t){return{...t,examples:this.convertExampleTypes(t.examples)}}convertExampleTypes(t){return t.map(r=>this.convertExampleType(r))}convertExampleType(t){return{...t,shape:this.convertExampleTypeShape(t.shape)}}convertExampleTypeReferences(t){return t.map(r=>this.convertExampleTypeReference(r))}convertExampleTypeReference(t){return{...t,shape:this.convertExampleTypeReferenceShape(t.shape)}}convertExampleTypeReferenceShape(t){switch(t.type){case"primitive":return ve.V29.ExampleTypeReferenceShape.primitive(this.convertExamplePrimitive(t.primitive));case"container":return ve.V29.ExampleTypeReferenceShape.container(this.convertExampleContainer(t.container));case"named":return ve.V29.ExampleTypeReferenceShape.named(this.convertExampleNamedType(t));case"unknown":return ve.V29.ExampleTypeReferenceShape.unknown(t);default:Ao(t)}}convertExamplePrimitive(t){switch(t.type){case"integer":return ve.V29.ExamplePrimitive.integer(t.integer);case"double":return ve.V29.ExamplePrimitive.double(t.double);case"string":return ve.V29.ExamplePrimitive.string(t.string.original);case"boolean":return ve.V29.ExamplePrimitive.boolean(t.boolean);case"long":return ve.V29.ExamplePrimitive.long(t.long);case"datetime":return ve.V29.ExamplePrimitive.datetime(t.datetime);case"date":return ve.V29.ExamplePrimitive.date(t.date);case"uuid":return ve.V29.ExamplePrimitive.uuid(t.uuid);default:Ao(t)}}convertExampleContainer(t){switch(t.type){case"list":return ve.V29.ExampleContainer.list(this.convertExampleTypeReferences(t.list));case"set":return ve.V29.ExampleContainer.set(this.convertExampleTypeReferences(t.set));case"optional":return ve.V29.ExampleContainer.optional(t.optional!=null?this.convertExampleTypeReference(t.optional):void 0);case"map":return ve.V29.ExampleContainer.map(this.convertKeyValuePairs(t.map));default:Ao(t)}}convertKeyValuePairs(t){return t.map(r=>({key:this.convertExampleTypeReference(r.key),value:this.convertExampleTypeReference(r.value)}))}convertExampleNamedType(t){return{...t,shape:this.convertExampleTypeShape(t.shape)}}convertExampleTypeShape(t){switch(t.type){case"alias":return ve.V29.ExampleTypeShape.alias({value:this.convertExampleTypeReference(t.value)});case"enum":return ve.V29.ExampleTypeShape.enum({wireValue:t.value.wireValue});case"object":return ve.V29.ExampleTypeShape.object(this.convertExampleObjectType(t));case"union":return ve.V29.ExampleTypeShape.union(this.convertExampleUnionType(t));default:Ao(t)}}convertExampleObjectType(t){return{properties:t.properties.map(r=>({...r,wireKey:r.name.wireValue,value:this.convertExampleTypeReference(r.value)}))}}convertExampleUnionType(t){return{wireDiscriminantValue:t.singleUnionType.wireDiscriminantValue.wireValue,properties:this.convertExampleSingleUnionTypeProperties(t.singleUnionType.shape)}}convertExampleSingleUnionTypeProperties(t){switch(t.type){case"samePropertiesAsObject":{let r=this.ir.types[t.typeId]?.name;if(r==null)throw new Error(`Internal error; type ID ${t.typeId} does not exist in the IR`);return ve.V29.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeName:r,shape:this.convertExampleTypeShape(ve.V30.ExampleTypeShape.object({properties:t.object.properties}))})}case"singleProperty":return ve.V29.ExampleSingleUnionTypeProperties.singleProperty({...t,shape:this.convertExampleTypeReferenceShape(t.shape)});case"noProperties":return ve.V29.ExampleSingleUnionTypeProperties.noProperties();default:Ao(t)}}};var Jyw={laterVersion:"v31",earlierVersion:"v30",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.8.8",[$.TYPESCRIPT_BROWSER_SDK]:"0.8.8",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.8.8",[$.TYPESCRIPT_EXPRESS]:"0.8.8",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.7.0-rc0",[$.JAVA_SDK]:"0.7.0-rc0",[$.JAVA_SPRING]:"0.7.0-rc0",[$.PYTHON_FASTAPI]:"0.7.5-1-gb54fb677",[$.PYTHON_PYDANTIC]:"0.7.5-1-gb54fb677",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.7.5-1-gb54fb677",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:ar,[$.RUBY_SDK]:ar,[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V30.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({apiName:e.apiName,apiDisplayName:e.apiDisplayName,apiDocs:e.apiDocs,auth:e.auth,headers:e.headers,types:e.types,webhookGroups:e.webhookGroups,errors:e.errors,subpackages:e.subpackages,rootPackage:e.rootPackage,constants:e.constants,environments:e.environments,basePath:e.basePath,pathParameters:e.pathParameters,errorDiscriminationStrategy:e.errorDiscriminationStrategy,sdkConfig:e.sdkConfig,variables:e.variables,serviceTypeReferenceInfo:e.serviceTypeReferenceInfo,services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{availability:r.availability,name:r.name,displayName:r.displayName,basePath:r.basePath,endpoints:r.endpoints.map(i=>({id:i.id,docs:i.docs,availability:i.availability,name:i.name,displayName:i.displayName,method:i.method,headers:i.headers,baseUrl:i.baseUrl,path:i.path,fullPath:i.fullPath,pathParameters:i.pathParameters,allPathParameters:i.allPathParameters,queryParameters:i.queryParameters,requestBody:i.requestBody,sdkRequest:i.sdkRequest,response:i.response,errors:i.errors,auth:i.auth,examples:i.examples})),headers:r.headers,pathParameters:r.pathParameters}]))})};var Yyw={laterVersion:"v32",earlierVersion:"v31",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.9.4-2-g139cf36",[$.GO_MODEL]:"0.9.4-2-g139cf36",[$.GO_SDK]:"0.9.4-2-g139cf36",[$.RUBY_MODEL]:"0.0.0",[$.RUBY_SDK]:"0.0.0",[$.CSHARP_MODEL]:ar,[$.CSHARP_SDK]:ar,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V31.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,{...r,examples:kM4(r.examples)}])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(JM4)}]))})};function GIn({examples:e,convert:t}){let r=[];for(let i of e){let n=t(i);n!=null&&r.push(n)}return r}function JM4(e){return{...e,examples:GIn({examples:e.examples,convert:KM4})}}function KM4(e){let t;if(e.request!=null&&(t=YM4(e.request),t==null))return;let r=XM4(e.response);if(r!=null)return{...e,rootPathParameters:GIn({examples:e.rootPathParameters,convert:nOd}),endpointPathParameters:GIn({examples:e.endpointPathParameters,convert:nOd}),servicePathParameters:GIn({examples:e.servicePathParameters,convert:nOd}),endpointHeaders:GIn({examples:e.endpointHeaders,convert:Kyw}),serviceHeaders:GIn({examples:e.serviceHeaders,convert:Kyw}),queryParameters:GIn({examples:e.queryParameters,convert:ZM4}),request:t,response:r}}function YM4(e){switch(e.type){case"inlinedRequestBody":{let t=[];for(let r of e.properties){let i=gEe(r.value);i!=null&&t.push({...r,value:i})}return ve.V31.ExampleRequestBody.inlinedRequestBody({...e,properties:t})}case"reference":{let t=aOd(e.shape);return t==null?void 0:ve.V31.ExampleRequestBody.reference({...e,shape:t})}default:Ao(e)}}function XM4(e){switch(e.type){case"ok":{if(e.body==null)return ve.V31.ExampleResponse.ok({body:void 0});let t=gEe(e.body);return t==null?void 0:ve.V31.ExampleResponse.ok({body:t})}case"error":{if(e.body==null)return ve.V31.ExampleResponse.error({...e,body:void 0});let t=gEe(e.body);return t==null?void 0:ve.V31.ExampleResponse.error({...e,body:t})}}}function nOd(e){let t=gEe(e.value);if(t!=null)return{...e,value:t}}function Kyw(e){let t=gEe(e.value);if(t!=null)return{...e,value:t}}function ZM4(e){let t=gEe(e.value);if(t!=null)return{...e,value:t}}function kM4(e){let t=[];for(let r of e){let i=eA4(r);i!=null&&t.push(i)}return t}function eA4(e){let t=Xyw(e.shape);if(t!=null)return{...e,shape:t}}function Xyw(e){switch(e.type){case"enum":return ve.V31.ExampleTypeShape.enum(e);case"alias":{let t=gEe(e.value);return t==null?void 0:ve.V31.ExampleTypeShape.alias({value:t})}case"object":{let t=[];for(let r of e.properties){let i=gEe(r.value);i!=null&&t.push({...r,value:i})}return ve.V31.ExampleTypeShape.object({properties:t})}case"union":{let t=tA4(e.singleUnionType);return t==null?void 0:ve.V31.ExampleTypeShape.union({...e,singleUnionType:t})}case"undiscriminatedUnion":return;default:Ao(e)}}function gEe(e){let t=aOd(e.shape);if(t!=null)return{shape:t,jsonExample:e.jsonExample}}function tA4(e){let t=rA4(e.shape);if(t!=null)return{...e,shape:t}}function rA4(e){switch(e.type){case"noProperties":return ve.V31.ExampleSingleUnionTypeProperties.noProperties();case"singleProperty":{let t=aOd(e.shape);return t==null?void 0:ve.V31.ExampleSingleUnionTypeProperties.singleProperty({...e,shape:t})}case"samePropertiesAsObject":{let t=[];for(let r of e.object.properties){let i=gEe(r.value);i!=null&&t.push({...r,value:i})}return ve.V31.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...e,object:{properties:t}})}default:Ao(e)}}function aOd(e){switch(e.type){case"container":{let t=iA4(e.container);return t==null?void 0:ve.V31.ExampleTypeReferenceShape.container(t)}case"named":{let t=Xyw(e.shape);return t==null?void 0:ve.V31.ExampleTypeReferenceShape.named({...e,shape:t})}case"primitive":return ve.V31.ExampleTypeReferenceShape.primitive(e.primitive);case"unknown":return ve.V31.ExampleTypeReferenceShape.unknown(e.unknown);default:Ao(e)}}function iA4(e){switch(e.type){case"list":{let t=[];for(let r of e.list){let i=gEe(r);i!=null&&t.push(i)}return ve.V31.ExampleContainer.list(t)}case"set":{let t=[];for(let r of e.set){let i=gEe(r);i!=null&&t.push(i)}return ve.V31.ExampleContainer.set(t)}case"map":{let t=[];for(let r of e.map){let i=gEe(r.key),n=gEe(r.value);i!=null&&n!=null&&t.push({key:i,value:n})}return ve.V31.ExampleContainer.map(t)}case"optional":{if(e.optional==null)return ve.V31.ExampleContainer.optional();let t=gEe(e.optional);return t==null?ve.V31.ExampleContainer.optional():ve.V31.ExampleContainer.optional(t)}default:Ao(e)}}var Zyw={laterVersion:"v33",earlierVersion:"v32",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.12.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.12.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.12.0",[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.13.0-3-g8c56a41",[$.GO_MODEL]:"0.13.0-3-g8c56a41",[$.GO_SDK]:"0.13.0-3-g8c56a41",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:"0.0.0",[$.CSHARP_SDK]:"0.0.0",[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V32.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=new oOd(e);return{...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>t.convertEndpoint(n))}]))}}},oOd=class{ir;constructor(t){this.ir=t}convertEndpoint(t){return{...t,queryParameters:t.queryParameters.map(r=>this.isTypeReferenceObject(r.valueType)?{...r,valueType:ve.V33.TypeReference.container(ve.V33.ContainerType.optional(ve.V33.TypeReference.primitive("STRING")))}:r),examples:nA4({examples:t.examples,convert:aA4})}}isTypeReferenceObject(t){switch(t.type){case"container":return this.isContainerObject(t.container);case"named":return this.isNamedTypeObject(t);case"primitive":return!1;case"unknown":return!0;default:Ao(t)}}isContainerObject(t){switch(t.type){case"map":case"list":case"set":return!0;case"optional":return this.isTypeReferenceObject(t.optional);case"literal":return!1;default:Ao(t)}}isNamedTypeObject(t){let r=this.ir.types[t.typeId];if(r==null)return!0;switch(r.shape.type){case"alias":return this.isTypeReferenceObject(r.shape.aliasOf);case"enum":return!1;case"object":case"union":case"undiscriminatedUnion":return!0;default:Ao(r.shape)}}};function nA4({examples:e,convert:t}){let r=[];for(let i of e){let n=t(i);n!=null&&r.push(n)}return r}function aA4(e){return{...e,queryParameters:e.queryParameters.filter(t=>!uOd(t.value))}}function uOd(e){switch(e.shape.type){case"container":return oA4(e.shape.container);case"named":return uA4(e.shape);case"primitive":return!1;case"unknown":return!0;default:Ao(e.shape)}}function oA4(e){switch(e.type){case"map":case"list":case"set":return!0;case"optional":return e.optional!=null&&uOd(e.optional);default:Ao(e)}}function uA4(e){switch(e.shape.type){case"alias":return uOd(e.shape.value);case"enum":return!1;case"object":case"union":case"undiscriminatedUnion":return!0;default:Ao(e.shape)}}var bwa=ui(rdl(),1);var kyw={laterVersion:"v34",earlierVersion:"v33",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.10.4",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V33.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>({...n,requestBody:n.requestBody?._visit({inlinedRequestBody:a=>bwa.FernIrV33.HttpRequestBody.inlinedRequestBody(a),reference:a=>bwa.FernIrV33.HttpRequestBody.reference(a),fileUpload:a=>bwa.FernIrV33.HttpRequestBody.fileUpload({...a,properties:a.properties.map(u=>(u.type==="file"&&u.value.type==="fileArray"&&t.taskContext.logger.warn(`${n.method} ${n.fullPath.head} accepts a list of files however the ${t.targetGenerator?.name}@${t.targetGenerator?.version} only supports accepting a single file. File an [issue](https://github.com/fern-api/fern/issues) to add request for file arrays in ${t.targetGenerator?.name}@${t.targetGenerator?.version}!`),u.type==="file"?bwa.FernIrV33.FileUploadRequestProperty.file({...u.value}):u))}),bytes:a=>bwa.FernIrV33.HttpRequestBody.bytes(a),_other:a=>{}})}))}]))})};var evw={laterVersion:"v35",earlierVersion:"v34",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.18.0",[$.GO_MODEL]:"0.18.0",[$.GO_SDK]:"0.18.0",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V34.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>({docs:i.docs,availability:i.availability,id:i.id,name:i.name,displayName:i.displayName,method:i.method,headers:i.headers,baseUrl:i.baseUrl,path:i.path,fullPath:i.fullPath,pathParameters:i.pathParameters,allPathParameters:i.allPathParameters,queryParameters:i.queryParameters,requestBody:i.requestBody,sdkRequest:i.sdkRequest,response:i.response,errors:i.errors,auth:i.auth,idempotent:i.idempotent,examples:i.examples}))}]))})};var tvw={laterVersion:"v36",earlierVersion:"v35",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.11.6",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V35.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e})};var rvw={laterVersion:"v37",earlierVersion:"v36",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.13.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.13.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.13.0",[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"0.12.0",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V36.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>({...n,examples:n.examples.filter(a=>a.exampleType==="userProvided")}))}]))})};var ivw={laterVersion:"v38",earlierVersion:"v37",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.15.0-rc0",[$.TYPESCRIPT_BROWSER_SDK]:"0.15.0-rc0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.15.0-rc0",[$.TYPESCRIPT_EXPRESS]:"0.12.0-rc0",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.9.0-rc0",[$.PYTHON_PYDANTIC]:"0.9.0-rc0",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"1.2.0-rc0",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V37.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>({...n,response:n.response?._visit({fileDownload:a=>ve.V37.HttpResponse.fileDownload(a),json:a=>ve.V37.HttpResponse.json(a),streaming:a=>a._visit({json:u=>ve.V37.HttpResponse.streaming({dataEventType:ve.V37.StreamingResponseChunkType.json(u.payload),docs:u.docs,terminator:u.terminator}),sse:()=>{},text:u=>ve.V37.HttpResponse.streaming({dataEventType:ve.V37.StreamingResponseChunkType.text(),docs:u.docs,terminator:void 0}),_other:()=>{}}),text:a=>ve.V37.HttpResponse.text(a),_other:()=>{}})}))}]))})};var nvw={laterVersion:"v39",earlierVersion:"v38",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.9.0-rc1",[$.PYTHON_PYDANTIC]:"0.9.0-rc1",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"1.4.0-rc1",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:"0.7.0-rc0",[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V38.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,auth:{...e.auth,schemes:e.auth.schemes.map(r=>sA4(r))}})};function sA4(e){switch(e.type){case"basic":return ve.V38.AuthScheme.basic(e);case"bearer":return ve.V38.AuthScheme.bearer(e);case"header":return ve.V38.AuthScheme.header(e);case"oauth":return ve.V38.AuthScheme.bearer({docs:e.docs,token:{originalName:"token",camelCase:{unsafeName:"token",safeName:"token"},pascalCase:{unsafeName:"Token",safeName:"Token"},snakeCase:{unsafeName:"token",safeName:"token"},screamingSnakeCase:{unsafeName:"TOKEN",safeName:"TOKEN"}},tokenEnvVar:void 0});default:Ao(e)}}var avw={laterVersion:"v40",earlierVersion:"v39",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:"0.20.0",[$.GO_MODEL]:"0.20.0",[$.GO_SDK]:"0.20.0",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V39.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e})};var ovw={laterVersion:"v41",earlierVersion:"v40",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V40.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,errors:Object.fromEntries(Object.entries(e.errors).map(([r,i])=>[r,{name:i.name,discriminantValue:i.discriminantValue,type:i.type,statusCode:i.statusCode,docs:i.docs}]))})};var uvw={laterVersion:"v42",earlierVersion:"v41",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.8.0-rc0",[$.JAVA_SDK]:"0.9.0-rc0",[$.JAVA_SPRING]:"0.8.0-rc0",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V41.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,auth:{...e.auth,schemes:e.auth.schemes.map(r=>cA4(r))}})};function cA4(e){switch(e.type){case"basic":return ve.V41.AuthScheme.basic(e);case"bearer":return ve.V41.AuthScheme.bearer(e);case"header":return ve.V41.AuthScheme.header(e);case"oauth":return ve.V41.AuthScheme.oauth(lA4(e));default:Ao(e)}}function lA4(e){switch(e.configuration.type){case"clientCredentials":return{...e,configuration:ve.V41.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:{...e.configuration.tokenEndpoint,endpointReference:e.configuration.tokenEndpoint.endpointReference.endpointId},refreshEndpoint:e.configuration.refreshEndpoint!=null?{...e.configuration.refreshEndpoint,endpointReference:e.configuration.refreshEndpoint?.endpointReference.endpointId}:void 0})};default:Ao(e.configuration.type)}}var svw={laterVersion:"v43",earlierVersion:"v42",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.17.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.17.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.17.0",[$.TYPESCRIPT_EXPRESS]:"0.13.0",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V42.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>({...n,response:n.response?.body}))}]))})};var lvw={laterVersion:"v44",earlierVersion:"v43",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V43.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:(e,t)=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([r,i])=>[r,{...i,endpoints:i.endpoints.map(n=>({...n,examples:n.examples.map(a=>fA4({example:a})).filter(yy)}))}]))})};function fA4({example:e}){return e._visit({userProvided:t=>ve.V43.HttpEndpointExample.userProvided(cvw({example:t})),generated:t=>ve.V43.HttpEndpointExample.generated(cvw({example:t})),_other:()=>{}})}function cvw({example:e}){return{...e,response:dA4({example:e.response})}}function dA4({example:e}){switch(e.type){case"ok":return pA4({example:e.value});case"error":return ve.V43.ExampleResponse.error(e);default:Ao(e)}}function pA4({example:e}){switch(e.type){case"body":return ve.V43.ExampleResponse.ok({body:e.value});case"sse":return ve.V43.ExampleResponse.ok({body:void 0});case"stream":return ve.V43.ExampleResponse.ok({body:void 0});default:Ao(e)}}var fvw={laterVersion:"v45",earlierVersion:"v44",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V44.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=Sd(e.types,r=>({...r,shape:ve.V45.types.Type._visit(r.shape,{union:i=>ve.V44.types.Type.union({...i,baseProperties:i.baseProperties.map(n=>({...n,valueType:YC(n.valueType)})),types:i.types.map(n=>SA4(n))}),enum:ve.V44.types.Type.enum,object:i=>ve.V44.types.Type.object({...i,properties:i.properties.map(n=>({...n,valueType:YC(n.valueType)}))}),alias:i=>ve.V44.types.Type.alias({aliasOf:YC(i.aliasOf),resolvedType:EA4(i.resolvedType)}),undiscriminatedUnion:i=>ve.V44.types.Type.undiscriminatedUnion(MA4(i)),_other:()=>{throw new Error("Encountered unknown shape")}})}));return{...e,auth:OA4(e.auth),headers:e.headers.map(r=>gwa(r)),idempotencyHeaders:e.idempotencyHeaders.map(r=>gwa(r)),types:t,services:Sd(e.services,r=>AA4(r)),errors:Sd(e.errors,r=>$A4(r)),webhookGroups:Sd(e.webhookGroups,r=>vA4(r)),websocketChannels:Sd(e.websocketChannels,r=>_A4(r)),pathParameters:e.pathParameters.map(r=>LOo(r)),variables:e.variables.map(r=>qA4(r))}}};function _A4(e){return{...e,headers:e.headers.map(t=>gwa(t)),queryParameters:e.queryParameters.map(t=>UOo(t)),pathParameters:e.pathParameters.map(t=>LOo(t)),messages:e.messages.map(t=>hA4(t))}}function hA4(e){return{...e,body:yA4(e.body)}}function yA4(e){switch(e.type){case"inlinedBody":return ve.V44.websocket.WebSocketMessageBody.inlinedBody({...e,properties:e.properties.map(t=>({...t,valueType:YC(t.valueType)}))});case"reference":return ve.V44.websocket.WebSocketMessageBody.reference({...e,bodyType:YC(e.bodyType)})}}function vA4(e){return e.map(t=>bA4(t))}function bA4(e){return{...e,headers:e.headers.map(t=>gwa(t)),payload:gA4(e.payload)}}function gA4(e){switch(e.type){case"reference":return ve.V44.webhooks.WebhookPayload.reference({...e,payloadType:YC(e.payloadType)});case"inlinedPayload":return ve.V44.webhooks.WebhookPayload.inlinedPayload({...e,properties:e.properties.map(t=>({...t,valueType:YC(t.valueType)}))})}}function OA4(e){return{...e,schemes:e.schemes.map(t=>{switch(t.type){case"basic":return ve.V44.auth.AuthScheme.basic(t);case"bearer":return ve.V44.auth.AuthScheme.bearer(t);case"header":return ve.V44.auth.AuthScheme.header(mA4(t));case"oauth":return ve.V44.auth.AuthScheme.oauth(PA4(t))}})}}function mA4(e){return{...e,valueType:YC(e.valueType)}}function PA4(e){return{...e,configuration:ve.V44.auth.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:jA4(e.configuration.tokenEndpoint),refreshEndpoint:e.configuration.refreshEndpoint!=null?wA4(e.configuration.refreshEndpoint):void 0})}}function jA4(e){return{...e,requestProperties:{clientId:$Ns(e.requestProperties.clientId),clientSecret:$Ns(e.requestProperties.clientSecret),scopes:e.requestProperties.scopes!=null?$Ns(e.requestProperties.scopes):void 0},responseProperties:{accessToken:bAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?bAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?bAi(e.responseProperties.refreshToken):void 0}}}function wA4(e){return{...e,requestProperties:{refreshToken:$Ns(e.requestProperties.refreshToken)},responseProperties:{accessToken:bAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?bAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?bAi(e.responseProperties.refreshToken):void 0}}}function gwa(e){return{...e,valueType:YC(e.valueType)}}function YC(e){return ve.V45.types.TypeReference._visit(e,{container:t=>ve.V44.types.TypeReference.container(dvw(t)),primitive:t=>t.v1==="BIG_INTEGER"?ve.V44.types.TypeReference.primitive(ve.V44.types.PrimitiveType.String):ve.V44.types.TypeReference.primitive(t.v1),named:ve.V44.types.TypeReference.named,unknown:ve.V44.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function dvw(e){return ve.V45.types.ContainerType._visit(e,{list:t=>ve.V44.types.ContainerType.list(YC(t)),optional:t=>ve.V44.types.ContainerType.optional(YC(t)),set:t=>ve.V44.types.ContainerType.set(YC(t)),map:({keyType:t,valueType:r})=>ve.V44.types.ContainerType.map({keyType:YC(t),valueType:YC(r)}),literal:ve.V44.types.ContainerType.literal,_other:()=>{throw new Error("Unknown ContainerType: "+e.type)}})}function SA4(e){return{...e,shape:DA4(e.shape)}}function DA4(e){return ve.V45.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V44.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V44.types.SingleUnionTypeProperties.singleProperty({...t,type:YC(t.type)}),noProperties:ve.V44.types.SingleUnionTypeProperties.noProperties,_other:()=>{throw new Error(`Unknown SingleUnionTypeProperties: ${JSON.stringify(e)}`)}})}function EA4(e){return ve.V45.types.ResolvedTypeReference._visit(e,{container:t=>ve.V44.types.ResolvedTypeReference.container(dvw(t)),named:ve.V44.types.ResolvedTypeReference.named,primitive:t=>t.v1==="BIG_INTEGER"?ve.V44.types.ResolvedTypeReference.primitive(ve.V44.types.PrimitiveType.String):ve.V44.types.ResolvedTypeReference.primitive(t.v1),unknown:ve.V44.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown ResolvedTypeReference: "+e.type)}})}function MA4(e){return{members:e.members.map(t=>({...t,type:YC(t.type)}))}}function AA4(e){return{...e,pathParameters:e.pathParameters.map(t=>LOo(t)),headers:e.headers.map(t=>gwa(t)),endpoints:e.endpoints.map(t=>TA4(t))}}function LOo(e){return{...e,valueType:YC(e.valueType)}}function qA4(e){return{...e,type:YC(e.type)}}function TA4(e){return{...e,pagination:e.pagination!=null?xA4(e.pagination):void 0,allPathParameters:e.allPathParameters.map(t=>LOo(t)),pathParameters:e.pathParameters.map(t=>LOo(t)),sdkRequest:e.sdkRequest!=null?LA4(e.sdkRequest):void 0,requestBody:e.requestBody!=null?WA4(e.requestBody):void 0,response:e.response!=null?CA4(e.response):void 0,headers:e.headers.map(t=>gwa(t)),queryParameters:e.queryParameters.map(t=>UOo(t))}}function CA4(e){return{...e,body:e.body!=null?BA4(e.body):void 0}}function BA4(e){switch(e.type){case"json":return ve.V44.http.HttpResponseBody.json(IA4(e.value));case"fileDownload":return ve.V44.http.HttpResponseBody.fileDownload(e);case"text":return ve.V44.http.HttpResponseBody.text(e);case"streaming":return ve.V44.http.HttpResponseBody.streaming(zA4(e.value))}}function IA4(e){switch(e.type){case"response":return ve.V44.http.JsonResponse.response({...e,responseBodyType:YC(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V44.http.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:YC(e.responseBodyType),responseProperty:e.responseProperty!=null?sOd(e.responseProperty):void 0})}}function zA4(e){switch(e.type){case"json":return ve.V44.http.StreamingResponse.json({...e,payload:YC(e.payload)});case"text":return ve.V44.http.StreamingResponse.text(e);case"sse":return ve.V44.http.StreamingResponse.sse({...e,payload:YC(e.payload)})}}function xA4(e){switch(e.type){case"cursor":return ve.V44.http.Pagination.cursor(RA4(e));case"offset":return ve.V44.http.Pagination.offset(NA4(e))}}function RA4(e){return{...e,page:UOo(e.page),next:bAi(e.next),results:bAi(e.results)}}function NA4(e){return{...e,page:UOo(e.page),results:bAi(e.results)}}function $Ns(e){return{...e,property:FA4(e.property)}}function FA4(e){switch(e.type){case"query":return ve.V44.RequestPropertyValue.query(UOo(e));case"body":return ve.V44.RequestPropertyValue.body(sOd(e))}}function bAi(e){return{...e,property:sOd(e.property)}}function sOd(e){return{...e,valueType:YC(e.valueType)}}function UOo(e){return{...e,valueType:YC(e.valueType)}}function LA4(e){return{...e,shape:UA4(e.shape)}}function UA4(e){return ve.V45.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V44.http.SdkRequestShape.justRequestBody(VA4(t)),wrapper:ve.V44.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function VA4(e){switch(e.type){case"bytes":return ve.V44.http.SdkRequestBodyType.bytes(e);case"typeReference":return ve.V44.http.SdkRequestBodyType.typeReference({...e,requestBodyType:YC(e.requestBodyType)})}}function WA4(e){return ve.V45.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V44.http.HttpRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,valueType:YC(r.valueType)}))}),reference:t=>ve.V44.http.HttpRequestBody.reference({...t,requestBodyType:YC(t.requestBodyType)}),fileUpload:t=>ve.V44.http.HttpRequestBody.fileUpload({...t,properties:t.properties.map(r=>{switch(r.type){case"bodyProperty":return ve.V44.http.FileUploadRequestProperty.bodyProperty({...r,valueType:YC(r.valueType)});case"file":return ve.V44.http.FileUploadRequestProperty.file(HA4(r.value))}})}),bytes:t=>ve.V44.http.HttpRequestBody.bytes(t),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function HA4(e){switch(e.type){case"file":return ve.V44.http.FileProperty.file(e);case"fileArray":return ve.V44.http.FileProperty.fileArray(e)}}function $A4(e){return{...e,type:e.type!=null?YC(e.type):void 0}}var _vw={laterVersion:"v46",earlierVersion:"v45",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.21.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.21.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.21.0",[$.TYPESCRIPT_EXPRESS]:"0.16.0",[$.JAVA]:Ne,[$.JAVA_MODEL]:"0.9.0",[$.JAVA_SDK]:"0.10.0",[$.JAVA_SPRING]:"0.9.0",[$.PYTHON_FASTAPI]:"0.10.1",[$.PYTHON_PYDANTIC]:"0.9.1",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"2.9.9",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V45.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,{...r,examples:GA4(r.examples)}])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>({...i,examples:QA4(i.examples)}))}])),websocketChannels:e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).map(([t,r])=>[t,{...r,examples:JA4(r.examples)}])):void 0,errors:Object.fromEntries(Object.entries(e.errors).map(([t,r])=>[t,{...r,examples:r.examples.map(i=>({...i,shape:a4(i.shape)}))}]))})};function a4(e){return e.shape._visit({container:t=>({...e,shape:t._visit({list:r=>ve.V45.ExampleTypeReferenceShape.container(ve.V45.ExampleContainer.list(r.map(i=>a4(i)))),set:r=>ve.V45.ExampleTypeReferenceShape.container(ve.V45.ExampleContainer.set(r.map(i=>a4(i)))),map:r=>ve.V45.ExampleTypeReferenceShape.container(ve.V45.ExampleContainer.map(r.map(i=>({key:a4(i.key),value:a4(i.value)})))),optional:r=>ve.V45.ExampleTypeReferenceShape.container(ve.V45.ExampleContainer.optional(r!=null?a4(r):void 0)),literal:r=>ve.V45.ExampleTypeReferenceShape.primitive(r._visit({string:i=>ve.V45.ExamplePrimitive.string(i),integer:i=>ve.V45.ExamplePrimitive.integer(i),double:i=>ve.V45.ExamplePrimitive.double(i),long:i=>ve.V45.ExamplePrimitive.long(i),boolean:i=>ve.V45.ExamplePrimitive.boolean(i),datetime:i=>ve.V45.ExamplePrimitive.datetime(i),date:i=>ve.V45.ExamplePrimitive.date(i),uuid:i=>ve.V45.ExamplePrimitive.uuid(i),_other:i=>{throw new Error(`Unexpected value: ${JSON.stringify(i)}`)}})),_other:r=>{throw new Error(`Unexpected value: ${JSON.stringify(r)}`)}})}),named:t=>({...e,shape:ve.V45.ExampleTypeReferenceShape.named({...t,shape:hvw(t.shape)})}),primitive:t=>({...e,shape:ve.V45.ExampleTypeReferenceShape.primitive(t._visit({string:r=>ve.V45.ExamplePrimitive.string(r),integer:r=>ve.V45.ExamplePrimitive.integer(r),double:r=>ve.V45.ExamplePrimitive.double(r),long:r=>ve.V45.ExamplePrimitive.long(r),boolean:r=>ve.V45.ExamplePrimitive.boolean(r),datetime:r=>ve.V45.ExamplePrimitive.datetime(r),date:r=>ve.V45.ExamplePrimitive.date(r),uuid:r=>ve.V45.ExamplePrimitive.uuid(r),_other:r=>{throw new Error(`Unexpected value: ${JSON.stringify(r)}`)}}))}),unknown:t=>({...e,shape:ve.V45.ExampleTypeReferenceShape.unknown(t)}),_other:t=>{throw new Error(`Unexpected value: ${JSON.stringify(t)}`)}})}function pvw(e){return{...e,properties:e.properties.map(t=>({...t,value:a4(t.value)}))}}function hvw(e){return e.type==="alias"?ve.V45.ExampleTypeShape.alias({value:a4(e.value)}):e.type==="object"?ve.V45.ExampleTypeShape.object(pvw(e)):e.type==="union"?ve.V45.ExampleTypeShape.union({...e,singleUnionType:{...e.singleUnionType,shape:e.singleUnionType.shape._visit({samePropertiesAsObject:t=>ve.V45.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...t,object:pvw(t.object)}),singleProperty:t=>ve.V45.ExampleSingleUnionTypeProperties.singleProperty(a4(t)),noProperties:()=>ve.V45.ExampleSingleUnionTypeProperties.noProperties(),_other:t=>{throw new Error(`Unexpected value: ${JSON.stringify(t)}`)}})}}):e.type==="undiscriminatedUnion"?ve.V45.ExampleTypeShape.undiscriminatedUnion({...e,singleUnionType:a4(e.singleUnionType)}):ve.V45.ExampleTypeShape.enum(e)}function GA4(e){return e.map(t=>({...t,shape:hvw(t.shape)}))}function GNs(e){return e.map(t=>({...t,value:a4(t.value)}))}function cOd(e){return e.map(t=>({...t,value:a4(t.value)}))}function yvw(e){return e.map(t=>({...t,value:a4(t.value)}))}function QA4(e){return e.map(t=>{let r={...t,rootPathParameters:GNs(t.rootPathParameters),servicePathParameters:GNs(t.servicePathParameters),endpointPathParameters:GNs(t.endpointPathParameters),serviceHeaders:cOd(t.serviceHeaders),endpointHeaders:cOd(t.endpointHeaders),queryParameters:yvw(t.queryParameters),request:t.request?._visit({inlinedRequestBody:i=>ve.V45.ExampleRequestBody.inlinedRequestBody({...i,properties:i.properties.map(n=>({...n,value:a4(n.value)}))}),reference:i=>ve.V45.ExampleRequestBody.reference(a4(i)),_other:i=>{throw new Error(`Unexpected value: ${JSON.stringify(i)}`)}}),response:t.response._visit({ok:i=>ve.V45.ExampleResponse.ok(i._visit({body:n=>ve.V45.ExampleEndpointSuccessResponse.body(n!=null?a4(n):void 0),stream:n=>ve.V45.ExampleEndpointSuccessResponse.stream(n.map(a4)),sse:n=>ve.V45.ExampleEndpointSuccessResponse.sse(n.map(a=>({...a,data:a4(a.data)}))),_other:n=>{throw new Error(`Unexpected value: ${JSON.stringify(n)}`)}})),error:i=>ve.V45.ExampleResponse.error({...i,body:i.body!=null?a4(i.body):void 0}),_other:i=>{throw new Error(`Unexpected value: ${JSON.stringify(i)}`)}})};return t._visit({userProvided:()=>ve.V45.HttpEndpointExample.userProvided(r),generated:()=>ve.V45.HttpEndpointExample.generated(r),_other:i=>{throw new Error(`Unexpected value: ${JSON.stringify(i)}`)}})})}function JA4(e){return e.map(t=>({...t,pathParameters:GNs(t.pathParameters),headers:cOd(t.headers),queryParameters:yvw(t.queryParameters),messages:t.messages.map(r=>({...r,body:r.body._visit({inlinedBody:i=>ve.V45.ExampleWebSocketMessageBody.inlinedBody({...i,properties:i.properties.map(n=>({...n,value:a4(n.value)}))}),reference:i=>ve.V45.ExampleWebSocketMessageBody.reference(a4(i)),_other:i=>{throw new Error(`Unexpected value: ${JSON.stringify(i)}`)}})}))}))}var vvw={laterVersion:"v47",earlierVersion:"v46",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V46.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>{let i=r.endpoints.map(n=>{let{autogeneratedExamples:a,userSpecifiedExamples:u,...c}=n;return{...c,autogeneratedExamples:void 0,userSpecifiedExamples:void 0,examples:[...n.userSpecifiedExamples.map(s=>{if(s.example!=null)return ve.V46.HttpEndpointExample.userProvided({...s.example,codeSamples:s.codeSamples})}).filter(yy),...n.autogeneratedExamples.map(s=>ve.V46.HttpEndpointExample.generated({...s.example,codeSamples:void 0}))]}});return[t,{...r,endpoints:i}]}))})};var bvw={laterVersion:"v48",earlierVersion:"v47",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.29.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.29.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.29.0",[$.TYPESCRIPT_EXPRESS]:"0.17.0",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V47.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=Object.fromEntries(Object.entries(e.services).map(([r,i])=>{let n=i.endpoints.map(a=>({...a,pagination:a.pagination!=null?YA4(a.pagination):void 0}));return[r,{...i,endpoints:n}]}));return{...e,sdkConfig:{...e.sdkConfig,hasPaginatedEndpoints:KA4(t)},services:t}}};function KA4(e){for(let t of Object.values(e))for(let r of t.endpoints)if(r.pagination!=null)return!0;return!1}function YA4(e){switch(e.type){case"cursor":{let t=XA4(e);return t!=null?ve.V47.Pagination.cursor(t):void 0}case"offset":{let t=ZA4(e);return t!=null?ve.V47.Pagination.offset(t):void 0}default:Ao(e)}}function XA4(e){let t=gvw(e.page);if(t!=null)return{...e,page:t}}function ZA4(e){if(e.step!=null)return;let t=gvw(e.page);if(t!=null)return{...e,page:t}}function gvw(e){switch(e.property.type){case"query":return e.property}}var Ovw={laterVersion:"v49",earlierVersion:"v48",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:"0.11.0-rc0",[$.PYTHON_PYDANTIC]:"0.10.0-rc0",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:"2.11.0-rc0",[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:ar,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V48.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=Object.fromEntries(Object.entries(e.services).map(([r,i])=>{let n=i.endpoints.flatMap(a=>{let u;return a.response?.body!=null&&(u=a.response.body?._visit({json:d=>ve.V48.HttpResponseBody.json({...d}),fileDownload:d=>ve.V48.HttpResponseBody.fileDownload({...d}),text:d=>ve.V48.HttpResponseBody.text({...d}),streaming:d=>ve.V48.HttpResponseBody.streaming({...d}),streamParameter:()=>{},_other:()=>{}}),u==null)?[]:{...a,response:a.response==null?void 0:{statusCode:a.response?.statusCode,body:u}}});return[r,{...i,endpoints:n}]}));return{...e,services:t}}};var mvw={laterVersion:"v50",earlierVersion:"v49",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.34.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.34.0",[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:"0.34.0",[$.TYPESCRIPT_EXPRESS]:"0.17.2",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:"0.0.0",[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V49.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=Sd(e.types,r=>({...r,shape:ve.V50.types.Type._visit(r.shape,{union:i=>ve.V49.types.Type.union({...i,baseProperties:i.baseProperties.map(n=>({...n,valueType:XC(n.valueType)})),types:i.types.map(n=>lq4(n))}),enum:ve.V49.types.Type.enum,object:i=>ve.V49.types.Type.object({...i,properties:i.properties.map(n=>({...n,valueType:XC(n.valueType)}))}),alias:i=>ve.V49.types.Type.alias({aliasOf:XC(i.aliasOf),resolvedType:dq4(i.resolvedType)}),undiscriminatedUnion:i=>ve.V49.types.Type.undiscriminatedUnion(pq4(i)),_other:()=>{throw new Error("Encountered unknown shape")}})}));return{...e,auth:aq4(e.auth),headers:e.headers.map(r=>Owa(r)),idempotencyHeaders:e.idempotencyHeaders.map(r=>Owa(r)),types:t,services:Sd(e.services,r=>_q4(r)),errors:Sd(e.errors,r=>qq4(r)),webhookGroups:Sd(e.webhookGroups,r=>rq4(r)),websocketChannels:Sd(e.websocketChannels,r=>kA4(r)),pathParameters:e.pathParameters.map(r=>VOo(r)),variables:e.variables.map(r=>hq4(r))}}};function kA4(e){return{...e,headers:e.headers.map(t=>Owa(t)),queryParameters:e.queryParameters.map(t=>fOd(t)),pathParameters:e.pathParameters.map(t=>VOo(t)),messages:e.messages.map(t=>eq4(t))}}function eq4(e){return{...e,body:tq4(e.body)}}function tq4(e){switch(e.type){case"inlinedBody":return ve.V49.websocket.WebSocketMessageBody.inlinedBody({...e,properties:e.properties.map(t=>({...t,valueType:XC(t.valueType)}))});case"reference":return ve.V49.websocket.WebSocketMessageBody.reference({...e,bodyType:XC(e.bodyType)})}}function rq4(e){return e.map(t=>iq4(t))}function iq4(e){return{...e,headers:e.headers.map(t=>Owa(t)),payload:nq4(e.payload)}}function nq4(e){switch(e.type){case"reference":return ve.V49.webhooks.WebhookPayload.reference({...e,payloadType:XC(e.payloadType)});case"inlinedPayload":return ve.V49.webhooks.WebhookPayload.inlinedPayload({...e,properties:e.properties.map(t=>({...t,valueType:XC(t.valueType)}))})}}function aq4(e){return{...e,schemes:e.schemes.map(t=>{switch(t.type){case"basic":return ve.V49.auth.AuthScheme.basic(t);case"bearer":return ve.V49.auth.AuthScheme.bearer(t);case"header":return ve.V49.auth.AuthScheme.header(oq4(t));case"oauth":return ve.V49.auth.AuthScheme.oauth(uq4(t))}})}}function oq4(e){return{...e,valueType:XC(e.valueType)}}function uq4(e){return{...e,configuration:ve.V49.auth.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:sq4(e.configuration.tokenEndpoint),refreshEndpoint:e.configuration.refreshEndpoint!=null?cq4(e.configuration.refreshEndpoint):void 0})}}function sq4(e){return{...e,requestProperties:{clientId:rGi(e.requestProperties.clientId),clientSecret:rGi(e.requestProperties.clientSecret),scopes:e.requestProperties.scopes!=null?rGi(e.requestProperties.scopes):void 0},responseProperties:{accessToken:gAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?gAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?gAi(e.responseProperties.refreshToken):void 0}}}function cq4(e){return{...e,requestProperties:{refreshToken:rGi(e.requestProperties.refreshToken)},responseProperties:{accessToken:gAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?gAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?gAi(e.responseProperties.refreshToken):void 0}}}function Owa(e){return{...e,valueType:XC(e.valueType)}}function XC(e){return ve.V50.types.TypeReference._visit(e,{container:t=>ve.V49.types.TypeReference.container(Pvw(t)),primitive:t=>t.v2?.type==="integer"?ve.V49.types.TypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.integer(t.v2)}):t.v2?.type==="double"?ve.V49.types.TypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.double(t.v2)}):t.v2?.type==="string"?ve.V49.types.TypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.string(t.v2)}):ve.V49.types.TypeReference.primitive({v1:t.v1,v2:void 0}),named:ve.V49.types.TypeReference.named,unknown:ve.V49.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function Pvw(e){return ve.V50.types.ContainerType._visit(e,{list:t=>ve.V49.types.ContainerType.list(XC(t)),optional:t=>ve.V49.types.ContainerType.optional(XC(t)),set:t=>ve.V49.types.ContainerType.set(XC(t)),map:({keyType:t,valueType:r})=>ve.V49.types.ContainerType.map({keyType:XC(t),valueType:XC(r)}),literal:ve.V49.types.ContainerType.literal,_other:()=>{throw new Error("Unknown ContainerType: "+e.type)}})}function lq4(e){return{...e,shape:fq4(e.shape)}}function fq4(e){return ve.V50.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V49.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V49.types.SingleUnionTypeProperties.singleProperty({...t,type:XC(t.type)}),noProperties:ve.V49.types.SingleUnionTypeProperties.noProperties,_other:()=>{throw new Error(`Unknown SingleUnionTypeProperties: ${JSON.stringify(e)}`)}})}function dq4(e){return ve.V50.types.ResolvedTypeReference._visit(e,{container:t=>ve.V49.types.ResolvedTypeReference.container(Pvw(t)),named:ve.V49.types.ResolvedTypeReference.named,primitive:t=>t.v2?.type==="integer"?ve.V49.types.ResolvedTypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.integer(t.v2)}):t.v2?.type==="double"?ve.V49.types.ResolvedTypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.double(t.v2)}):t.v2?.type==="string"?ve.V49.types.ResolvedTypeReference.primitive({v1:t.v1,v2:ve.V49.types.PrimitiveTypeV2.string(t.v2)}):ve.V49.types.ResolvedTypeReference.primitive({v1:t.v1,v2:void 0}),unknown:ve.V49.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown ResolvedTypeReference: "+e.type)}})}function pq4(e){return{members:e.members.map(t=>({...t,type:XC(t.type)}))}}function _q4(e){return{...e,pathParameters:e.pathParameters.map(t=>VOo(t)),headers:e.headers.map(t=>Owa(t)),endpoints:e.endpoints.map(t=>yq4(t))}}function VOo(e){return{...e,valueType:XC(e.valueType)}}function hq4(e){return{...e,type:XC(e.type)}}function yq4(e){return{...e,pagination:e.pagination!=null?mq4(e.pagination):void 0,allPathParameters:e.allPathParameters.map(t=>VOo(t)),pathParameters:e.pathParameters.map(t=>VOo(t)),sdkRequest:e.sdkRequest!=null?Sq4(e.sdkRequest):void 0,requestBody:e.requestBody!=null?Mq4(e.requestBody):void 0,response:e.response!=null?vq4(e.response):void 0,headers:e.headers.map(t=>Owa(t)),queryParameters:e.queryParameters.map(t=>fOd(t))}}function vq4(e){return{...e,body:e.body!=null?bq4(e.body):void 0}}function bq4(e){switch(e.type){case"json":return ve.V49.http.HttpResponseBody.json(jvw(e.value));case"fileDownload":return ve.V49.http.HttpResponseBody.fileDownload(e);case"text":return ve.V49.http.HttpResponseBody.text(e);case"streaming":return ve.V49.http.HttpResponseBody.streaming(wvw(e.value));case"streamParameter":return ve.V49.http.HttpResponseBody.streamParameter(Oq4(e))}}function jvw(e){switch(e.type){case"response":return ve.V49.http.JsonResponse.response({...e,responseBodyType:XC(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V49.http.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:XC(e.responseBodyType),responseProperty:e.responseProperty!=null?lOd(e.responseProperty):void 0})}}function wvw(e){switch(e.type){case"json":return ve.V49.http.StreamingResponse.json({...e,payload:XC(e.payload)});case"text":return ve.V49.http.StreamingResponse.text(e);case"sse":return ve.V49.http.StreamingResponse.sse({...e,payload:XC(e.payload)})}}function gq4(e){switch(e.type){case"json":return ve.V49.http.NonStreamHttpResponseBody.json(jvw(e.value));case"text":return ve.V49.http.NonStreamHttpResponseBody.text(e);case"fileDownload":return ve.V49.http.NonStreamHttpResponseBody.fileDownload(e)}}function Oq4(e){return{nonStreamResponse:gq4(e.nonStreamResponse),streamResponse:wvw(e.streamResponse)}}function mq4(e){switch(e.type){case"cursor":return ve.V49.http.Pagination.cursor(Pq4(e));case"offset":return ve.V49.http.Pagination.offset(jq4(e))}}function Pq4(e){return{...e,page:rGi(e.page),next:gAi(e.next),results:gAi(e.results)}}function jq4(e){return{...e,page:rGi(e.page),results:gAi(e.results),step:e.step!=null?rGi(e.step):void 0}}function rGi(e){return{...e,property:wq4(e.property)}}function wq4(e){switch(e.type){case"query":return ve.V49.RequestPropertyValue.query(fOd(e));case"body":return ve.V49.RequestPropertyValue.body(lOd(e))}}function gAi(e){return{...e,property:lOd(e.property)}}function lOd(e){return{...e,valueType:XC(e.valueType)}}function fOd(e){return{...e,valueType:XC(e.valueType)}}function Sq4(e){return{...e,streamParameter:e.streamParameter!=null?rGi(e.streamParameter):void 0,shape:Dq4(e.shape)}}function Dq4(e){return ve.V50.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V49.http.SdkRequestShape.justRequestBody(Eq4(t)),wrapper:ve.V49.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function Eq4(e){switch(e.type){case"bytes":return ve.V49.http.SdkRequestBodyType.bytes(e);case"typeReference":return ve.V49.http.SdkRequestBodyType.typeReference({...e,requestBodyType:XC(e.requestBodyType)})}}function Mq4(e){return ve.V50.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V49.http.HttpRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,valueType:XC(r.valueType)}))}),reference:t=>ve.V49.http.HttpRequestBody.reference({...t,requestBodyType:XC(t.requestBodyType)}),fileUpload:t=>ve.V49.http.HttpRequestBody.fileUpload({...t,properties:t.properties.map(r=>{switch(r.type){case"bodyProperty":return ve.V49.http.FileUploadRequestProperty.bodyProperty({...r,valueType:XC(r.valueType)});case"file":return ve.V49.http.FileUploadRequestProperty.file(Aq4(r.value))}})}),bytes:t=>ve.V49.http.HttpRequestBody.bytes(t),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function Aq4(e){switch(e.type){case"file":return ve.V49.http.FileProperty.file(e);case"fileArray":return ve.V49.http.FileProperty.fileArray(e)}}function qq4(e){return{...e,type:e.type!=null?XC(e.type):void 0}}var Evw={laterVersion:"v51",earlierVersion:"v50",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:"0.1.2",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V50.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>{let t=Sd(e.types,r=>{let i=r.autogeneratedExamples.map(a=>Svw(a)),n=r.userProvidedExamples.map(a=>Svw(a));return{...r,examples:[...i,...n]}});return{...e,types:t,services:Sd(e.services,r=>Uq4(r)),errors:Sd(e.errors,r=>Gq4(r)),webhookGroups:Sd(e.webhookGroups,r=>Iq4(r)),websocketChannels:Sd(e.websocketChannels,r=>Tq4(r))}}};function Tq4(e){return{...e,examples:e.examples.map(t=>Cq4(t))}}function Cq4(e){return{...e,pathParameters:e.pathParameters.map(t=>QNs(t)),headers:e.headers.map(t=>dOd(t)),queryParameters:e.queryParameters.map(t=>Mvw(t)),messages:e.messages.map(t=>({...t,body:Bq4(t.body)}))}}function Mvw(e){return{...e,value:J9(e.value)}}function dOd(e){return{...e,value:J9(e.value)}}function QNs(e){return{...e,value:J9(e.value)}}function Bq4(e){switch(e.type){case"inlinedBody":return ve.V50.ExampleWebSocketMessageBody.inlinedBody(Avw(e));case"reference":return ve.V50.ExampleWebSocketMessageBody.reference(J9(e))}}function Avw(e){return{...e,properties:e.properties.map(t=>({...t,value:J9(t.value)}))}}function Iq4(e){return e.map(t=>({...t,examples:t.examples?.map(r=>({...r,payload:J9(r.payload)}))}))}function Svw(e){return{...e,shape:qvw(e.shape)}}function pOd(e){switch(e.type){case"primitive":return ve.V50.ExampleTypeReferenceShape.primitive({...e.primitive});case"container":return ve.V50.ExampleTypeReferenceShape.container(zq4(e));case"unknown":return ve.V50.ExampleTypeReferenceShape.unknown(e.unknown);case"named":return ve.V50.ExampleTypeReferenceShape.named({...e,typeName:e.typeName,shape:qvw(e.shape)})}}function zq4(e){switch(e.container.type){case"list":return ve.V50.ExampleContainer.list(e.container.list.map(t=>J9(t)));case"set":return ve.V50.ExampleContainer.set(e.container.set.map(t=>J9(t)));case"optional":return ve.V50.ExampleContainer.optional(e.container.optional!=null?J9(e.container.optional):void 0);case"map":return ve.V50.ExampleContainer.map(e.container.map.map(t=>({key:J9(t.key),value:J9(t.value)})));case"literal":return ve.V50.ExampleContainer.literal(e.container.literal)}}function J9(e){return{...e,shape:pOd(e.shape)}}function qvw(e){switch(e.type){case"object":return ve.V50.ExampleTypeShape.object({properties:e.properties.map(t=>Tvw(t))});case"alias":return ve.V50.ExampleTypeShape.alias({value:{...J9(e.value)}});case"enum":return ve.V50.ExampleTypeShape.enum(e);case"union":return ve.V50.ExampleTypeShape.union(Rq4(e));case"undiscriminatedUnion":return ve.V50.ExampleTypeShape.undiscriminatedUnion(xq4(e))}}function xq4(e){return{...e,singleUnionType:J9(e.singleUnionType)}}function Rq4(e){return{...e,singleUnionType:Nq4(e.singleUnionType)}}function Nq4(e){return{...e,shape:Fq4(e.shape)}}function Fq4(e){switch(e.type){case"samePropertiesAsObject":return ve.V50.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...e,object:Lq4(e.object)});case"singleProperty":return ve.V50.ExampleSingleUnionTypeProperties.singleProperty({...e,shape:pOd(e.shape)});case"noProperties":return ve.V50.ExampleSingleUnionTypeProperties.noProperties()}}function Lq4(e){return{...e,properties:e.properties.map(t=>Tvw(t))}}function Tvw(e){return{...e,value:{...e.value,shape:pOd(e.value.shape)}}}function Uq4(e){return{...e,endpoints:e.endpoints.map(t=>Vq4(t))}}function Vq4(e){return{...e,autogeneratedExamples:e.autogeneratedExamples.map(t=>({...t,example:Dvw(t.example)})),userSpecifiedExamples:e.userSpecifiedExamples.map(t=>({...t,example:t.example!=null?Dvw(t.example):void 0}))}}function Dvw(e){return{...e,rootPathParameters:e.rootPathParameters.map(t=>QNs(t)),servicePathParameters:e.servicePathParameters.map(t=>QNs(t)),endpointPathParameters:e.endpointPathParameters.map(t=>QNs(t)),serviceHeaders:e.serviceHeaders.map(t=>dOd(t)),endpointHeaders:e.endpointHeaders.map(t=>dOd(t)),queryParameters:e.queryParameters.map(t=>Mvw(t)),request:e.request!=null?$q4(e.request):void 0,response:Wq4(e.response)}}function Wq4(e){switch(e.type){case"error":return ve.V50.ExampleResponse.error({...e,body:e.body!=null?J9(e.body):void 0});case"ok":return ve.V50.ExampleResponse.ok(Hq4(e))}}function Hq4(e){switch(e.value.type){case"body":return ve.V50.ExampleEndpointSuccessResponse.body(e.value.value!=null?J9(e.value.value):void 0);case"stream":return ve.V50.ExampleEndpointSuccessResponse.stream(e.value.value.map(t=>J9(t)));case"sse":return ve.V50.ExampleEndpointSuccessResponse.sse(e.value.value.map(t=>({...t,data:J9(t.data)})))}}function $q4(e){switch(e.type){case"inlinedRequestBody":return ve.V50.ExampleRequestBody.inlinedRequestBody(Avw(e));case"reference":return ve.V50.ExampleRequestBody.reference(J9(e))}}function Gq4(e){return{...e,examples:e.examples.map(t=>({...t,shape:J9(t.shape)}))}}var Ivw={laterVersion:"v52",earlierVersion:"v51",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:ar,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V51.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,apiVersion:e.apiVersion!=null?Jq4(e.apiVersion):void 0,auth:rT4(e.auth),headers:e.headers.map(t=>QIn(t)),idempotencyHeaders:e.idempotencyHeaders.map(t=>QIn(t)),types:Qq4(e.types),services:Sd(e.services,t=>pT4(t)),webhookGroups:Sd(e.webhookGroups,t=>Zq4(t)),websocketChannels:Sd(e.websocketChannels,t=>Kq4(t)),errors:Sd(e.errors,t=>AT4(t)),pathParameters:e.pathParameters.map(t=>WOo(t)),variables:e.variables.map(t=>_T4(t))})};function Qq4(e){return Sd(e,t=>({...t,autogeneratedExamples:t.autogeneratedExamples.map(r=>Cvw(r)),userProvidedExamples:t.userProvidedExamples.map(r=>Cvw(r)),shape:ve.V52.types.Type._visit(t.shape,{union:r=>ve.V51.types.Type.union({...r,baseProperties:r.baseProperties.map(i=>({...i,valueType:ZM(i.valueType)})),types:r.types.map(i=>cT4(i))}),enum:ve.V51.types.Type.enum,object:r=>ve.V51.types.Type.object({...r,properties:r.properties.map(i=>({...i,valueType:ZM(i.valueType)}))}),alias:r=>ve.V51.types.Type.alias({aliasOf:ZM(r.aliasOf),resolvedType:fT4(r.resolvedType)}),undiscriminatedUnion:r=>ve.V51.types.Type.undiscriminatedUnion(dT4(r)),_other:()=>{throw new Error("Encountered unknown shape")}})}))}function Jq4(e){return ve.V51.ApiVersionScheme.header({...e,header:QIn(e.header)})}function Kq4(e){return{...e,headers:e.headers.map(t=>QIn(t)),queryParameters:e.queryParameters.map(t=>yOd(t)),pathParameters:e.pathParameters.map(t=>WOo(t)),messages:e.messages.map(t=>Yq4(t)),examples:e.examples.map(t=>qT4(t))}}function Yq4(e){return{...e,body:Xq4(e.body)}}function Xq4(e){switch(e.type){case"inlinedBody":return ve.V51.websocket.WebSocketMessageBody.inlinedBody({...e,properties:e.properties.map(t=>({...t,valueType:ZM(t.valueType)}))});case"reference":return ve.V51.websocket.WebSocketMessageBody.reference({...e,bodyType:ZM(e.bodyType)})}}function Zq4(e){return e.map(t=>kq4(t))}function kq4(e){return{...e,headers:e.headers.map(t=>QIn(t)),payload:eT4(e.payload),examples:e.examples!=null?e.examples.map(t=>tT4(t)):void 0}}function eT4(e){switch(e.type){case"reference":return ve.V51.webhooks.WebhookPayload.reference({...e,payloadType:ZM(e.payloadType)});case"inlinedPayload":return ve.V51.webhooks.WebhookPayload.inlinedPayload({...e,properties:e.properties.map(t=>({...t,valueType:ZM(t.valueType)}))})}}function tT4(e){return{...e,payload:K9(e.payload)}}function rT4(e){return{...e,schemes:e.schemes.map(t=>{switch(t.type){case"basic":return ve.V51.auth.AuthScheme.basic(t);case"bearer":return ve.V51.auth.AuthScheme.bearer(t);case"header":return ve.V51.auth.AuthScheme.header(iT4(t));case"oauth":return ve.V51.auth.AuthScheme.oauth(nT4(t))}})}}function iT4(e){return{...e,valueType:ZM(e.valueType)}}function nT4(e){return{...e,configuration:ve.V51.auth.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:aT4(e.configuration.tokenEndpoint),refreshEndpoint:e.configuration.refreshEndpoint!=null?oT4(e.configuration.refreshEndpoint):void 0})}}function aT4(e){return{...e,requestProperties:{clientId:iGi(e.requestProperties.clientId),clientSecret:iGi(e.requestProperties.clientSecret),scopes:e.requestProperties.scopes!=null?iGi(e.requestProperties.scopes):void 0},responseProperties:{accessToken:OAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?OAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?OAi(e.responseProperties.refreshToken):void 0}}}function oT4(e){return{...e,requestProperties:{refreshToken:iGi(e.requestProperties.refreshToken)},responseProperties:{accessToken:OAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?OAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?OAi(e.responseProperties.refreshToken):void 0}}}function QIn(e){return{...e,valueType:ZM(e.valueType)}}function ZM(e){return ve.V52.types.TypeReference._visit(e,{container:t=>ve.V51.types.TypeReference.container(xvw(t)),primitive:t=>ve.V51.types.TypeReference.primitive(zvw(t)),named:ve.V51.types.TypeReference.named,unknown:ve.V51.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function zvw(e){return{v1:uT4(e.v1),v2:e.v2!=null?sT4(e.v2):void 0}}function uT4(e){switch(e){case"UINT":return ve.V51.types.PrimitiveTypeV1.Integer;case"UINT_64":return ve.V51.types.PrimitiveTypeV1.Long}return e}function sT4(e){switch(e.type){case"integer":return ve.V51.types.PrimitiveTypeV2.integer(e);case"double":return ve.V51.types.PrimitiveTypeV2.double(e);case"string":return ve.V51.types.PrimitiveTypeV2.string(e);case"boolean":return ve.V51.types.PrimitiveTypeV2.boolean(e);case"long":return ve.V51.types.PrimitiveTypeV2.long(e);case"bigInteger":return ve.V51.types.PrimitiveTypeV2.bigInteger(e);case"uint":return;case"uint64":return;default:Ao(e)}}function xvw(e){return ve.V52.types.ContainerType._visit(e,{list:t=>ve.V51.types.ContainerType.list(ZM(t)),optional:t=>ve.V51.types.ContainerType.optional(ZM(t)),set:t=>ve.V51.types.ContainerType.set(ZM(t)),map:({keyType:t,valueType:r})=>ve.V51.types.ContainerType.map({keyType:ZM(t),valueType:ZM(r)}),literal:ve.V51.types.ContainerType.literal,_other:()=>{throw new Error("Unknown ContainerType: "+e.type)}})}function cT4(e){return{...e,shape:lT4(e.shape)}}function lT4(e){return ve.V52.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V51.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V51.types.SingleUnionTypeProperties.singleProperty({...t,type:ZM(t.type)}),noProperties:ve.V51.types.SingleUnionTypeProperties.noProperties,_other:()=>{throw new Error(`Unknown SingleUnionTypeProperties: ${JSON.stringify(e)}`)}})}function fT4(e){return ve.V52.types.ResolvedTypeReference._visit(e,{container:t=>ve.V51.types.ResolvedTypeReference.container(xvw(t)),named:ve.V51.types.ResolvedTypeReference.named,primitive:t=>ve.V51.types.ResolvedTypeReference.primitive(zvw(t)),unknown:ve.V51.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown ResolvedTypeReference: "+e.type)}})}function dT4(e){return{members:e.members.map(t=>({...t,type:ZM(t.type)}))}}function pT4(e){return{...e,pathParameters:e.pathParameters.map(t=>WOo(t)),headers:e.headers.map(t=>QIn(t)),endpoints:e.endpoints.map(t=>hT4(t))}}function WOo(e){return{...e,valueType:ZM(e.valueType)}}function _T4(e){return{...e,type:ZM(e.type)}}function hT4(e){return{...e,pagination:e.pagination!=null?OT4(e.pagination):void 0,allPathParameters:e.allPathParameters.map(t=>WOo(t)),pathParameters:e.pathParameters.map(t=>WOo(t)),sdkRequest:e.sdkRequest!=null?wT4(e.sdkRequest):void 0,requestBody:e.requestBody!=null?ET4(e.requestBody):void 0,response:e.response!=null?yT4(e.response):void 0,headers:e.headers.map(t=>QIn(t)),queryParameters:e.queryParameters.map(t=>yOd(t)),autogeneratedExamples:e.autogeneratedExamples.map(t=>({...t,example:Bvw(t.example)})),userSpecifiedExamples:e.userSpecifiedExamples.map(t=>({...t,example:t.example!=null?Bvw(t.example):void 0}))}}function yT4(e){return{...e,body:e.body!=null?vT4(e.body):void 0}}function vT4(e){switch(e.type){case"json":return ve.V51.http.HttpResponseBody.json(Rvw(e.value));case"fileDownload":return ve.V51.http.HttpResponseBody.fileDownload(e);case"text":return ve.V51.http.HttpResponseBody.text(e);case"streaming":return ve.V51.http.HttpResponseBody.streaming(Nvw(e.value));case"streamParameter":return ve.V51.http.HttpResponseBody.streamParameter(gT4(e))}}function Rvw(e){switch(e.type){case"response":return ve.V51.http.JsonResponse.response({...e,responseBodyType:ZM(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V51.http.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:ZM(e.responseBodyType),responseProperty:e.responseProperty!=null?hOd(e.responseProperty):void 0})}}function Nvw(e){switch(e.type){case"json":return ve.V51.http.StreamingResponse.json({...e,payload:ZM(e.payload)});case"text":return ve.V51.http.StreamingResponse.text(e);case"sse":return ve.V51.http.StreamingResponse.sse({...e,payload:ZM(e.payload)})}}function bT4(e){switch(e.type){case"json":return ve.V51.http.NonStreamHttpResponseBody.json(Rvw(e.value));case"text":return ve.V51.http.NonStreamHttpResponseBody.text(e);case"fileDownload":return ve.V51.http.NonStreamHttpResponseBody.fileDownload(e)}}function gT4(e){return{nonStreamResponse:bT4(e.nonStreamResponse),streamResponse:Nvw(e.streamResponse)}}function OT4(e){switch(e.type){case"cursor":return ve.V51.http.Pagination.cursor(mT4(e));case"offset":return ve.V51.http.Pagination.offset(PT4(e))}}function mT4(e){return{...e,page:iGi(e.page),next:OAi(e.next),results:OAi(e.results)}}function PT4(e){return{...e,page:iGi(e.page),results:OAi(e.results),step:e.step!=null?iGi(e.step):void 0}}function iGi(e){return{...e,property:jT4(e.property)}}function jT4(e){switch(e.type){case"query":return ve.V51.RequestPropertyValue.query(yOd(e));case"body":return ve.V51.RequestPropertyValue.body(hOd(e))}}function OAi(e){return{...e,property:hOd(e.property)}}function hOd(e){return{...e,valueType:ZM(e.valueType)}}function yOd(e){return{...e,valueType:ZM(e.valueType)}}function wT4(e){return{...e,streamParameter:e.streamParameter!=null?iGi(e.streamParameter):void 0,shape:ST4(e.shape)}}function ST4(e){return ve.V52.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V51.http.SdkRequestShape.justRequestBody(DT4(t)),wrapper:ve.V51.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function DT4(e){switch(e.type){case"bytes":return ve.V51.http.SdkRequestBodyType.bytes(e);case"typeReference":return ve.V51.http.SdkRequestBodyType.typeReference({...e,requestBodyType:ZM(e.requestBodyType)})}}function ET4(e){return ve.V52.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V51.http.HttpRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,valueType:ZM(r.valueType)}))}),reference:t=>ve.V51.http.HttpRequestBody.reference({...t,requestBodyType:ZM(t.requestBodyType)}),fileUpload:t=>ve.V51.http.HttpRequestBody.fileUpload({...t,properties:t.properties.map(r=>{switch(r.type){case"bodyProperty":return ve.V51.http.FileUploadRequestProperty.bodyProperty({...r,valueType:ZM(r.valueType)});case"file":return ve.V51.http.FileUploadRequestProperty.file(MT4(r.value))}})}),bytes:t=>ve.V51.http.HttpRequestBody.bytes(t),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function MT4(e){switch(e.type){case"file":return ve.V51.http.FileProperty.file(e);case"fileArray":return ve.V51.http.FileProperty.fileArray(e)}}function AT4(e){return{...e,type:e.type!=null?ZM(e.type):void 0,examples:e.examples.map(t=>({...t,shape:K9(t.shape)}))}}function qT4(e){return{...e,pathParameters:e.pathParameters.map(t=>JNs(t)),headers:e.headers.map(t=>_Od(t)),queryParameters:e.queryParameters.map(t=>Fvw(t)),messages:e.messages.map(t=>({...t,body:TT4(t.body)}))}}function Fvw(e){return{...e,value:K9(e.value)}}function _Od(e){return{...e,value:K9(e.value)}}function JNs(e){return{...e,value:K9(e.value)}}function TT4(e){switch(e.type){case"inlinedBody":return ve.V51.ExampleWebSocketMessageBody.inlinedBody(Lvw(e));case"reference":return ve.V51.ExampleWebSocketMessageBody.reference(K9(e))}}function Lvw(e){return{...e,properties:e.properties.map(t=>({...t,value:K9(t.value)}))}}function Cvw(e){return{...e,shape:Vvw(e.shape)}}function vOd(e){switch(e.type){case"primitive":return ve.V51.ExampleTypeReferenceShape.primitive(CT4(e));case"container":return ve.V51.ExampleTypeReferenceShape.container(BT4(e));case"unknown":return ve.V51.ExampleTypeReferenceShape.unknown(e.unknown);case"named":return ve.V51.ExampleTypeReferenceShape.named({...e,typeName:e.typeName,shape:Vvw(e.shape)})}}function Uvw(e){switch(e.type){case"integer":return ve.V51.ExamplePrimitive.integer(e.integer);case"uint":return ve.V51.ExamplePrimitive.integer(e.uint);case"uint64":return ve.V51.ExamplePrimitive.integer(e.uint64);case"double":return ve.V51.ExamplePrimitive.double(e.double);case"long":return ve.V51.ExamplePrimitive.long(e.long);case"boolean":return ve.V51.ExamplePrimitive.boolean(e.boolean);case"string":return ve.V51.ExamplePrimitive.string(e.string);case"date":return ve.V51.ExamplePrimitive.date(e.date);case"datetime":return ve.V51.ExamplePrimitive.datetime(e.datetime);case"uuid":return ve.V51.ExamplePrimitive.uuid(e.uuid)}}function CT4(e){return Uvw(e.primitive)}function BT4(e){switch(e.container.type){case"list":return ve.V51.ExampleContainer.list({list:e.container.list.map(t=>K9(t)),itemType:ZM(e.container.itemType)});case"set":return ve.V51.ExampleContainer.set({set:e.container.set.map(t=>K9(t)),itemType:ZM(e.container.itemType)});case"optional":return ve.V51.ExampleContainer.optional({optional:e.container.optional!=null?K9(e.container.optional):void 0,valueType:ZM(e.container.valueType)});case"map":return ve.V51.ExampleContainer.map({map:e.container.map.map(t=>({key:K9(t.key),value:K9(t.value)})),keyType:ZM(e.container.keyType),valueType:ZM(e.container.valueType)});case"literal":return ve.V51.ExampleContainer.literal({literal:Uvw(e.container.literal)})}}function K9(e){return{...e,shape:vOd(e.shape)}}function Vvw(e){switch(e.type){case"object":return ve.V51.ExampleTypeShape.object({properties:e.properties.map(t=>Wvw(t))});case"alias":return ve.V51.ExampleTypeShape.alias({value:{...K9(e.value)}});case"enum":return ve.V51.ExampleTypeShape.enum(e);case"union":return ve.V51.ExampleTypeShape.union(zT4(e));case"undiscriminatedUnion":return ve.V51.ExampleTypeShape.undiscriminatedUnion(IT4(e))}}function IT4(e){return{...e,singleUnionType:K9(e.singleUnionType)}}function zT4(e){return{...e,singleUnionType:xT4(e.singleUnionType)}}function xT4(e){return{...e,shape:RT4(e.shape)}}function RT4(e){switch(e.type){case"samePropertiesAsObject":return ve.V51.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...e,object:NT4(e.object)});case"singleProperty":return ve.V51.ExampleSingleUnionTypeProperties.singleProperty({...e,shape:vOd(e.shape)});case"noProperties":return ve.V51.ExampleSingleUnionTypeProperties.noProperties()}}function NT4(e){return{...e,properties:e.properties.map(t=>Wvw(t))}}function Wvw(e){return{...e,value:{...e.value,shape:vOd(e.value.shape)}}}function Bvw(e){return{...e,rootPathParameters:e.rootPathParameters.map(t=>JNs(t)),servicePathParameters:e.servicePathParameters.map(t=>JNs(t)),endpointPathParameters:e.endpointPathParameters.map(t=>JNs(t)),serviceHeaders:e.serviceHeaders.map(t=>_Od(t)),endpointHeaders:e.endpointHeaders.map(t=>_Od(t)),queryParameters:e.queryParameters.map(t=>Fvw(t)),request:e.request!=null?UT4(e.request):void 0,response:FT4(e.response)}}function FT4(e){switch(e.type){case"error":return ve.V51.ExampleResponse.error({...e,body:e.body!=null?K9(e.body):void 0});case"ok":return ve.V51.ExampleResponse.ok(LT4(e))}}function LT4(e){switch(e.value.type){case"body":return ve.V51.ExampleEndpointSuccessResponse.body(e.value.value!=null?K9(e.value.value):void 0);case"stream":return ve.V51.ExampleEndpointSuccessResponse.stream(e.value.value.map(t=>K9(t)));case"sse":return ve.V51.ExampleEndpointSuccessResponse.sse(e.value.value.map(t=>({...t,data:K9(t.data)})))}}function UT4(e){switch(e.type){case"inlinedRequestBody":return ve.V51.ExampleRequestBody.inlinedRequestBody(Lvw(e));case"reference":return ve.V51.ExampleRequestBody.reference(K9(e))}}var Gvw={laterVersion:"v53",earlierVersion:"v52",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.38.0-rc0",[$.TYPESCRIPT_BROWSER_SDK]:"0.38.0-rc0",[$.TYPESCRIPT]:"0.38.0-rc0",[$.TYPESCRIPT_SDK]:"0.38.0-rc0",[$.TYPESCRIPT_EXPRESS]:"0.17.3",[$.JAVA]:Ne,[$.JAVA_MODEL]:"1.3.0",[$.JAVA_SDK]:"2.5.0",[$.JAVA_SPRING]:"1.3.0",[$.PYTHON_FASTAPI]:"1.1.0-rc0",[$.PYTHON_PYDANTIC]:"1.1.0-rc0",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:"0.1.0",[$.STOPLIGHT]:Ne,[$.POSTMAN]:"0.2.0",[$.PYTHON_SDK]:"3.3.0-rc0",[$.GO_FIBER]:"0.23.5",[$.GO_MODEL]:"0.23.5",[$.GO_SDK]:"0.28.3",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:"0.5.0",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:"0.1.0",[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V52.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,apiVersion:e.apiVersion!=null?WT4(e.apiVersion):void 0,auth:XT4(e.auth),headers:e.headers.map(t=>JIn(t)),idempotencyHeaders:e.idempotencyHeaders.map(t=>JIn(t)),types:VT4(e.types),services:Sd(e.services,t=>sC4(t)),webhookGroups:Sd(e.webhookGroups,t=>QT4(t)),websocketChannels:Sd(e.websocketChannels,t=>HT4(t)),errors:Sd(e.errors,t=>wC4(t)),pathParameters:e.pathParameters.map(t=>HOo(t)),variables:e.variables.map(t=>cC4(t))})};function VT4(e){return Sd(e,t=>({...t,autogeneratedExamples:t.autogeneratedExamples.map(r=>Hvw(r)),userProvidedExamples:t.userProvidedExamples.map(r=>Hvw(r)),shape:ve.V53.types.Type._visit(t.shape,{union:r=>ve.V52.types.Type.union({...r,baseProperties:r.baseProperties.map(i=>({...i,valueType:kM(i.valueType)})),types:r.types.map(i=>nC4(i))}),enum:ve.V52.types.Type.enum,object:r=>ve.V52.types.Type.object({...r,properties:r.properties.map(i=>({...i,valueType:kM(i.valueType)}))}),alias:r=>ve.V52.types.Type.alias({aliasOf:kM(r.aliasOf),resolvedType:oC4(r.resolvedType)}),undiscriminatedUnion:r=>ve.V52.types.Type.undiscriminatedUnion(uC4(r)),_other:()=>{throw new Error("Encountered unknown shape")}})}))}function WT4(e){return ve.V52.ApiVersionScheme.header({...e,header:JIn(e.header)})}function HT4(e){return{...e,headers:e.headers.map(t=>JIn(t)),queryParameters:e.queryParameters.map(t=>OOd(t)),pathParameters:e.pathParameters.map(t=>HOo(t)),messages:e.messages.map(t=>$T4(t)),examples:e.examples.map(t=>SC4(t))}}function $T4(e){return{...e,body:GT4(e.body)}}function GT4(e){switch(e.type){case"inlinedBody":return ve.V52.websocket.WebSocketMessageBody.inlinedBody({...e,properties:e.properties.map(t=>({...t,valueType:kM(t.valueType)}))});case"reference":return ve.V52.websocket.WebSocketMessageBody.reference({...e,bodyType:kM(e.bodyType)})}}function QT4(e){return e.map(t=>JT4(t))}function JT4(e){return{...e,headers:e.headers.map(t=>JIn(t)),payload:KT4(e.payload),examples:e.examples!=null?e.examples.map(t=>YT4(t)):void 0}}function KT4(e){switch(e.type){case"reference":return ve.V52.webhooks.WebhookPayload.reference({...e,payloadType:kM(e.payloadType)});case"inlinedPayload":return ve.V52.webhooks.WebhookPayload.inlinedPayload({...e,properties:e.properties.map(t=>({...t,valueType:kM(t.valueType)}))})}}function YT4(e){return{...e,payload:Y9(e.payload)}}function XT4(e){return{...e,schemes:e.schemes.map(t=>{switch(t.type){case"basic":return ve.V52.auth.AuthScheme.basic(t);case"bearer":return ve.V52.auth.AuthScheme.bearer(t);case"header":return ve.V52.auth.AuthScheme.header(ZT4(t));case"oauth":return ve.V52.auth.AuthScheme.oauth(kT4(t))}})}}function ZT4(e){return{...e,valueType:kM(e.valueType)}}function kT4(e){return{...e,configuration:ve.V52.auth.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:eC4(e.configuration.tokenEndpoint),refreshEndpoint:e.configuration.refreshEndpoint!=null?tC4(e.configuration.refreshEndpoint):void 0})}}function eC4(e){return{...e,requestProperties:{clientId:nGi(e.requestProperties.clientId),clientSecret:nGi(e.requestProperties.clientSecret),scopes:e.requestProperties.scopes!=null?nGi(e.requestProperties.scopes):void 0},responseProperties:{accessToken:mAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?mAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?mAi(e.responseProperties.refreshToken):void 0}}}function tC4(e){return{...e,requestProperties:{refreshToken:nGi(e.requestProperties.refreshToken)},responseProperties:{accessToken:mAi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?mAi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?mAi(e.responseProperties.refreshToken):void 0}}}function JIn(e){return{...e,valueType:kM(e.valueType)}}function kM(e){return ve.V53.types.TypeReference._visit(e,{container:t=>ve.V52.types.TypeReference.container(Jvw(t)),primitive:t=>ve.V52.types.TypeReference.primitive(Qvw(t)),named:ve.V52.types.TypeReference.named,unknown:ve.V52.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function Qvw(e){return{v1:rC4(e.v1),v2:e.v2!=null?iC4(e.v2):void 0}}function rC4(e){switch(e){case"FLOAT":return ve.V52.types.PrimitiveTypeV1.Double}return e}function iC4(e){switch(e.type){case"integer":return ve.V52.types.PrimitiveTypeV2.integer(e);case"double":return ve.V52.types.PrimitiveTypeV2.double(e);case"string":return ve.V52.types.PrimitiveTypeV2.string(e);case"boolean":return ve.V52.types.PrimitiveTypeV2.boolean(e);case"long":return ve.V52.types.PrimitiveTypeV2.long(e);case"bigInteger":return ve.V52.types.PrimitiveTypeV2.bigInteger(e);case"uint":return ve.V52.types.PrimitiveTypeV2.uint();case"uint64":return ve.V52.types.PrimitiveTypeV2.uint64();case"date":return;case"dateTime":return;case"uuid":return;case"base64":return;case"float":return;default:Ao(e)}}function Jvw(e){return ve.V53.types.ContainerType._visit(e,{list:t=>ve.V52.types.ContainerType.list(kM(t)),optional:t=>ve.V52.types.ContainerType.optional(kM(t)),set:t=>ve.V52.types.ContainerType.set(kM(t)),map:({keyType:t,valueType:r})=>ve.V52.types.ContainerType.map({keyType:kM(t),valueType:kM(r)}),literal:ve.V52.types.ContainerType.literal,_other:()=>{throw new Error("Unknown ContainerType: "+e.type)}})}function nC4(e){return{...e,shape:aC4(e.shape)}}function aC4(e){return ve.V53.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V52.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V52.types.SingleUnionTypeProperties.singleProperty({...t,type:kM(t.type)}),noProperties:ve.V52.types.SingleUnionTypeProperties.noProperties,_other:()=>{throw new Error(`Unknown SingleUnionTypeProperties: ${JSON.stringify(e)}`)}})}function oC4(e){return ve.V53.types.ResolvedTypeReference._visit(e,{container:t=>ve.V52.types.ResolvedTypeReference.container(Jvw(t)),named:ve.V52.types.ResolvedTypeReference.named,primitive:t=>ve.V52.types.ResolvedTypeReference.primitive(Qvw(t)),unknown:ve.V52.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown ResolvedTypeReference: "+e.type)}})}function uC4(e){return{members:e.members.map(t=>({...t,type:kM(t.type)}))}}function sC4(e){return{...e,pathParameters:e.pathParameters.map(t=>HOo(t)),headers:e.headers.map(t=>JIn(t)),endpoints:e.endpoints.map(t=>lC4(t))}}function HOo(e){return{...e,valueType:kM(e.valueType)}}function cC4(e){return{...e,type:kM(e.type)}}function lC4(e){return{...e,pagination:e.pagination!=null?hC4(e.pagination):void 0,allPathParameters:e.allPathParameters.map(t=>HOo(t)),pathParameters:e.pathParameters.map(t=>HOo(t)),sdkRequest:e.sdkRequest!=null?gC4(e.sdkRequest):void 0,requestBody:e.requestBody!=null?PC4(e.requestBody):void 0,response:e.response!=null?fC4(e.response):void 0,headers:e.headers.map(t=>JIn(t)),queryParameters:e.queryParameters.map(t=>OOd(t)),autogeneratedExamples:e.autogeneratedExamples.map(t=>({...t,example:$vw(t.example)})),userSpecifiedExamples:e.userSpecifiedExamples.map(t=>({...t,example:t.example!=null?$vw(t.example):void 0}))}}function fC4(e){return{...e,body:e.body!=null?dC4(e.body):void 0}}function dC4(e){switch(e.type){case"json":return ve.V52.http.HttpResponseBody.json(Kvw(e.value));case"fileDownload":return ve.V52.http.HttpResponseBody.fileDownload(e);case"text":return ve.V52.http.HttpResponseBody.text(e);case"streaming":return ve.V52.http.HttpResponseBody.streaming(Yvw(e.value));case"streamParameter":return ve.V52.http.HttpResponseBody.streamParameter(_C4(e))}}function Kvw(e){switch(e.type){case"response":return ve.V52.http.JsonResponse.response({...e,responseBodyType:kM(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V52.http.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:kM(e.responseBodyType),responseProperty:e.responseProperty!=null?gOd(e.responseProperty):void 0})}}function Yvw(e){switch(e.type){case"json":return ve.V52.http.StreamingResponse.json({...e,payload:kM(e.payload)});case"text":return ve.V52.http.StreamingResponse.text(e);case"sse":return ve.V52.http.StreamingResponse.sse({...e,payload:kM(e.payload)})}}function pC4(e){switch(e.type){case"json":return ve.V52.http.NonStreamHttpResponseBody.json(Kvw(e.value));case"text":return ve.V52.http.NonStreamHttpResponseBody.text(e);case"fileDownload":return ve.V52.http.NonStreamHttpResponseBody.fileDownload(e)}}function _C4(e){return{nonStreamResponse:pC4(e.nonStreamResponse),streamResponse:Yvw(e.streamResponse)}}function hC4(e){switch(e.type){case"cursor":return ve.V52.http.Pagination.cursor(yC4(e));case"offset":return ve.V52.http.Pagination.offset(vC4(e))}}function yC4(e){return{...e,page:nGi(e.page),next:mAi(e.next),results:mAi(e.results)}}function vC4(e){return{...e,page:nGi(e.page),results:mAi(e.results),step:e.step!=null?nGi(e.step):void 0}}function nGi(e){return{...e,property:bC4(e.property)}}function bC4(e){switch(e.type){case"query":return ve.V52.RequestPropertyValue.query(OOd(e));case"body":return ve.V52.RequestPropertyValue.body(gOd(e))}}function mAi(e){return{...e,property:gOd(e.property)}}function gOd(e){return{...e,valueType:kM(e.valueType)}}function OOd(e){return{...e,valueType:kM(e.valueType)}}function gC4(e){return{...e,streamParameter:e.streamParameter!=null?nGi(e.streamParameter):void 0,shape:OC4(e.shape)}}function OC4(e){return ve.V53.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V52.http.SdkRequestShape.justRequestBody(mC4(t)),wrapper:ve.V52.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function mC4(e){switch(e.type){case"bytes":return ve.V52.http.SdkRequestBodyType.bytes(e);case"typeReference":return ve.V52.http.SdkRequestBodyType.typeReference({...e,requestBodyType:kM(e.requestBodyType)})}}function PC4(e){return ve.V53.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V52.http.HttpRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,valueType:kM(r.valueType)}))}),reference:t=>ve.V52.http.HttpRequestBody.reference({...t,requestBodyType:kM(t.requestBodyType)}),fileUpload:t=>ve.V52.http.HttpRequestBody.fileUpload({...t,properties:t.properties.map(r=>{switch(r.type){case"bodyProperty":return ve.V52.http.FileUploadRequestProperty.bodyProperty({...r,valueType:kM(r.valueType)});case"file":return ve.V52.http.FileUploadRequestProperty.file(jC4(r.value))}})}),bytes:t=>ve.V52.http.HttpRequestBody.bytes(t),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function jC4(e){switch(e.type){case"file":return ve.V52.http.FileProperty.file(e);case"fileArray":return ve.V52.http.FileProperty.fileArray(e)}}function wC4(e){return{...e,type:e.type!=null?kM(e.type):void 0,examples:e.examples.map(t=>({...t,shape:Y9(t.shape)}))}}function SC4(e){return{...e,pathParameters:e.pathParameters.map(t=>KNs(t)),headers:e.headers.map(t=>bOd(t)),queryParameters:e.queryParameters.map(t=>Xvw(t)),messages:e.messages.map(t=>({...t,body:DC4(t.body)}))}}function Xvw(e){return{...e,value:Y9(e.value)}}function bOd(e){return{...e,value:Y9(e.value)}}function KNs(e){return{...e,value:Y9(e.value)}}function DC4(e){switch(e.type){case"inlinedBody":return ve.V52.ExampleWebSocketMessageBody.inlinedBody(Zvw(e));case"reference":return ve.V52.ExampleWebSocketMessageBody.reference(Y9(e))}}function Zvw(e){return{...e,properties:e.properties.map(t=>({...t,value:Y9(t.value)}))}}function Hvw(e){return{...e,shape:ebw(e.shape)}}function mOd(e){switch(e.type){case"primitive":return ve.V52.ExampleTypeReferenceShape.primitive(EC4(e));case"container":return ve.V52.ExampleTypeReferenceShape.container(MC4(e));case"unknown":return ve.V52.ExampleTypeReferenceShape.unknown(e.unknown);case"named":return ve.V52.ExampleTypeReferenceShape.named({...e,typeName:e.typeName,shape:ebw(e.shape)})}}function kvw(e){switch(e.type){case"integer":return ve.V52.ExamplePrimitive.integer(e.integer);case"uint":return ve.V52.ExamplePrimitive.integer(e.uint);case"uint64":return ve.V52.ExamplePrimitive.integer(e.uint64);case"float":return ve.V52.ExamplePrimitive.double(e.float);case"double":return ve.V52.ExamplePrimitive.double(e.double);case"long":return ve.V52.ExamplePrimitive.long(e.long);case"boolean":return ve.V52.ExamplePrimitive.boolean(e.boolean);case"string":return ve.V52.ExamplePrimitive.string(e.string);case"date":return ve.V52.ExamplePrimitive.date(e.date);case"datetime":return ve.V52.ExamplePrimitive.datetime(e.datetime);case"uuid":return ve.V52.ExamplePrimitive.uuid(e.uuid);case"base64":return ve.V52.ExamplePrimitive.string({original:e.base64});case"bigInteger":return ve.V52.ExamplePrimitive.string({original:e.bigInteger})}}function EC4(e){return kvw(e.primitive)}function MC4(e){switch(e.container.type){case"list":return ve.V52.ExampleContainer.list({list:e.container.list.map(t=>Y9(t)),itemType:kM(e.container.itemType)});case"set":return ve.V52.ExampleContainer.set({set:e.container.set.map(t=>Y9(t)),itemType:kM(e.container.itemType)});case"optional":return ve.V52.ExampleContainer.optional({optional:e.container.optional!=null?Y9(e.container.optional):void 0,valueType:kM(e.container.valueType)});case"map":return ve.V52.ExampleContainer.map({map:e.container.map.map(t=>({key:Y9(t.key),value:Y9(t.value)})),keyType:kM(e.container.keyType),valueType:kM(e.container.valueType)});case"literal":return ve.V52.ExampleContainer.literal({literal:kvw(e.container.literal)})}}function Y9(e){return{...e,shape:mOd(e.shape)}}function ebw(e){switch(e.type){case"object":return ve.V52.ExampleTypeShape.object({properties:e.properties.map(t=>tbw(t))});case"alias":return ve.V52.ExampleTypeShape.alias({value:{...Y9(e.value)}});case"enum":return ve.V52.ExampleTypeShape.enum(e);case"union":return ve.V52.ExampleTypeShape.union(qC4(e));case"undiscriminatedUnion":return ve.V52.ExampleTypeShape.undiscriminatedUnion(AC4(e))}}function AC4(e){return{...e,singleUnionType:Y9(e.singleUnionType)}}function qC4(e){return{...e,singleUnionType:TC4(e.singleUnionType)}}function TC4(e){return{...e,shape:CC4(e.shape)}}function CC4(e){switch(e.type){case"samePropertiesAsObject":return ve.V52.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...e,object:BC4(e.object)});case"singleProperty":return ve.V52.ExampleSingleUnionTypeProperties.singleProperty({...e,shape:mOd(e.shape)});case"noProperties":return ve.V52.ExampleSingleUnionTypeProperties.noProperties()}}function BC4(e){return{...e,properties:e.properties.map(t=>tbw(t))}}function tbw(e){return{...e,value:{...e.value,shape:mOd(e.value.shape)}}}function $vw(e){return{...e,rootPathParameters:e.rootPathParameters.map(t=>KNs(t)),servicePathParameters:e.servicePathParameters.map(t=>KNs(t)),endpointPathParameters:e.endpointPathParameters.map(t=>KNs(t)),serviceHeaders:e.serviceHeaders.map(t=>bOd(t)),endpointHeaders:e.endpointHeaders.map(t=>bOd(t)),queryParameters:e.queryParameters.map(t=>Xvw(t)),request:e.request!=null?xC4(e.request):void 0,response:IC4(e.response)}}function IC4(e){switch(e.type){case"error":return ve.V52.ExampleResponse.error({...e,body:e.body!=null?Y9(e.body):void 0});case"ok":return ve.V52.ExampleResponse.ok(zC4(e))}}function zC4(e){switch(e.value.type){case"body":return ve.V52.ExampleEndpointSuccessResponse.body(e.value.value!=null?Y9(e.value.value):void 0);case"stream":return ve.V52.ExampleEndpointSuccessResponse.stream(e.value.value.map(t=>Y9(t)));case"sse":return ve.V52.ExampleEndpointSuccessResponse.sse(e.value.value.map(t=>({...t,data:Y9(t.data)})))}}function xC4(e){switch(e.type){case"inlinedRequestBody":return ve.V52.ExampleRequestBody.inlinedRequestBody(Zvw(e));case"reference":return ve.V52.ExampleRequestBody.reference(Y9(e))}}var rbw={laterVersion:"v54",earlierVersion:"v53",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:Ne,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V53.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,services:Sd(e.services,t=>({...t,endpoints:t.endpoints.map(r=>({...r,response:RC4(r.response)}))}))})};function RC4(e){if(e!=null)return{statusCode:e.statusCode,body:e.body?.type==="bytes"?ve.V53.HttpResponseBody.fileDownload({docs:void 0}):e.body}}var abw={laterVersion:"v55",earlierVersion:"v54",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.47.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.47.0",[$.TYPESCRIPT]:"0.47.0",[$.TYPESCRIPT_SDK]:"0.47.0",[$.TYPESCRIPT_EXPRESS]:"0.17.7",[$.JAVA]:Ne,[$.JAVA_MODEL]:"1.7.0",[$.JAVA_SDK]:"2.16.0",[$.JAVA_SPRING]:"1.5.0",[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:"1.10.1",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:"0.3.2",[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V54.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,apiVersion:e.apiVersion!=null?FC4(e.apiVersion):void 0,auth:QC4(e.auth),headers:e.headers.map(t=>KIn(t)),idempotencyHeaders:e.idempotencyHeaders.map(t=>KIn(t)),types:NC4(e.types),services:Sd(e.services,t=>rB4(t)),webhookGroups:Sd(e.webhookGroups,t=>WC4(t)),websocketChannels:Sd(e.websocketChannels,t=>LC4(t)),errors:Sd(e.errors,t=>bB4(t)),pathParameters:e.pathParameters.map(t=>$Oo(t)),variables:e.variables.map(t=>iB4(t)),dynamic:e.dynamic!=null?TB4(e.dynamic):void 0})};function NC4(e){return Sd(e,t=>({...t,autogeneratedExamples:t.autogeneratedExamples.map(r=>ibw(r)),userProvidedExamples:t.userProvidedExamples.map(r=>ibw(r)),shape:ve.V55.types.Type._visit(t.shape,{union:r=>ve.V54.types.Type.union({...r,baseProperties:r.baseProperties.map(i=>({...i,valueType:Yj(i.valueType)})),types:r.types.map(i=>ZC4(i))}),enum:ve.V54.types.Type.enum,object:r=>ve.V54.types.Type.object({...r,properties:r.properties.map(i=>({...i,valueType:Yj(i.valueType)})),extendedProperties:r.extendedProperties?.map(i=>({...i,valueType:Yj(i.valueType)}))}),alias:r=>ve.V54.types.Type.alias({aliasOf:Yj(r.aliasOf),resolvedType:eB4(r.resolvedType)}),undiscriminatedUnion:r=>ve.V54.types.Type.undiscriminatedUnion(tB4(r)),_other:()=>{throw new Error("Encountered unknown shape")}})}))}function FC4(e){return ve.V54.ApiVersionScheme.header({...e,header:KIn(e.header)})}function LC4(e){return{...e,headers:e.headers.map(t=>KIn(t)),queryParameters:e.queryParameters.map(t=>wOd(t)),pathParameters:e.pathParameters.map(t=>$Oo(t)),messages:e.messages.map(t=>UC4(t)),examples:e.examples.map(t=>gB4(t))}}function UC4(e){return{...e,body:VC4(e.body)}}function VC4(e){switch(e.type){case"inlinedBody":return ve.V54.websocket.WebSocketMessageBody.inlinedBody({...e,properties:e.properties.map(t=>({...t,valueType:Yj(t.valueType)}))});case"reference":return ve.V54.websocket.WebSocketMessageBody.reference({...e,bodyType:Yj(e.bodyType)})}}function WC4(e){return e.map(t=>HC4(t))}function HC4(e){return{...e,headers:e.headers.map(t=>KIn(t)),payload:$C4(e.payload),examples:e.examples!=null?e.examples.map(t=>GC4(t)):void 0}}function $C4(e){switch(e.type){case"reference":return ve.V54.webhooks.WebhookPayload.reference({...e,payloadType:Yj(e.payloadType)});case"inlinedPayload":return ve.V54.webhooks.WebhookPayload.inlinedPayload({...e,properties:e.properties.map(t=>({...t,valueType:Yj(t.valueType)}))})}}function GC4(e){return{...e,payload:m8(e.payload)}}function QC4(e){return{...e,schemes:e.schemes.map(t=>{switch(t.type){case"basic":return ve.V54.auth.AuthScheme.basic(t);case"bearer":return ve.V54.auth.AuthScheme.bearer(t);case"header":return ve.V54.auth.AuthScheme.header(JC4(t));case"oauth":return ve.V54.auth.AuthScheme.oauth(KC4(t))}})}}function JC4(e){return{...e,valueType:Yj(e.valueType)}}function KC4(e){return{...e,configuration:ve.V54.auth.OAuthConfiguration.clientCredentials({...e.configuration,tokenEndpoint:YC4(e.configuration.tokenEndpoint),refreshEndpoint:e.configuration.refreshEndpoint!=null?XC4(e.configuration.refreshEndpoint):void 0})}}function YC4(e){return{...e,requestProperties:{clientId:aGi(e.requestProperties.clientId),clientSecret:aGi(e.requestProperties.clientSecret),scopes:e.requestProperties.scopes!=null?aGi(e.requestProperties.scopes):void 0},responseProperties:{accessToken:wvi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?wvi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?wvi(e.responseProperties.refreshToken):void 0}}}function XC4(e){return{...e,requestProperties:{refreshToken:aGi(e.requestProperties.refreshToken)},responseProperties:{accessToken:wvi(e.responseProperties.accessToken),expiresIn:e.responseProperties.expiresIn!=null?wvi(e.responseProperties.expiresIn):void 0,refreshToken:e.responseProperties.refreshToken!=null?wvi(e.responseProperties.refreshToken):void 0}}}function KIn(e){return{...e,valueType:Yj(e.valueType)}}function Yj(e){return e.type==="container"&&e.container.type==="nullable"?HB4(e.container.nullable):e.type==="container"&&e.container.type==="optional"?WB4(e.container.optional):ve.V55.types.TypeReference._visit(e,{container:t=>ve.V54.types.TypeReference.container(ubw(t)),primitive:t=>ve.V54.types.TypeReference.primitive(obw(t)),named:ve.V54.types.TypeReference.named,unknown:ve.V54.types.TypeReference.unknown,_other:()=>{throw new Error("Unknown type reference: "+e.type)}})}function obw(e){return{v1:e.v1,v2:e.v2!=null?e.v2:void 0}}function ubw(e){return ve.V55.types.ContainerType._visit(e,{list:t=>ve.V54.types.ContainerType.list(Yj(t)),optional:t=>ve.V54.types.ContainerType.optional(Yj(t)),nullable:t=>ve.V54.types.ContainerType.optional(Yj(t)),set:t=>ve.V54.types.ContainerType.set(Yj(t)),map:({keyType:t,valueType:r})=>ve.V54.types.ContainerType.map({keyType:Yj(t),valueType:Yj(r)}),literal:ve.V54.types.ContainerType.literal,_other:()=>{throw new Error("Unknown ContainerType: "+e.type)}})}function ZC4(e){return{...e,shape:kC4(e.shape)}}function kC4(e){return ve.V55.types.SingleUnionTypeProperties._visit(e,{samePropertiesAsObject:t=>ve.V54.types.SingleUnionTypeProperties.samePropertiesAsObject(t),singleProperty:t=>ve.V54.types.SingleUnionTypeProperties.singleProperty({...t,type:Yj(t.type)}),noProperties:ve.V54.types.SingleUnionTypeProperties.noProperties,_other:()=>{throw new Error(`Unknown SingleUnionTypeProperties: ${JSON.stringify(e)}`)}})}function eB4(e){return ve.V55.types.ResolvedTypeReference._visit(e,{container:t=>ve.V54.types.ResolvedTypeReference.container(ubw(t)),named:ve.V54.types.ResolvedTypeReference.named,primitive:t=>ve.V54.types.ResolvedTypeReference.primitive(obw(t)),unknown:ve.V54.types.ResolvedTypeReference.unknown,_other:()=>{throw new Error("Unknown ResolvedTypeReference: "+e.type)}})}function tB4(e){return{members:e.members.map(t=>({...t,type:Yj(t.type)}))}}function rB4(e){return{...e,pathParameters:e.pathParameters.map(t=>$Oo(t)),headers:e.headers.map(t=>KIn(t)),endpoints:e.endpoints.map(t=>nB4(t))}}function $Oo(e){return{...e,valueType:Yj(e.valueType)}}function iB4(e){return{...e,type:Yj(e.type)}}function nB4(e){return{...e,pagination:e.pagination!=null?cB4(e.pagination):void 0,allPathParameters:e.allPathParameters.map(t=>$Oo(t)),pathParameters:e.pathParameters.map(t=>$Oo(t)),sdkRequest:e.sdkRequest!=null?pB4(e.sdkRequest):void 0,requestBody:e.requestBody!=null?yB4(e.requestBody):void 0,response:e.response!=null?aB4(e.response):void 0,headers:e.headers.map(t=>KIn(t)),queryParameters:e.queryParameters.map(t=>wOd(t)),autogeneratedExamples:e.autogeneratedExamples.map(t=>({...t,example:nbw(t.example)})),userSpecifiedExamples:e.userSpecifiedExamples.map(t=>({...t,example:t.example!=null?nbw(t.example):void 0}))}}function aB4(e){return{...e,body:e.body!=null?oB4(e.body):void 0}}function oB4(e){switch(e.type){case"json":return ve.V54.http.HttpResponseBody.json(sbw(e.value));case"fileDownload":return ve.V54.http.HttpResponseBody.fileDownload(e);case"bytes":return ve.V54.http.HttpResponseBody.bytes(e);case"text":return ve.V54.http.HttpResponseBody.text(e);case"streaming":return ve.V54.http.HttpResponseBody.streaming(cbw(e.value));case"streamParameter":return ve.V54.http.HttpResponseBody.streamParameter(sB4(e));default:Ao(e)}}function sbw(e){switch(e.type){case"response":return ve.V54.http.JsonResponse.response({...e,responseBodyType:Yj(e.responseBodyType)});case"nestedPropertyAsResponse":return ve.V54.http.JsonResponse.nestedPropertyAsResponse({...e,responseBodyType:Yj(e.responseBodyType),responseProperty:e.responseProperty!=null?jOd(e.responseProperty):void 0})}}function cbw(e){switch(e.type){case"json":return ve.V54.http.StreamingResponse.json({...e,payload:Yj(e.payload)});case"text":return ve.V54.http.StreamingResponse.text(e);case"sse":return ve.V54.http.StreamingResponse.sse({...e,payload:Yj(e.payload)})}}function uB4(e){switch(e.type){case"json":return ve.V54.http.NonStreamHttpResponseBody.json(sbw(e.value));case"bytes":return ve.V54.http.NonStreamHttpResponseBody.bytes(e);case"text":return ve.V54.http.NonStreamHttpResponseBody.text(e);case"fileDownload":return ve.V54.http.NonStreamHttpResponseBody.fileDownload(e);default:Ao(e)}}function sB4(e){return{nonStreamResponse:uB4(e.nonStreamResponse),streamResponse:cbw(e.streamResponse)}}function cB4(e){switch(e.type){case"cursor":return ve.V54.http.Pagination.cursor(lB4(e));case"offset":return ve.V54.http.Pagination.offset(fB4(e))}}function lB4(e){return{...e,page:aGi(e.page),next:wvi(e.next),results:wvi(e.results)}}function fB4(e){return{...e,page:aGi(e.page),results:wvi(e.results),step:e.step!=null?aGi(e.step):void 0,hasNextPage:e.hasNextPage!=null?wvi(e.hasNextPage):void 0}}function aGi(e){return{...e,property:dB4(e.property)}}function dB4(e){switch(e.type){case"query":return ve.V54.RequestPropertyValue.query(wOd(e));case"body":return ve.V54.RequestPropertyValue.body(jOd(e))}}function wvi(e){return{...e,property:jOd(e.property)}}function jOd(e){return{...e,valueType:Yj(e.valueType)}}function wOd(e){return{...e,valueType:Yj(e.valueType)}}function pB4(e){return{...e,streamParameter:e.streamParameter!=null?aGi(e.streamParameter):void 0,shape:_B4(e.shape)}}function _B4(e){return ve.V55.http.SdkRequestShape._visit(e,{justRequestBody:t=>ve.V54.http.SdkRequestShape.justRequestBody(hB4(t)),wrapper:ve.V54.http.SdkRequestShape.wrapper,_other:()=>{throw new Error("Unknown SdkRequestShape: "+e.type)}})}function hB4(e){switch(e.type){case"bytes":return ve.V54.http.SdkRequestBodyType.bytes(e);case"typeReference":return ve.V54.http.SdkRequestBodyType.typeReference({...e,requestBodyType:Yj(e.requestBodyType)})}}function yB4(e){return ve.V55.http.HttpRequestBody._visit(e,{inlinedRequestBody:t=>ve.V54.http.HttpRequestBody.inlinedRequestBody({...t,properties:t.properties.map(r=>({...r,valueType:Yj(r.valueType)})),extendedProperties:t.extendedProperties?.map(r=>({...r,valueType:Yj(r.valueType)}))}),reference:t=>ve.V54.http.HttpRequestBody.reference({...t,requestBodyType:Yj(t.requestBodyType)}),fileUpload:t=>ve.V54.http.HttpRequestBody.fileUpload({...t,properties:t.properties.map(r=>{switch(r.type){case"bodyProperty":return ve.V54.http.FileUploadRequestProperty.bodyProperty({...r,valueType:Yj(r.valueType)});case"file":return ve.V54.http.FileUploadRequestProperty.file(vB4(r.value))}})}),bytes:t=>ve.V54.http.HttpRequestBody.bytes(t),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}})}function vB4(e){switch(e.type){case"file":return ve.V54.http.FileProperty.file(e);case"fileArray":return ve.V54.http.FileProperty.fileArray(e)}}function bB4(e){return{...e,type:e.type!=null?Yj(e.type):void 0,examples:e.examples.map(t=>({...t,shape:m8(t.shape)}))}}function gB4(e){return{...e,pathParameters:e.pathParameters.map(t=>YNs(t)),headers:e.headers.map(t=>POd(t)),queryParameters:e.queryParameters.map(t=>lbw(t)),messages:e.messages.map(t=>({...t,body:OB4(t.body)}))}}function lbw(e){return{...e,value:m8(e.value)}}function POd(e){return{...e,value:m8(e.value)}}function YNs(e){return{...e,value:m8(e.value)}}function OB4(e){switch(e.type){case"inlinedBody":return ve.V54.ExampleWebSocketMessageBody.inlinedBody(fbw(e));case"reference":return ve.V54.ExampleWebSocketMessageBody.reference(m8(e))}}function fbw(e){return{...e,properties:e.properties.map(t=>({...t,value:m8(t.value)}))}}function ibw(e){return{...e,shape:dbw(e.shape)}}function SOd(e){switch(e.type){case"primitive":return ve.V54.ExampleTypeReferenceShape.primitive(mB4(e));case"container":return ve.V54.ExampleTypeReferenceShape.container(PB4(e));case"unknown":return ve.V54.ExampleTypeReferenceShape.unknown(e.unknown);case"named":return ve.V54.ExampleTypeReferenceShape.named({...e,typeName:e.typeName,shape:dbw(e.shape)})}}function mB4(e){return e.primitive}function PB4(e){switch(e.container.type){case"list":return ve.V54.ExampleContainer.list({list:e.container.list.map(t=>m8(t)),itemType:Yj(e.container.itemType)});case"set":return ve.V54.ExampleContainer.set({set:e.container.set.map(t=>m8(t)),itemType:Yj(e.container.itemType)});case"optional":return ve.V54.ExampleContainer.optional({optional:e.container.optional!=null?m8(e.container.optional):void 0,valueType:Yj(e.container.valueType)});case"nullable":return ve.V54.ExampleContainer.optional({optional:e.container.nullable!=null?m8(e.container.nullable):void 0,valueType:Yj(e.container.valueType)});case"map":return ve.V54.ExampleContainer.map({map:e.container.map.map(t=>({key:m8(t.key),value:m8(t.value)})),keyType:Yj(e.container.keyType),valueType:Yj(e.container.valueType)});case"literal":return ve.V54.ExampleContainer.literal({literal:e.container.literal})}}function m8(e){return{...e,shape:SOd(e.shape)}}function dbw(e){switch(e.type){case"object":return ve.V54.ExampleTypeShape.object({properties:e.properties.map(t=>pbw(t))});case"alias":return ve.V54.ExampleTypeShape.alias({value:{...m8(e.value)}});case"enum":return ve.V54.ExampleTypeShape.enum(e);case"union":return ve.V54.ExampleTypeShape.union(wB4(e));case"undiscriminatedUnion":return ve.V54.ExampleTypeShape.undiscriminatedUnion(jB4(e))}}function jB4(e){return{...e,singleUnionType:m8(e.singleUnionType)}}function wB4(e){return{...e,singleUnionType:SB4(e.singleUnionType)}}function SB4(e){return{...e,shape:DB4(e.shape)}}function DB4(e){switch(e.type){case"samePropertiesAsObject":return ve.V54.ExampleSingleUnionTypeProperties.samePropertiesAsObject({...e,object:EB4(e.object)});case"singleProperty":return ve.V54.ExampleSingleUnionTypeProperties.singleProperty({...e,shape:SOd(e.shape)});case"noProperties":return ve.V54.ExampleSingleUnionTypeProperties.noProperties()}}function EB4(e){return{...e,properties:e.properties.map(t=>pbw(t))}}function pbw(e){return{...e,value:{...e.value,shape:SOd(e.value.shape)}}}function nbw(e){return{...e,rootPathParameters:e.rootPathParameters.map(t=>YNs(t)),servicePathParameters:e.servicePathParameters.map(t=>YNs(t)),endpointPathParameters:e.endpointPathParameters.map(t=>YNs(t)),serviceHeaders:e.serviceHeaders.map(t=>POd(t)),endpointHeaders:e.endpointHeaders.map(t=>POd(t)),queryParameters:e.queryParameters.map(t=>lbw(t)),request:e.request!=null?qB4(e.request):void 0,response:MB4(e.response)}}function MB4(e){switch(e.type){case"error":return ve.V54.ExampleResponse.error({...e,body:e.body!=null?m8(e.body):void 0});case"ok":return ve.V54.ExampleResponse.ok(AB4(e))}}function AB4(e){switch(e.value.type){case"body":return ve.V54.ExampleEndpointSuccessResponse.body(e.value.value!=null?m8(e.value.value):void 0);case"stream":return ve.V54.ExampleEndpointSuccessResponse.stream(e.value.value.map(t=>m8(t)));case"sse":return ve.V54.ExampleEndpointSuccessResponse.sse(e.value.value.map(t=>({...t,data:m8(t.data)})))}}function qB4(e){switch(e.type){case"inlinedRequestBody":return ve.V54.ExampleRequestBody.inlinedRequestBody(fbw(e));case"reference":return ve.V54.ExampleRequestBody.reference(m8(e))}}function TB4(e){return{...e,types:Sd(e.types,t=>CB4(t)),endpoints:Sd(e.endpoints,t=>BB4(t)),headers:e.headers?.map(t=>pHt(t))}}function CB4(e){switch(e.type){case"alias":return ve.V54.dynamic.NamedType.alias({...e,typeReference:dze(e.typeReference)});case"enum":return ve.V54.dynamic.NamedType.enum(e);case"object":return ve.V54.dynamic.NamedType.object({...e,properties:e.properties.map(t=>pHt(t))});case"discriminatedUnion":return ve.V54.dynamic.NamedType.discriminatedUnion({...e,types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,zB4(r)]))});case"undiscriminatedUnion":return ve.V54.dynamic.NamedType.undiscriminatedUnion({...e,types:e.types.map(t=>dze(t))});default:Ao(e)}}function BB4(e){return{...e,auth:e.auth!=null?IB4(e.auth):void 0,request:xB4(e.request)}}function IB4(e){switch(e.type){case"basic":return ve.V54.dynamic.Auth.basic(e);case"bearer":return ve.V54.dynamic.Auth.bearer(e);case"header":return ve.V54.dynamic.Auth.header({header:pHt(e.header)})}}function dze(e){switch(e.type){case"list":return ve.V54.dynamic.TypeReference.list(dze(e.value));case"optional":return GB4(e.value);case"nullable":return $B4(e.value);case"map":return ve.V54.dynamic.TypeReference.map({...e,key:dze(e.key),value:dze(e.value)});case"literal":return ve.V54.dynamic.TypeReference.literal(e.value);case"named":return ve.V54.dynamic.TypeReference.named(e.value);case"primitive":return ve.V54.dynamic.TypeReference.primitive(e.value);case"set":return ve.V54.dynamic.TypeReference.set(dze(e.value));case"unknown":return ve.V54.dynamic.TypeReference.unknown();default:Ao(e)}}function zB4(e){switch(e.type){case"samePropertiesAsObject":return ve.V54.dynamic.SingleDiscriminatedUnionType.samePropertiesAsObject({...e,properties:e.properties.map(t=>pHt(t))});case"singleProperty":return ve.V54.dynamic.SingleDiscriminatedUnionType.singleProperty({...e,typeReference:dze(e.typeReference),properties:e.properties?.map(t=>pHt(t))});case"noProperties":return ve.V54.dynamic.SingleDiscriminatedUnionType.noProperties({...e,properties:e.properties?.map(t=>pHt(t))});default:Ao(e)}}function pHt(e){return{...e,typeReference:dze(e.typeReference)}}function xB4(e){switch(e.type){case"body":return ve.V54.dynamic.Request.body(RB4(e));case"inlined":return ve.V54.dynamic.Request.inlined(NB4(e));default:Ao(e)}}function RB4(e){return{pathParameters:e.pathParameters?.map(t=>pHt(t)),body:e.body!=null?_bw(e.body):void 0}}function NB4(e){return{...e,pathParameters:e.pathParameters?.map(t=>pHt(t)),queryParameters:e.queryParameters?.map(t=>pHt(t)),headers:e.headers?.map(t=>pHt(t)),body:e.body!=null?FB4(e.body):void 0}}function FB4(e){switch(e.type){case"properties":return ve.V54.dynamic.InlinedRequestBody.properties(e.value.map(t=>pHt(t)));case"referenced":return ve.V54.dynamic.InlinedRequestBody.referenced(LB4(e));case"fileUpload":return ve.V54.dynamic.InlinedRequestBody.fileUpload(UB4(e));default:Ao(e)}}function LB4(e){return{...e,bodyType:_bw(e.bodyType)}}function _bw(e){switch(e.type){case"bytes":return ve.V54.dynamic.ReferencedRequestBodyType.bytes();case"typeReference":return ve.V54.dynamic.ReferencedRequestBodyType.typeReference(dze(e.value));default:Ao(e)}}function UB4(e){return{properties:e.properties.map(t=>VB4(t))}}function VB4(e){switch(e.type){case"file":return ve.V54.dynamic.FileUploadRequestBodyProperty.file(e);case"fileArray":return ve.V54.dynamic.FileUploadRequestBodyProperty.fileArray(e);case"bodyProperty":return ve.V54.dynamic.FileUploadRequestBodyProperty.bodyProperty(pHt(e));default:Ao(e)}}function WB4(e){return e.type==="container"&&e.container.type==="nullable"?ve.V54.types.TypeReference.container(ve.V54.types.ContainerType.optional(Yj(e.container.nullable))):ve.V54.types.TypeReference.container(ve.V54.types.ContainerType.optional(Yj(e)))}function HB4(e){return e.type==="container"&&e.container.type==="optional"?Yj(e):ve.V54.types.TypeReference.container(ve.V54.types.ContainerType.optional(Yj(e)))}function $B4(e){return e.type==="optional"?dze(e):ve.V54.dynamic.TypeReference.optional(dze(e))}function GB4(e){return e.type==="nullable"?ve.V54.dynamic.TypeReference.optional(dze(e.value)):ve.V54.dynamic.TypeReference.optional(dze(e))}var hbw={laterVersion:"v56",earlierVersion:"v55",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:Ne,[$.TYPESCRIPT_BROWSER_SDK]:Ne,[$.TYPESCRIPT]:Ne,[$.TYPESCRIPT_SDK]:Ne,[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:Ne,[$.JAVA_SPRING]:Ne,[$.PYTHON_FASTAPI]:Ne,[$.PYTHON_PYDANTIC]:Ne,[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.PYTHON_SDK]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:Ne,[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:"0.0.2",[$.CSHARP_SDK]:"1.12.0-rc0",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:Ne,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V55.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,services:Sd(e.services,t=>QB4(t))})};function QB4(e){return{...e,endpoints:e.endpoints.map(t=>JB4(t))}}function JB4(e){return{...e,pagination:KB4(e.pagination)}}function KB4(e){if(e!=null)switch(e.type){case"cursor":return ve.V55.http.Pagination.cursor({next:e.next,page:e.page,results:e.results});case"offset":return ve.V55.http.Pagination.offset({hasNextPage:e.hasNextPage,page:e.page,results:e.results,step:e.step});case"custom":return;default:Ao(e)}}var ybw={laterVersion:"v57",earlierVersion:"v56",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"0.49.0",[$.TYPESCRIPT_BROWSER_SDK]:"0.49.0",[$.TYPESCRIPT]:"0.49.0",[$.TYPESCRIPT_SDK]:"0.49.0",[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:"1.8.0",[$.JAVA_SDK]:"2.34.0",[$.JAVA_SPRING]:"1.6.0",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.PYTHON_FASTAPI]:"1.6.3",[$.PYTHON_PYDANTIC]:"1.4.8",[$.PYTHON_SDK]:"4.3.19",[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.GO_FIBER]:"0.23.6",[$.GO_MODEL]:"0.23.6",[$.GO_SDK]:"0.37.0",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:"1.12.0-rc11",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:ar,[$.PHP_MODEL]:ar,[$.PHP_SDK]:"0.14.1",[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V56.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,dynamic:e.dynamic!=null?YB4(e.dynamic):void 0})};function YB4(e){return{...e,endpoints:XB4(e.endpoints)}}function XB4(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ZB4(r)]).filter(([t,r])=>r!=null))}function ZB4(e){return{...e,auth:e.auth!=null?tI4(e.auth):void 0,examples:e.examples!=null?kB4(e.examples):void 0}}function kB4(e){return e.map(t=>eI4(t)).filter(t=>t!=null)}function eI4(e){return{...e,auth:e.auth!=null?rI4(e.auth):void 0}}function tI4(e){switch(e.type){case"basic":return ve.V56.dynamic.Auth.basic(e);case"bearer":return ve.V56.dynamic.Auth.bearer(e);case"header":return ve.V56.dynamic.Auth.header(e);case"oauth":return;default:Ao(e)}}function rI4(e){switch(e.type){case"basic":return ve.V56.dynamic.AuthValues.basic(e);case"bearer":return ve.V56.dynamic.AuthValues.bearer(e);case"header":return ve.V56.dynamic.AuthValues.header(e);case"oauth":return;default:Ao(e)}}var vbw={laterVersion:"v58",earlierVersion:"v57",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"1.2.0",[$.TYPESCRIPT_BROWSER_SDK]:"1.2.0",[$.TYPESCRIPT]:"1.2.0",[$.TYPESCRIPT_SDK]:"1.2.0",[$.TYPESCRIPT_EXPRESS]:"0.18.0",[$.JAVA]:Ne,[$.JAVA_MODEL]:Ne,[$.JAVA_SDK]:"2.36.5",[$.JAVA_SPRING]:"1.6.1",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.PYTHON_FASTAPI]:"1.7.0",[$.PYTHON_PYDANTIC]:"1.5.0",[$.PYTHON_SDK]:"4.21.0",[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.GO_FIBER]:Ne,[$.GO_MODEL]:Ne,[$.GO_SDK]:"1.1.0",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:"1.17.5",[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:"0.1.0",[$.PHP_MODEL]:Ne,[$.PHP_SDK]:"1.15.1",[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V57.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,services:e.services!=null?iI4(e.services):void 0,dynamic:e.dynamic!=null?uI4(e.dynamic):void 0})};function iI4(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,nI4(r)]))}function nI4(e){return{...e,endpoints:aI4(e.endpoints)}}function aI4(e){return e.map(oI4).filter(t=>t!=null)}function oI4(e){if(e.method!=="HEAD")return{...e,method:e.method}}function uI4(e){return{...e,endpoints:sI4(e.endpoints)}}function sI4(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,cI4(r)]).filter(([t,r])=>r!=null))}function cI4(e){let t=e.location.method;if(t!=="HEAD")return{...e,examples:e.examples!=null?lI4(e.examples):void 0,location:{...e.location,method:t}}}function lI4(e){return e.map(t=>fI4(t)).filter(t=>t!=null)}function fI4(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,endpoint:{...e.endpoint,method:t}}}var bbw={laterVersion:"v59",earlierVersion:"v58",firstGeneratorVersionToConsumeNewIR:{[$.TYPESCRIPT_NODE_SDK]:"2.6.8",[$.TYPESCRIPT_BROWSER_SDK]:"2.6.8",[$.TYPESCRIPT]:"2.6.8",[$.TYPESCRIPT_SDK]:"2.6.8",[$.TYPESCRIPT_EXPRESS]:Ne,[$.JAVA]:Ne,[$.JAVA_MODEL]:"1.8.1",[$.JAVA_SDK]:"2.43.0",[$.JAVA_SPRING]:"1.8.2",[$.OPENAPI_PYTHON_CLIENT]:Ne,[$.OPENAPI]:Ne,[$.PYTHON_FASTAPI]:"1.8.0",[$.PYTHON_PYDANTIC]:"1.6.0",[$.PYTHON_SDK]:"4.26.0",[$.STOPLIGHT]:Ne,[$.POSTMAN]:Ne,[$.GO_FIBER]:"0.23.7",[$.GO_MODEL]:"0.23.7",[$.GO_SDK]:"1.7.0",[$.RUBY_MODEL]:Ne,[$.RUBY_SDK]:Ne,[$.CSHARP_MODEL]:Ne,[$.CSHARP_SDK]:Ne,[$.SWIFT_MODEL]:Ne,[$.SWIFT_SDK]:"0.6.0",[$.PHP_MODEL]:Ne,[$.PHP_SDK]:Ne,[$.RUST_MODEL]:ar,[$.RUST_SDK]:ar},jsonifyEarlierVersion:e=>O_.V58.IntermediateRepresentation.jsonOrThrow(e,{unrecognizedObjectKeys:"strip",skipValidation:!0}),migrateBackwards:e=>({...e,dynamic:e.dynamic!=null?pI4(e.dynamic):void 0,auth:e.auth!=null?dI4(e.auth):void 0})};function dI4(e){return{...e,schemes:e.schemes.filter(t=>t.type!=="inferred")}}function pI4(e){return{...e,endpoints:_I4(e.endpoints)}}function _I4(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,hI4(r)]).filter(([t,r])=>r!=null))}function hI4(e){return{...e,examples:e.examples!=null?vI4(e.examples):void 0,auth:yI4(e.auth)}}function yI4(e){if(e==null)return e;if(e.type!=="inferred")return e}function vI4(e){return e.map(t=>bI4(t)).filter(t=>t!=null)}function bI4(e){return{...e,auth:gI4(e.auth)}}function gI4(e){if(e==null)return e;if(e.type!=="inferred")return e}function GOo(){return mI4}var XNs=class{migrations;constructor(t){this.migrations=t}withMigration(t){return new DOd([...this.migrations,t])}},DOd=class extends XNs{build(){return new EOd(this.migrations)}},EOd=class{migrations;constructor(t){this.migrations=t}migrateForGenerator({intermediateRepresentation:t,context:r,targetGenerator:i}){return this.migrate({intermediateRepresentation:t,shouldMigrate:n=>this.shouldRunMigration({migration:n,targetGenerator:i}),context:r,targetGenerator:i})}migrateThroughMigration({migration:t,intermediateRepresentation:r,context:i,targetGenerator:n}){return this.migrateThroughVersion({version:t.earlierVersion,intermediateRepresentation:r,context:i,targetGenerator:n})}migrateThroughVersion({version:t,intermediateRepresentation:r,context:i,targetGenerator:n}){let a=!1;if(this.migrations[0]?.laterVersion===t)return{ir:r,jsonify:()=>Promise.resolve().then(()=>Up.IntermediateRepresentation.jsonOrThrow(r,{unrecognizedObjectKeys:"strip"}))};let c=this.migrate({intermediateRepresentation:r,shouldMigrate:d=>{let s=d.earlierVersion===t;return a||=s,s||!a},context:i,targetGenerator:n});return a||i.failAndThrow(`IR ${t} does not exist`),c}migrate({intermediateRepresentation:t,shouldMigrate:r,context:i,targetGenerator:n}){let a=t,u=async()=>Up.IntermediateRepresentation.jsonOrThrow(a,{unrecognizedObjectKeys:"strip"});for(let c of this.migrations){if(!r(c))break;i.logger.debug(`Migrating IR from ${c.laterVersion} to ${c.earlierVersion}`),a=c.migrateBackwards(a,{taskContext:i,targetGenerator:n}),u=()=>Promise.resolve().then(()=>c.jsonifyEarlierVersion(a))}return{ir:a,jsonify:u}}shouldRunMigration({migration:t,targetGenerator:r}){let i=t.firstGeneratorVersionToConsumeNewIR[r.name];if(i==null)throw new Error(`Cannot migrate intermediate representation. Unrecognized generator: ${r.name}. If leveraging a custom generator, ensure you are specifying "ir-version" within the generator configuration.`);switch(i){case Ne:return!0;case ar:throw new Error(`Cannot migrate intermediate representation. Generator was created after intermediate representation ${t.laterVersion}.`)}return que(i,r.version)}getIRVersionForGenerator({targetGenerator:t}){let r=this.migrations[0]?.laterVersion;for(let i of this.migrations)if(this.shouldRunMigration({migration:i,targetGenerator:t}))r=i.earlierVersion;else break;return r}},OI4={Builder:new XNs([])},mI4=OI4.Builder.withMigration(bbw).withMigration(vbw).withMigration(ybw).withMigration(hbw).withMigration(abw).withMigration(rbw).withMigration(Gvw).withMigration(Ivw).withMigration(Evw).withMigration(mvw).withMigration(Ovw).withMigration(bvw).withMigration(vvw).withMigration(_vw).withMigration(fvw).withMigration(lvw).withMigration(svw).withMigration(uvw).withMigration(ovw).withMigration(avw).withMigration(nvw).withMigration(ivw).withMigration(rvw).withMigration(tvw).withMigration(evw).withMigration(kyw).withMigration(Zyw).withMigration(Yyw).withMigration(Jyw).withMigration(Qyw).withMigration(Gyw).withMigration(Fyw).withMigration(Nyw).withMigration(Ryw).withMigration(zyw).withMigration(Iyw).withMigration(bWO).withMigration(hWO).withMigration(_WO).withMigration(fWO).withMigration(cWO).withMigration(uWO).withMigration(oWO).withMigration(aWO).withMigration(rWO).withMigration(kVO).withMigration(ZVO).withMigration(XVO).withMigration(KVO).withMigration(JVO).withMigration(QVO).withMigration(WVO).withMigration(LVO).withMigration(FVO).withMigration(NVO).withMigration(wVO).withMigration(mVO).withMigration(R0h).build();function QOo({intermediateRepresentation:e,context:t,targetGenerator:r}){return GOo().migrateForGenerator({intermediateRepresentation:e,context:t,targetGenerator:r}).jsonify()}function MOd({intermediateRepresentation:e,context:t,targetGenerator:r,irVersion:i}){return GOo().migrateThroughVersion({version:i,intermediateRepresentation:e,context:t,targetGenerator:r}).jsonify()}function JOo({intermediateRepresentation:e,context:t,version:r}){return GOo().migrateThroughVersion({version:r,intermediateRepresentation:e,context:t}).jsonify()}async function gbw({workspace:e,audiences:t,generatorInvocation:r,context:i,irVersionOverride:n,version:a,packageName:u,sourceConfig:c,includeOptionalRequestPropertyExamples:d,ir:s}){let o=s??gx({workspace:e,audiences:t,generationLanguage:r.language,keywords:r.keywords,smartCasing:r.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:d,disabled:r.disableExamples},readme:r.readme,version:a,packageName:u,context:i,sourceResolver:new vx(i,e)});c!=null&&(o.sourceConfig=c),i.logger.debug("Generated IR");let l=n!=null?await JOo({intermediateRepresentation:o,context:i,version:n}):await QOo({intermediateRepresentation:o,context:i,targetGenerator:{name:r.name,version:r.version}});return{latest:o,migrated:l}}var Obw=ui(wbu(),1),one=require("fs/promises"),mbw=ui(Gk(),1),ZNs=class{context;absolutePathToTmpOutputDirectory;absolutePathToTmpSnippetJSON;absolutePathToTmpSnippetTemplatesJSON;absolutePathToLocalSnippetTemplateJSON;absolutePathToLocalOutput;absolutePathToLocalSnippetJSON;constructor({context:t,absolutePathToTmpOutputDirectory:r,absolutePathToTmpSnippetJSON:i,absolutePathToLocalSnippetTemplateJSON:n,absolutePathToLocalOutput:a,absolutePathToLocalSnippetJSON:u,absolutePathToTmpSnippetTemplatesJSON:c}){this.context=t,this.absolutePathToLocalOutput=a,this.absolutePathToTmpOutputDirectory=r,this.absolutePathToTmpSnippetJSON=i,this.absolutePathToLocalSnippetJSON=u,this.absolutePathToLocalSnippetTemplateJSON=n,this.absolutePathToTmpSnippetTemplatesJSON=c}async copyGeneratedFiles(){await this.isFernIgnorePresent()?await this.copyGeneratedFilesWithFernIgnore():await this.copyGeneratedFilesNoFernIgnore(),this.absolutePathToTmpSnippetJSON!=null&&this.absolutePathToLocalSnippetJSON!=null&&await Cf(this.absolutePathToTmpSnippetJSON)&&await this.copySnippetJSON({absolutePathToTmpSnippetJSON:this.absolutePathToTmpSnippetJSON,absolutePathToLocalSnippetJSON:this.absolutePathToLocalSnippetJSON}),this.absolutePathToTmpSnippetTemplatesJSON!=null&&this.absolutePathToLocalSnippetTemplateJSON!=null&&await Cf(this.absolutePathToTmpSnippetTemplatesJSON)&&await this.copySnippetJSON({absolutePathToTmpSnippetJSON:this.absolutePathToTmpSnippetTemplatesJSON,absolutePathToLocalSnippetJSON:this.absolutePathToLocalSnippetTemplateJSON})}async isFernIgnorePresent(){let t=$c.of(Bu(this.absolutePathToLocalOutput,za.of(iqo)));return await Cf(t)}async copyGeneratedFilesWithFernIgnore(){let t=$c.of((await mbw.default.dir({})).path),r=$c.of(Bu(this.absolutePathToLocalOutput,za.of(iqo))),i=await jI4({absolutePathToFernignore:r});await(0,one.cp)(this.absolutePathToLocalOutput,t,{recursive:!0}),await this.runGitCommand(["init"],t),await this.runGitCommand(["add","."],t),(await this.runGitCommand(["config","--list"],t)).includes("user.name")||(await this.runGitCommand(["config","user.name","fern-api"],t),await this.runGitCommand(["config","user.email","info@buildwithfern.com"],t)),await this.runGitCommand(["commit","--allow-empty","-m",'"init"'],t),await this.runGitCommand(["rm","-rf","."],t),await this.copyGeneratedFilesToDirectory(t),await this.runGitCommand(["reset","--",...i],t),await this.runGitCommand(["restore","."],t),await(0,one.rmdir)(Bu(t,za.of(".git")),{recursive:!0}),await(0,one.rmdir)(this.absolutePathToLocalOutput,{recursive:!0}),await(0,one.cp)(t,this.absolutePathToLocalOutput,{recursive:!0})}async copyGeneratedFilesNoFernIgnore(){this.context.logger.debug(`rm -rf ${this.absolutePathToLocalOutput}`),await(0,one.rm)(this.absolutePathToLocalOutput,{force:!0,recursive:!0}),await this.copyGeneratedFilesToDirectory(this.absolutePathToLocalOutput)}async copyGeneratedFilesToDirectory(t){let[r,...i]=await(0,one.readdir)(this.absolutePathToTmpOutputDirectory);if(r!=null)if(this.context.logger.debug(`Copying generated files to ${t}`),r.endsWith(".zip")){await(0,Obw.default)(Bu(this.absolutePathToTmpOutputDirectory,za.of(r)),t);for(let n of i)await(0,one.cp)(Bu(this.absolutePathToTmpOutputDirectory,za.of(n)),Bu(t,za.of(n)),{recursive:!0})}else await(0,one.cp)(this.absolutePathToTmpOutputDirectory,t,{recursive:!0})}async copySnippetJSON({absolutePathToTmpSnippetJSON:t,absolutePathToLocalSnippetJSON:r}){this.context.logger.debug(`Copying generated snippets to ${r}`),await(0,one.cp)(t,r)}async runGitCommand(t,r){return(await yx(this.context.logger,"git",t,{cwd:r,doNotPipeOutput:!0})).stdout}},PI4=/\r?\n/;async function jI4({absolutePathToFernignore:e}){let t=(await(0,one.readFile)(e)).toString();return[iqo,...t.trim().split(PI4).map(r=>{let i=r.indexOf("#");return i!==-1?r.slice(0,i).trim():r.trim()}).filter(r=>r.length>0)]}async function wbw({organization:e,absolutePathToFernConfig:t,workspace:r,generatorInvocation:i,absolutePathToLocalOutput:n,absolutePathToLocalSnippetJSON:a,absolutePathToLocalSnippetTemplateJSON:u,audiences:c,version:d,workspaceTempDir:s,keepDocker:o,context:l,irVersionOverride:b,outputVersionOverride:g,writeUnitTests:O,generateOauthClients:m,generatePaginatedClients:P,includeOptionalRequestPropertyExamples:D,inspect:A,executionEnvironment:M,runner:E,ir:C}){let{latest:z,migrated:G}=await gbw({workspace:r,audiences:c,generatorInvocation:i,context:l,irVersionOverride:b,packageName:$h.getPackageName({generatorInvocation:i}),version:d??g,sourceConfig:SI4(r),includeOptionalRequestPropertyExamples:D,ir:C}),I=await wI4({workspaceTempDir:s,filename:S5c,context:l,ir:G});l.logger.debug("Wrote IR to: "+I);let N=(0,mwa.join)(s.path,w5c),U=$c.of(N);await(0,YIn.writeFile)(N,""),l.logger.debug("Will write config.json to: "+U);let Y=(0,mwa.join)(s.path,j5c),J=$c.of(Y);await(0,YIn.mkdir)(Y,{recursive:!0}),l.logger.debug("Will write output to: "+J);let X;if(a!=null){let De=(0,mwa.join)(s.path,"snippet.json");X=$c.of(De),await(0,YIn.writeFile)(De,""),l.logger.debug("Will write snippet.json to: "+X)}let oe;if(u!=null){let De=(0,mwa.join)(s.path,d8d);oe=$c.of(De),await(0,YIn.writeFile)(De,""),l.logger.debug("Will write snippet-templates.json to: "+oe)}let pe=M??new FWa({dockerImage:`${i.name}:${i.version}`,keepDocker:o}),me=pe instanceof FWa?{outputDirectory:$c.of(I0u),irPath:$c.of(z0u),configPath:$c.of(NWa),snippetPath:$c.of(x0u),snippetTemplatePath:$c.of(R0u)}:{outputDirectory:J,configPath:U,irPath:I,snippetPath:X,snippetTemplatePath:oe},Le=x0h({generatorInvocation:i,customConfig:i.config,workspaceName:r.definition.rootApiFile.contents.name,outputVersion:g,organization:e,absolutePathToSnippet:X,absolutePathToSnippetTemplates:oe,absolutePathToFernConfig:t,writeUnitTests:O,generateOauthClients:m,generatePaginatedClients:P,paths:me});return await(0,YIn.writeFile)(U,JSON.stringify(await Pbw.GeneratorConfig.jsonOrThrow(Le),void 0,4)),await pe.execute({generatorName:i.name,irPath:I,configPath:U,outputPath:J,snippetPath:X,snippetTemplatePath:oe,context:l,inspect:A,runner:E}),await new ZNs({context:l,absolutePathToLocalOutput:n,absolutePathToTmpOutputDirectory:J,absolutePathToLocalSnippetJSON:a,absolutePathToLocalSnippetTemplateJSON:u,absolutePathToTmpSnippetJSON:X,absolutePathToTmpSnippetTemplatesJSON:oe}).copyGeneratedFiles(),{ir:z,generatorConfig:Le}}async function wI4({ir:e,workspaceTempDir:t,filename:r,context:i}){i.logger.debug("Migrated IR");let n;if(r)n=$c.of((0,mwa.join)(t.path,r));else{let a=await jbw.default.file({tmpdir:t.path});n=$c.of(a.path)}return await $k(n,e,{pretty:!1}),i.logger.debug(`Wrote IR to ${n}`),n}function SI4(e){return{sources:e.getSources().map(t=>t.type==="protobuf"?Ioe.proto({id:t.id,protoRootUrl:`file:///${DI4(t)}`}):Ioe.openapi())}}function DI4(e){return`${_ph}/${e.id}`}var AOd=ui(require("os"),1),Sbw=ui(require("path"),1),Dbw=ui(Gk(),1);async function Ebw({token:e,projectConfig:t,workspace:r,generatorGroup:i,version:n,keepDocker:a,inspect:u,context:c,runner:d}){let s=await MI4();(await Promise.all(i.generators.map(async l=>c.runInteractiveTask({name:l.name},async b=>{l=(z=>QCi(z,{onError:G=>b.failAndThrow(G)}))(l);let O=await r.toFernWorkspace({context:c},LKn(l)),m=gx({workspace:O,audiences:i.audiences,generationLanguage:l.language,keywords:l.keywords,smartCasing:l.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:!1,disabled:l.disableExamples},readme:l.readme,version:n,packageName:$h.getPackageName({generatorInvocation:l}),context:c,sourceResolver:new vx(c,O)}),P=QAe({token:e?.value});if(l.absolutePathToLocalOutput==null&&(e=await qUn(),e==null)){b.failWithoutThrowing("Please provide a FERN_TOKEN in your environment.");return}let D=await P.organization.get(MS.OrganizationId(t.organization));if(l.absolutePathToLocalOutput==null&&!D.ok){b.failWithoutThrowing(`Failed to load details for organization ${t.organization}.`);return}D.ok&&(D.body.selfHostedSdKs&&(m.selfHosted=!0),D.body.isWhitelabled&&(m.readmeConfig==null&&(m.readmeConfig=TI4),m.readmeConfig.whiteLabel=!0));let A=EI4(l),M=AI4({generatorInvocation:l,org:D.ok?D.body:void 0,version:n,packageName:A,context:b});M!=null&&(m.publishConfig=M);let E=l.absolutePathToLocalOutput??Bu(r.absoluteFilePath,za.of("sdks"),za.of(l.language??l.name)),C=l.raw?.snippets?.path!=null?$c.of(Bu(r.absoluteFilePath,za.of(l.raw.snippets.path))):void 0;await wbw({organization:t.organization,absolutePathToFernConfig:t._absolutePath,workspace:O,generatorInvocation:l,absolutePathToLocalOutput:E,absolutePathToLocalSnippetJSON:C,absolutePathToLocalSnippetTemplateJSON:void 0,version:n,audiences:i.audiences,workspaceTempDir:s,keepDocker:a,context:b,irVersionOverride:l.irVersionOverride,outputVersionOverride:void 0,writeUnitTests:D.ok?D?.body.snippetUnitTestsEnabled??!1:!1,generateOauthClients:D.ok?D?.body.oauthClientEnabled??!1:!1,generatePaginatedClients:D.ok?D?.body.paginationEnabled??!1:!1,includeOptionalRequestPropertyExamples:!1,inspect:u,executionEnvironment:void 0,ir:m,runner:d}),b.logger.info(Bs.green("Wrote files to "+E))})))).some(l=>!l)&&c.failAndThrow()}function EI4(e){return typeof e.raw?.config=="object"&&e.raw?.config!==null?e.raw.config.package_name:void 0}async function MI4(){return Dbw.default.dir({tmpdir:AOd.default.platform()==="darwin"?Sbw.default.join("/private",AOd.default.tmpdir()):void 0,prefix:"fern"})}function AI4({generatorInvocation:e,org:t,version:r,packageName:i,context:n}){if(e.raw?.github!=null&&qI4(e.raw.github))return Hs.PublishingConfig.github({owner:"",repo:"",uri:e.raw.github.uri,token:e.raw.github.token,target:Hs.PublishTarget.postman({apiKey:"",workspaceId:"",collectionId:void 0})});if(e.raw?.output?.location==="local-file-system"){let a;return e.language==="python"&&(a=zoe.pypi({version:r,packageName:i}),n.logger.debug(`Created PyPiPublishTarget: version ${r} package name: ${i}`)),Hs.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:a})}return e.outputMode._visit({downloadFiles:()=>Hs.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:void 0}),github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:()=>{},_other:()=>{}})}function qI4(e){return e==null?!1:"uri"in e&&"token"in e}var TI4={defaultEndpoint:void 0,bannerLink:void 0,introduction:void 0,apiReferenceLink:void 0,apiName:void 0,disabledFeatures:void 0,whiteLabel:void 0,features:void 0};var o7s=ui(Ozi(),1);var Mbw=require("fs"),kNs=require("fs/promises"),Abw=require("stream/promises");async function qbw({snippetsS3PreSignedReadUrl:e,absolutePathToLocalSnippetJSON:t,context:r}){try{await CI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(Bs.green(`Downloaded to ${t}`))}catch{r.logger.debug(Bs.yellow("Failed to download snippet.json from output."))}}async function CI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await o7.get(e,{responseType:"stream"});await Cf(t)&&await(0,kNs.rm)(t,{recursive:!0}),await(0,kNs.mkdir)(zd(t),{recursive:!0}),await(0,Abw.pipeline)(r.data,(0,Mbw.createWriteStream)(t))}var xOd=ui(NAe(),1);var Pwa=ui(Ozi(),1);var zbw=ui(Ibw(),1),OEe=require("fs/promises");var xbw=require("path"),Rbw=ui(ifu(),1),Nbw=ui(Gk(),1);async function Fbw({projectConfig:e,workspace:t,organization:r,intermediateRepresentation:i,generatorInvocation:n,version:a,context:u,shouldLogS3Url:c,token:d,whitelabel:s,irVersionOverride:o,absolutePathToPreview:l}){let b=await LI4({projectConfig:e,workspace:t,organization:r,generatorInvocation:n,version:a,context:u,shouldLogS3Url:c,token:d,whitelabel:s,absolutePathToPreview:l});return await UI4({intermediateRepresentation:i,job:b,context:u,generatorInvocation:n,irVersionOverride:o}),b}async function LI4({projectConfig:e,workspace:t,organization:r,generatorInvocation:i,version:n,context:a,shouldLogS3Url:u,token:c,whitelabel:d,absolutePathToPreview:s}){let o=lOi({token:c.value}),l={id:i.name,version:i.version,outputMode:i.outputMode,customConfig:i.config,publishMetadata:i.publishMetadata},b;if(i.outputMode.type.startsWith("github"))try{let O=await Nbw.default.dir(),m=$c.of(O.path);a.logger.debug(`Writing mock fern definition to ${m}`);let P=Bu(m,za.of(PH)),D=Bu(P,za.of(AL));await(0,OEe.mkdir)(D,{recursive:!0});let A=Bu(D,za.of(n6));await(0,OEe.writeFile)(A,xd.dump(t.definition.rootApiFile.contents)),await Lbw({absolutePathToDefinitionDirectory:D,definition:t.definition});let M=Bu(P,za.of(Uae));await(0,OEe.writeFile)(M,JSON.stringify(e.rawConfig,void 0,2));try{let z=t.getSources();for(let G of z){let I=await(0,OEe.readFile)(G.absoluteFilePath),N=(0,xbw.relative)(t.absoluteFilePath,G.absoluteFilePath),U=Bu(P,za.of(N));await(0,OEe.mkdir)(zd(U),{recursive:!0}),await(0,OEe.writeFile)(U,new Uint8Array(I))}}catch(z){a.logger.debug(`Failed to write source files to disk, continuing: ${z}`)}let E=Bu(m,za.of("definition.tgz"));await(0,Rbw.create)({file:E,cwd:P},["."]),a.logger.debug("Getting upload URL for Fern definition.");let C=await o.remoteGen.getDefinitionUploadUrl({apiName:t.definition.rootApiFile.contents.name,organizationName:r,version:n});C.ok?(a.logger.debug("Uploading definition..."),await o7.put(C.body.s3Url,await(0,OEe.readFile)(E)),b={definitionS3DownloadUrl:C.body.s3Url,outputPath:".mock",cliVersion:e.version}):C.error.content.reason==="status-code"?a.logger.debug(`Failed with status-code to get upload URL with status code ${C.error.content.statusCode}, continuing: ${C.error.content.body}`):C.error.content.reason==="non-json"?a.logger.debug(`Failed with non-json to get upload URL with status code ${C.error.content.statusCode}, continuing: ${C.error.content.rawBody}`):C.error.content.reason==="unknown"&&a.logger.debug(`Failed to get upload URL as unknown error occurred continuing: ${C.error.content.errorMessage}`)}catch(O){a.logger.debug(`Failed to upload definition to S3, continuing: ${O}`)}let g=await o.remoteGen.createJobV3({apiName:t.definition.rootApiFile.contents.name,version:n,organizationName:r,generators:[l],uploadToS3:WI4({outputMode:i.outputMode,generatorInvocation:i,absolutePathToPreview:s,shouldLogS3Url:u}),whitelabel:d,fernDefinitionMetadata:b,preview:s!=null});return g.ok?g.body:VI4(g.error)._visit({illegalApiNameError:()=>a.failAndThrow("API name is invalid: "+t.definition.rootApiFile.contents.name),illegalApiVersionError:()=>a.failAndThrow("API version is invalid: "+n),cannotPublishToNpmScope:({validScope:O,invalidScope:m})=>a.failAndThrow(`You do not have permission to publish to ${m} (expected ${O})`),cannotPublishToMavenGroup:({validGroup:O,invalidGroup:m})=>a.failAndThrow(`You do not have permission to publish to ${m} (expected ${O})`),cannotPublishPypiPackage:({validPrefix:O,invalidPackageName:m})=>a.failAndThrow(`You do not have permission to publish to ${m} (expected ${O})`),generatorsDoNotExistError:O=>a.failAndThrow("Generators do not exist: "+O.nonExistentGenerators.map(m=>`${m.id}@${m.version}`).join(", ")),insufficientPermissions:()=>a.failAndThrow("Insufficient permissions."),orgNotConfiguredForWhitelabel:()=>a.failAndThrow("Your org is not configured for white-labeling. Please reach out to support@buildwithfern.com."),_other:O=>a.failAndThrow("Failed to create job",O)})}async function Lbw({absolutePathToDefinitionDirectory:e,definition:t}){for(let[r,i]of Object.entries(t.namedDefinitionFiles)){let n=Bu(e,za.of(r));await(0,OEe.mkdir)(zd(n),{recursive:!0}),await(0,OEe.writeFile)(n,xd.dump(i.contents))}for(let[r,i]of Object.entries(t.packageMarkers))if(i.contents.export==null){let n=Bu(e,za.of(r));await(0,OEe.mkdir)(zd(n),{recursive:!0}),await(0,OEe.writeFile)(n,xd.dump(i.contents))}for(let[r,i]of Object.entries(t.importedDefinitions))await Lbw({absolutePathToDefinitionDirectory:Bu(e,za.of(r)),definition:i.definition})}async function UI4({intermediateRepresentation:e,generatorInvocation:t,job:r,context:i,irVersionOverride:n}){let a=n==null?await QOo({intermediateRepresentation:e,context:i,targetGenerator:{name:t.name,version:t.version}}):await MOd({intermediateRepresentation:e,context:i,irVersion:n,targetGenerator:{name:t.name,version:t.version}}),u=new zbw.default,c=await cJs(a,{onWrite:s=>{i.logger.debug("Wrote IR to disk: "+s)}});u.append("file",c);let d=Fb(Mnc(),`/api/remote-gen/jobs/${r.jobId}/start`);try{await o7.post(d,u,{headers:u.getHeaders(),maxBodyLength:1/0})}catch(s){let o=s instanceof XYp?s.response?.data:s;i.logger.debug(`POST ${d} failed with ${JSON.stringify(s)}`),i.failAndThrow("Failed to start job",o)}}function VI4(e){if(e?.reason==="status-code"){let t=e.body;switch(t?._error){case"IllegalApiNameError":return Pwa.FernFiddle.remoteGen.createJobV3.Error.illegalApiNameError();case"GeneratorsDoNotExistError":return Pwa.FernFiddle.remoteGen.createJobV3.Error.generatorsDoNotExistError(t.body);case"CannotPublishToNpmScope":return Pwa.FernFiddle.remoteGen.createJobV3.Error.cannotPublishToNpmScope(t.body);case"CannotPublishToMavenScope":return Pwa.FernFiddle.remoteGen.createJobV3.Error.cannotPublishToMavenGroup(t.body);case"InsufficientPermissions":return Pwa.FernFiddle.remoteGen.createJobV3.Error.insufficientPermissions(t.body)}}return e}function WI4({outputMode:e,generatorInvocation:t,absolutePathToPreview:r,shouldLogS3Url:i}){return e.type==="downloadFiles"||t.absolutePathToLocalSnippets!=null||r!=null||i}function e7s({apiName:e,organization:t,generatorInvocation:r}){let i=HI4(r);if(i!=null)return{apiName:e,organization:t,customConfig:r.config,outputConfig:i}}function HI4(e){let t=e.outputMode;switch(t.type){case"downloadFiles":return _s.GeneratorOutputConfig.local();case"publishV2":return $I4({publish:t.publishV2,version:e.version});case"githubV2":return GI4({github:t.githubV2,language:e.language,version:e.version});case"publish":case"github":return;default:Ao(t)}}function $I4({publish:e,version:t}){switch(e.type){case"npmOverride":{let r=e.npmOverride;return r==null?void 0:_s.GeneratorOutputConfig.publish(_s.PublishInfo.npm({version:t,packageName:r.packageName,repoUrl:void 0}))}case"mavenOverride":{let r=e.mavenOverride;return r==null?void 0:_s.GeneratorOutputConfig.publish(_s.PublishInfo.maven({version:t,coordinate:r.coordinate,repoUrl:void 0}))}case"pypiOverride":{let r=e.pypiOverride;return r==null?void 0:_s.GeneratorOutputConfig.publish(_s.PublishInfo.pypi({version:t,packageName:r.coordinate,repoUrl:void 0}))}case"rubyGemsOverride":{let r=e.rubyGemsOverride;return r==null?void 0:_s.GeneratorOutputConfig.publish(_s.PublishInfo.rubygems({version:t,packageName:r.packageName,repoUrl:void 0}))}case"nugetOverride":{let r=e.nugetOverride;return r==null?void 0:_s.GeneratorOutputConfig.publish(_s.PublishInfo.nuget({version:t,packageName:r.packageName,repoUrl:void 0}))}case"postman":return;default:Ao(e)}}function GI4({github:e,version:t,language:r}){let i=QI4({owner:e.owner,repo:e.repo});if(r===$h.GenerationLanguage.GO)return _s.GeneratorOutputConfig.publish(_s.PublishInfo.go({version:t,repoUrl:i}));let n=e.publishInfo;if(n!=null)switch(n.type){case"maven":return _s.GeneratorOutputConfig.publish(_s.PublishInfo.maven({version:t,coordinate:n.coordinate,repoUrl:i}));case"npm":return _s.GeneratorOutputConfig.publish(_s.PublishInfo.npm({version:t,packageName:n.packageName,repoUrl:i}));case"pypi":return _s.GeneratorOutputConfig.publish(_s.PublishInfo.pypi({version:t,packageName:n.packageName,repoUrl:i}));case"rubygems":return _s.GeneratorOutputConfig.publish(_s.PublishInfo.rubygems({version:t,packageName:n.packageName,repoUrl:i}));case"nuget":return _s.GeneratorOutputConfig.publish(_s.PublishInfo.nuget({version:t,packageName:n.packageName,repoUrl:i}));case"postman":return;default:Ao(n)}}function QI4({owner:e,repo:t}){return`https://github.com/${e}/${t}`}var Ubw=lOi();var JI4=3;function Vbw({job:e,taskId:t,taskHandler:r,context:i}){let n=0,a=async()=>{let u=await Ubw.remoteGen.getJobStatus(e.jobId);if(u.ok)return u.body[t];i.logger.debug("Failed to get job status.",JSON.stringify(u.error.content))};return new Promise((u,c)=>{d();async function d(){try{let s=await a();if(s==null)n++,n===JI4&&i.failAndThrow(`Failed to get job status after ${n} attempts.`),setTimeout(d,2e3+1e3*n);else{n=0;let o=await r.processUpdate(s);r.isFinished?u(o):setTimeout(d,2e3)}}catch(s){c(s)}}})}var Gbw=ui(wbu(),1),Qbw=require("fs"),i7s=require("fs/promises"),zOd=ui(require("path"),1),Jbw=require("stream/promises");var t7s=ui($bw(),1);function PAi(e,t,{target:r="stdout",...i}={}){return t7s.default[r]?QQn.link(e,t):i.fallback===!1?e:typeof i.fallback=="function"?i.fallback(e,t):`${e} (\u200B${t}\u200B)`}PAi.isSupported=t7s.default.stdout;PAi.stderr=(e,t,r={})=>PAi(e,t,{target:"stderr",...r});PAi.stderr.isSupported=t7s.default.stderr;var Kbw=ui(Gk(),1),r7s=class{context;generatorInvocation;absolutePathToPreview;lengthOfLastLogs=0;constructor({interactiveTaskContext:t,generatorInvocation:r,absolutePathToPreview:i}){this.context=t,this.generatorInvocation=r,this.absolutePathToPreview=i}async processUpdate(t){t==null&&this.context.failAndThrow("Task is missing on job status");let r=t.packages.map(n=>n.coordinate._visit({npm:a=>`${a.name}@${a.version}`,maven:a=>`${a.group}:${a.artifact}:${a.version}`,pypi:a=>`${a.name} ${a.version}`,ruby:a=>`${a.name}:${a.version}`,nuget:a=>`${a.name} ${a.version}`,_other:()=>"<unknown package>"}));this.absolutePathToPreview==null&&this.context.setSubtitle(r.length>0?r.map(n=>`\u25E6 ${n}`).join(`
2395
- `):void 0);for(let n of t.logs.slice(this.lengthOfLastLogs))this.context.logger.log(ZI4(n.level),n.message);this.lengthOfLastLogs=t.logs.length;let i=n=>{this.context.logger.debug(`Generated files. ${PAi("View here",n,{fallback:(a,u)=>`${a}: ${u}`})}`)};return await t.status._visit({notStarted:Ko,running:Ko,failed:({message:n,s3PreSignedReadUrl:a})=>{a!=null&&i(a),this.context.failAndThrow(n)},finished:async n=>{if(n.s3PreSignedReadUrlV2!=null){i(n.s3PreSignedReadUrlV2);let a=this.getAbsolutePathToLocalOutput();a!=null&&await YI4({s3PreSignedReadUrl:n.s3PreSignedReadUrlV2,absolutePathToLocalOutput:a,context:this.context})}if(this.absolutePathToPreview==null)for(let a of r)this.context.logger.info(`Published ${a}`);this.#e=!0,this.#t=n.createdSnippets!=null?n.createdSnippets:!1,this.#r=n.snippetsS3PreSignedReadUrl},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?Bu(this.absolutePathToPreview,za.of(zOd.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}};async function YI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{await XI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(Bs.green(`Downloaded to ${t}`))}catch(i){r.failAndThrow("Failed to download files",i)}}async function XI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await o7.get(e,{responseType:"stream"}),i=await Kbw.default.dir({prefix:"fern",unsafeCleanup:!0}),n=zOd.default.join(i.path,"output.zip");await(0,Jbw.pipeline)(r.data,(0,Qbw.createWriteStream)(n)),await Cf(t)&&await(0,i7s.rm)(t,{recursive:!0}),await(0,i7s.mkdir)(t,{recursive:!0}),await(0,Gbw.default)(n,t)}function ZI4(e){switch(e){case"DEBUG":return Sb.Debug;case"INFO":return Sb.Info;case"WARN":return Sb.Warn;case"ERROR":return Sb.Error;default:return Sb.Info}}var a7s=require("fs/promises"),Ybw=ui(Gk(),1),kI4="proto.zip",n7s=class{sourceTypes;context;sources;constructor(t,r){this.context=t,this.sources=Object.fromEntries(r.map(i=>[i.id,i])),this.sourceTypes=new Set(Object.values(this.sources).map(i=>i.type))}async uploadSources(t){for(let[r,i]of Object.entries(t)){let n=this.getSourceOrThrow(r);await this.uploadSource(n,i.uploadUrl)}return this.convertFdrSourceUploadsToSourceConfig(t)}async uploadSource(t,r){let i=await this.getUploadCommand(t),n=await(0,a7s.readFile)(i.absoluteFilePath),a=await fetch(r,{method:"PUT",body:n,headers:{"Content-Type":"application/octet-stream"}});await i.cleanup(),a.ok||this.context.failAndThrow(`Failed to upload source file: ${t.absoluteFilePath}. Status: ${a.status}, ${a.statusText}`)}async getUploadCommand(t){if(t.type==="protobuf"){let r=await this.zipSource(t.absoluteFilePath);return{absoluteFilePath:r,cleanup:async()=>{this.context.logger.debug(`Removing ${r}`),await(0,a7s.unlink)(r)}}}return{absoluteFilePath:t.absoluteFilePath,cleanup:async()=>{}}}async zipSource(t){let r=await Ybw.default.dir(),i=Bu($c.of(r.path),za.of(kI4));return this.context.logger.debug(`Zipping source ${t} into ${i}`),await yx(this.context.logger,"zip",["-r",i,"."],{cwd:t,doNotPipeOutput:!0}),i}convertFdrSourceUploadsToSourceConfig(t){let r=[];for(let[i,n]of Object.entries(t))switch(this.getSourceOrThrow(i).type){case"protobuf":r.push(Ioe.proto({id:i,protoRootUrl:n.downloadUrl}));continue;case"openapi":r.push(Ioe.openapi());continue;case"asyncapi":continue}return{sources:r}}getSourceOrThrow(t){let r=this.sources[t];return r==null&&this.context.failAndThrow(`Internal error; server responded with source id "${t}" which does not exist in the workspace.`),r}};async function Xbw({projectConfig:e,organization:t,workspace:r,interactiveTaskContext:i,generatorInvocation:n,version:a,audiences:u,shouldLogS3Url:c,token:d,whitelabel:s,irVersionOverride:o,absolutePathToPreview:l,readme:b}){let g=Nen({token:d.value}),O=$h.getPackageName({generatorInvocation:n}),m=l!=null,P=X=>QCi(X,{onError:oe=>i.failAndThrow(oe)},{substituteAsEmpty:m}),D=P(n),A=e7s({apiName:r.definition.rootApiFile.contents.name,organization:t,generatorInvocation:D}),M=gx({workspace:r,generationLanguage:n.language,keywords:n.keywords,smartCasing:n.smartCasing,exampleGeneration:{disabled:n.disableExamples,skipAutogenerationIfManualExamplesExist:!0},audiences:u,readme:b,packageName:O,version:a??await tz4({fdr:g,packageName:O,generatorInvocation:n}),context:i,sourceResolver:new vx(i,r),dynamicGeneratorConfig:A}),E=r.getSources(),C=Kee({ir:M,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},context:i}),z=await g.api.v1.register.registerApiDefinition({orgId:xOd.FernRegistry.OrgId(t),apiId:xOd.FernRegistry.ApiId(M.apiName.originalName),definition:C,sources:E.length>0?rz4(E):void 0}),G,I;z.ok&&(G=z.body.apiDefinitionId,I=z.body.sources);let N=new n7s(i,E);if(I==null&&N.sourceTypes.has("protobuf")&&(z.ok||i.failAndThrow(`Failed to register API definition: ${JSON.stringify(z.error.content)}`),i.failAndThrow("Did not successfully upload Protobuf source files.")),I!=null){i.logger.debug("Uploading source files ...");let X=await N.uploadSources(I);i.logger.debug("Setting IR source configuration ..."),M.sourceConfig=X}let U=await Fbw({projectConfig:e,workspace:r,organization:t,generatorInvocation:D,context:i,version:a,intermediateRepresentation:{...M,fdrApiDefinitionId:G,publishConfig:ez4({generatorInvocation:D})},shouldLogS3Url:c,token:d,whitelabel:s!=null?P(s):void 0,irVersionOverride:o,absolutePathToPreview:l});i.logger.debug(`Job ID: ${U.jobId}`);let Y=U.taskIds[0];if(Y==null){i.failAndThrow("Did not receive a task ID.");return}i.logger.debug(`Task ID: ${Y}`);let J=new r7s({job:U,taskId:Y,generatorInvocation:n,interactiveTaskContext:i,absolutePathToPreview:l});return await Vbw({job:U,taskHandler:J,taskId:Y,context:i})}function ez4({generatorInvocation:e}){return e.outputMode._visit({downloadFiles:()=>{},github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:t=>t._visit({mavenOverride:()=>{},pypiOverride:()=>{},nugetOverride:()=>{},npmOverride:()=>{},rubyGemsOverride:()=>{},postman:r=>{let i;return e.raw?.output?.location==="postman"&&(i=e.raw.output?.["collection-id"]),Hs.PublishingConfig.direct({target:Hs.PublishTarget.postman({apiKey:r.apiKey,workspaceId:r.workspaceId,collectionId:i})})},_other:()=>{}}),_other:()=>{}})}async function tz4({fdr:e,packageName:t,generatorInvocation:r}){if(r.language==null)return;let i;switch(r.language){case"csharp":i="Csharp";break;case"go":i="Go";break;case"java":i="Java";break;case"python":i="Python";break;case"ruby":i="Ruby";break;case"typescript":i="TypeScript";break;default:return}if(t==null)return;let n=await e.sdks.versions.computeSemanticVersion({githubRepository:r.outputMode.type==="githubV2"?`${r.outputMode.githubV2.owner}/${r.outputMode.githubV2.repo}`:void 0,language:i,package:t});if(n.ok)return n.body.version}function rz4(e){return Object.fromEntries(Object.values(e).map(t=>[t.id,{type:t.type==="protobuf"?"proto":t.type}]))}async function ROd({projectConfig:e,organization:t,workspace:r,context:i,generatorGroup:n,version:a,shouldLogS3Url:u,token:c,whitelabel:d,absolutePathToPreview:s,mode:o}){if(n.generators.length===0)return i.logger.warn("No generators specified."),null;let l=[],b=[];return l.push(...n.generators.map(O=>i.runInteractiveTask({name:O.name},async m=>{let P=LKn(O),D=await r.toFernWorkspace({context:i},P),A=await Xbw({projectConfig:e,organization:t,workspace:D,interactiveTaskContext:m,generatorInvocation:{...O,outputMode:O.outputMode._visit({downloadFiles:()=>O.outputMode,github:M=>o7s.FernFiddle.OutputMode.github({...M,makePr:o==="pull-request"}),githubV2:M=>o==="pull-request"?o7s.FernFiddle.OutputMode.githubV2(o7s.FernFiddle.GithubOutputModeV2.pullRequest(M)):O.outputMode,publish:()=>O.outputMode,publishV2:()=>O.outputMode,_other:()=>O.outputMode})},version:a,audiences:n.audiences,shouldLogS3Url:u,token:c,whitelabel:d,readme:O.readme,irVersionOverride:O.irVersionOverride,absolutePathToPreview:s});A!=null&&A.createdSnippets&&(b.push(O),O.absolutePathToLocalSnippets!=null&&A.snippetsS3PreSignedReadUrl!=null&&await qbw({snippetsS3PreSignedReadUrl:A.snippetsS3PreSignedReadUrl,absolutePathToLocalSnippetJSON:O.absolutePathToLocalSnippets,context:m}))}))),(await Promise.all(l)).some(O=>!O)&&i.failAndThrow(),{snippetsProducedBy:b}}var _Ht=ui(NAe(),1);var H0w=require("fs/promises");var nmd=ui(ben(),1);var R0w=ui(x0w(),1);var N0w=require("util"),Wx4=(0,N0w.promisify)(R0w.default);async function F0w(e,t,r){let i=LIa(e,t),n=[];for(let a of i){let u=await Promise.all(a.map(async c=>{try{let d=await Wx4(c);return d==null||d.height==null||d.width==null?void 0:{filePath:c,width:d.width,height:d.height,blurDataUrl:void 0}}catch(d){r.logger.error(`Failed to measure image size for ${c}. ${d?.message}`);return}}));n.push(...u.filter(yy))}return new Map(n.map(a=>[a.filePath,a]))}var Hx4=10,L0w=10;async function $0w({token:e,organization:t,docsWorkspace:r,domain:i,customDomains:n,apiWorkspaces:a,ossWorkspaces:u,context:c,preview:d,editThisPage:s,isPrivate:o=!1,disableTemplates:l=!1,dynamicSnippets:b=!1}){let g=Nen({token:e.value}),O=o?{type:"private",authType:"sso"}:{type:"public"},m,P=n[0]??i,D=$x4(i),M=await new uJt(i,r,u,a,c,s,async C=>{let z=new Map(C.map(J=>[J.absoluteFilePath,J])),I=C.map(J=>({...J,mediaType:nmd.lookup(J.absoluteFilePath)})).filter(J=>J.mediaType!==!1).filter(J=>Iq.parse(J.mediaType)?.isImage()??!1).map(J=>J.absoluteFilePath),N=await F0w(I,Hx4,c),U=[];[...N.values()].forEach(J=>{let X=z.get(J.filePath);if(X==null)return;let oe={filePath:_Ht.FernRegistry.docs.v1.write.FilePath(rBo(X.relativeFilePath)),width:J.width,height:J.height,blurDataUrl:J.blurDataUrl,alt:void 0};U.push(oe)});let Y=C.filter(({absoluteFilePath:J})=>!N.has(J)).map(({relativeFilePath:J})=>rBo(J));if(d){let J=await g.docs.v2.write.startDocsPreviewRegister({orgId:_Ht.FernRegistry.OrgId(t),authConfig:o?{type:"private",authType:"sso"}:{type:"public"},filepaths:Y.map(X=>_Ht.FernRegistry.docs.v1.write.FilePath(X)),images:U,basePath:D});return J.ok?(P=J.body.previewUrl,m=J.body.docsRegistrationId,await U0w(J.body.uploadUrls,r.absoluteFilePath,c,L0w),V0w(J.body.uploadUrls,r.absoluteFilePath)):await W0w(J.error,c)}else{let J=await g.docs.v2.write.startDocsRegister({domain:i,customDomains:n,authConfig:O,apiId:_Ht.FernRegistry.ApiId(""),orgId:_Ht.FernRegistry.OrgId(t),filepaths:Y.map(X=>_Ht.FernRegistry.docs.v1.write.FilePath(X)),images:U});return J.ok?(m=J.body.docsRegistrationId,await U0w(J.body.uploadUrls,r.absoluteFilePath,c,L0w),V0w(J.body.uploadUrls,r.absoluteFilePath)):W0w(J.error,c)}},async({ir:C,snippetsConfig:z,playgroundConfig:G,apiName:I,workspace:N})=>{let U=Kee({ir:C,snippetsConfig:z,playgroundConfig:G,context:c}),Y;b&&(Y=await Gx4({workspace:N,organization:t,context:c,snippetsConfig:z}));let J=await g.api.v1.register.registerApiDefinition({orgId:_Ht.FernRegistry.OrgId(t),apiId:_Ht.FernRegistry.ApiId(C.apiName.originalName),definition:{...U,snippetsConfiguration:d?void 0:U.snippetsConfiguration},definitionV2:void 0,dynamicIRs:Y});if(J.ok)return c.logger.debug(`Registered API Definition ${J.body.apiDefinitionId}`),J.body.dynamicIRs&&Y&&await Qx4({dynamicIRs:Y,dynamicIRUploadUrls:J.body.dynamicIRs,context:c,apiId:J.body.apiDefinitionId}),J.body.apiDefinitionId;switch(J.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return I!=null?c.failAndThrow(`Failed to publish docs because API definition (${I}) could not be uploaded. Please contact support@buildwithfern.com
2395
+ `):void 0);for(let n of t.logs.slice(this.lengthOfLastLogs))this.context.logger.log(ZI4(n.level),n.message);this.lengthOfLastLogs=t.logs.length;let i=n=>{this.context.logger.debug(`Generated files. ${PAi("View here",n,{fallback:(a,u)=>`${a}: ${u}`})}`)};return await t.status._visit({notStarted:Ko,running:Ko,failed:({message:n,s3PreSignedReadUrl:a})=>{a!=null&&i(a),this.context.failAndThrow(n)},finished:async n=>{if(n.s3PreSignedReadUrlV2!=null){i(n.s3PreSignedReadUrlV2);let a=this.getAbsolutePathToLocalOutput();a!=null&&await YI4({s3PreSignedReadUrl:n.s3PreSignedReadUrlV2,absolutePathToLocalOutput:a,context:this.context})}if(this.absolutePathToPreview==null)for(let a of r)this.context.logger.info(`Published ${a}`);this.#e=!0,this.#t=n.createdSnippets!=null?n.createdSnippets:!1,this.#r=n.snippetsS3PreSignedReadUrl},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?Bu(this.absolutePathToPreview,za.of(zOd.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}};async function YI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{await XI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(Bs.green(`Downloaded to ${t}`))}catch(i){r.failAndThrow("Failed to download files",i)}}async function XI4({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await o7.get(e,{responseType:"stream"}),i=await Kbw.default.dir({prefix:"fern",unsafeCleanup:!0}),n=zOd.default.join(i.path,"output.zip");await(0,Jbw.pipeline)(r.data,(0,Qbw.createWriteStream)(n)),await Cf(t)&&await(0,i7s.rm)(t,{recursive:!0}),await(0,i7s.mkdir)(t,{recursive:!0}),await(0,Gbw.default)(n,t)}function ZI4(e){switch(e){case"DEBUG":return Sb.Debug;case"INFO":return Sb.Info;case"WARN":return Sb.Warn;case"ERROR":return Sb.Error;default:return Sb.Info}}var a7s=require("fs/promises"),Ybw=ui(Gk(),1),kI4="proto.zip",n7s=class{sourceTypes;context;sources;constructor(t,r){this.context=t,this.sources=Object.fromEntries(r.map(i=>[i.id,i])),this.sourceTypes=new Set(Object.values(this.sources).map(i=>i.type))}async uploadSources(t){for(let[r,i]of Object.entries(t)){let n=this.getSourceOrThrow(r);await this.uploadSource(n,i.uploadUrl)}return this.convertFdrSourceUploadsToSourceConfig(t)}async uploadSource(t,r){let i=await this.getUploadCommand(t),n=await(0,a7s.readFile)(i.absoluteFilePath),a=await fetch(r,{method:"PUT",body:n,headers:{"Content-Type":"application/octet-stream"}});await i.cleanup(),a.ok||this.context.failAndThrow(`Failed to upload source file: ${t.absoluteFilePath}. Status: ${a.status}, ${a.statusText}`)}async getUploadCommand(t){if(t.type==="protobuf"){let r=await this.zipSource(t.absoluteFilePath);return{absoluteFilePath:r,cleanup:async()=>{this.context.logger.debug(`Removing ${r}`),await(0,a7s.unlink)(r)}}}return{absoluteFilePath:t.absoluteFilePath,cleanup:async()=>{}}}async zipSource(t){let r=await Ybw.default.dir(),i=Bu($c.of(r.path),za.of(kI4));return this.context.logger.debug(`Zipping source ${t} into ${i}`),await yx(this.context.logger,"zip",["-r",i,"."],{cwd:t,doNotPipeOutput:!0}),i}convertFdrSourceUploadsToSourceConfig(t){let r=[];for(let[i,n]of Object.entries(t))switch(this.getSourceOrThrow(i).type){case"protobuf":r.push(Ioe.proto({id:i,protoRootUrl:n.downloadUrl}));continue;case"openapi":r.push(Ioe.openapi());continue;case"asyncapi":continue}return{sources:r}}getSourceOrThrow(t){let r=this.sources[t];return r==null&&this.context.failAndThrow(`Internal error; server responded with source id "${t}" which does not exist in the workspace.`),r}};async function Xbw({projectConfig:e,organization:t,workspace:r,interactiveTaskContext:i,generatorInvocation:n,version:a,audiences:u,shouldLogS3Url:c,token:d,whitelabel:s,irVersionOverride:o,absolutePathToPreview:l,readme:b}){let g=Nen({token:d.value}),O=$h.getPackageName({generatorInvocation:n}),m=l!=null,P=X=>QCi(X,{onError:oe=>i.failAndThrow(oe)},{substituteAsEmpty:m}),D=P(n),A=e7s({apiName:r.definition.rootApiFile.contents.name,organization:t,generatorInvocation:D}),M=gx({workspace:r,generationLanguage:n.language,keywords:n.keywords,smartCasing:n.smartCasing,exampleGeneration:{disabled:n.disableExamples,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!1},audiences:u,readme:b,packageName:O,version:a??await tz4({fdr:g,packageName:O,generatorInvocation:n}),context:i,sourceResolver:new vx(i,r),dynamicGeneratorConfig:A}),E=r.getSources(),C=Kee({ir:M,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},context:i}),z=await g.api.v1.register.registerApiDefinition({orgId:xOd.FernRegistry.OrgId(t),apiId:xOd.FernRegistry.ApiId(M.apiName.originalName),definition:C,sources:E.length>0?rz4(E):void 0}),G,I;z.ok&&(G=z.body.apiDefinitionId,I=z.body.sources);let N=new n7s(i,E);if(I==null&&N.sourceTypes.has("protobuf")&&(z.ok||i.failAndThrow(`Failed to register API definition: ${JSON.stringify(z.error.content)}`),i.failAndThrow("Did not successfully upload Protobuf source files.")),I!=null){i.logger.debug("Uploading source files ...");let X=await N.uploadSources(I);i.logger.debug("Setting IR source configuration ..."),M.sourceConfig=X}let U=await Fbw({projectConfig:e,workspace:r,organization:t,generatorInvocation:D,context:i,version:a,intermediateRepresentation:{...M,fdrApiDefinitionId:G,publishConfig:ez4({generatorInvocation:D})},shouldLogS3Url:c,token:d,whitelabel:s!=null?P(s):void 0,irVersionOverride:o,absolutePathToPreview:l});i.logger.debug(`Job ID: ${U.jobId}`);let Y=U.taskIds[0];if(Y==null){i.failAndThrow("Did not receive a task ID.");return}i.logger.debug(`Task ID: ${Y}`);let J=new r7s({job:U,taskId:Y,generatorInvocation:n,interactiveTaskContext:i,absolutePathToPreview:l});return await Vbw({job:U,taskHandler:J,taskId:Y,context:i})}function ez4({generatorInvocation:e}){return e.outputMode._visit({downloadFiles:()=>{},github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:t=>t._visit({mavenOverride:()=>{},pypiOverride:()=>{},nugetOverride:()=>{},npmOverride:()=>{},rubyGemsOverride:()=>{},postman:r=>{let i;return e.raw?.output?.location==="postman"&&(i=e.raw.output?.["collection-id"]),Hs.PublishingConfig.direct({target:Hs.PublishTarget.postman({apiKey:r.apiKey,workspaceId:r.workspaceId,collectionId:i})})},_other:()=>{}}),_other:()=>{}})}async function tz4({fdr:e,packageName:t,generatorInvocation:r}){if(r.language==null)return;let i;switch(r.language){case"csharp":i="Csharp";break;case"go":i="Go";break;case"java":i="Java";break;case"python":i="Python";break;case"ruby":i="Ruby";break;case"typescript":i="TypeScript";break;default:return}if(t==null)return;let n=await e.sdks.versions.computeSemanticVersion({githubRepository:r.outputMode.type==="githubV2"?`${r.outputMode.githubV2.owner}/${r.outputMode.githubV2.repo}`:void 0,language:i,package:t});if(n.ok)return n.body.version}function rz4(e){return Object.fromEntries(Object.values(e).map(t=>[t.id,{type:t.type==="protobuf"?"proto":t.type}]))}async function ROd({projectConfig:e,organization:t,workspace:r,context:i,generatorGroup:n,version:a,shouldLogS3Url:u,token:c,whitelabel:d,absolutePathToPreview:s,mode:o}){if(n.generators.length===0)return i.logger.warn("No generators specified."),null;let l=[],b=[];return l.push(...n.generators.map(O=>i.runInteractiveTask({name:O.name},async m=>{let P=LKn(O),D=await r.toFernWorkspace({context:i},P),A=await Xbw({projectConfig:e,organization:t,workspace:D,interactiveTaskContext:m,generatorInvocation:{...O,outputMode:O.outputMode._visit({downloadFiles:()=>O.outputMode,github:M=>o7s.FernFiddle.OutputMode.github({...M,makePr:o==="pull-request"}),githubV2:M=>o==="pull-request"?o7s.FernFiddle.OutputMode.githubV2(o7s.FernFiddle.GithubOutputModeV2.pullRequest(M)):O.outputMode,publish:()=>O.outputMode,publishV2:()=>O.outputMode,_other:()=>O.outputMode})},version:a,audiences:n.audiences,shouldLogS3Url:u,token:c,whitelabel:d,readme:O.readme,irVersionOverride:O.irVersionOverride,absolutePathToPreview:s});A!=null&&A.createdSnippets&&(b.push(O),O.absolutePathToLocalSnippets!=null&&A.snippetsS3PreSignedReadUrl!=null&&await qbw({snippetsS3PreSignedReadUrl:A.snippetsS3PreSignedReadUrl,absolutePathToLocalSnippetJSON:O.absolutePathToLocalSnippets,context:m}))}))),(await Promise.all(l)).some(O=>!O)&&i.failAndThrow(),{snippetsProducedBy:b}}var _Ht=ui(NAe(),1);var H0w=require("fs/promises");var nmd=ui(ben(),1);var R0w=ui(x0w(),1);var N0w=require("util"),Wx4=(0,N0w.promisify)(R0w.default);async function F0w(e,t,r){let i=LIa(e,t),n=[];for(let a of i){let u=await Promise.all(a.map(async c=>{try{let d=await Wx4(c);return d==null||d.height==null||d.width==null?void 0:{filePath:c,width:d.width,height:d.height,blurDataUrl:void 0}}catch(d){r.logger.error(`Failed to measure image size for ${c}. ${d?.message}`);return}}));n.push(...u.filter(yy))}return new Map(n.map(a=>[a.filePath,a]))}var Hx4=10,L0w=10;async function $0w({token:e,organization:t,docsWorkspace:r,domain:i,customDomains:n,apiWorkspaces:a,ossWorkspaces:u,context:c,preview:d,editThisPage:s,isPrivate:o=!1,disableTemplates:l=!1,dynamicSnippets:b=!1}){let g=Nen({token:e.value}),O=o?{type:"private",authType:"sso"}:{type:"public"},m,P=n[0]??i,D=$x4(i),M=await new uJt(i,r,u,a,c,s,async C=>{let z=new Map(C.map(J=>[J.absoluteFilePath,J])),I=C.map(J=>({...J,mediaType:nmd.lookup(J.absoluteFilePath)})).filter(J=>J.mediaType!==!1).filter(J=>Iq.parse(J.mediaType)?.isImage()??!1).map(J=>J.absoluteFilePath),N=await F0w(I,Hx4,c),U=[];[...N.values()].forEach(J=>{let X=z.get(J.filePath);if(X==null)return;let oe={filePath:_Ht.FernRegistry.docs.v1.write.FilePath(rBo(X.relativeFilePath)),width:J.width,height:J.height,blurDataUrl:J.blurDataUrl,alt:void 0};U.push(oe)});let Y=C.filter(({absoluteFilePath:J})=>!N.has(J)).map(({relativeFilePath:J})=>rBo(J));if(d){let J=await g.docs.v2.write.startDocsPreviewRegister({orgId:_Ht.FernRegistry.OrgId(t),authConfig:o?{type:"private",authType:"sso"}:{type:"public"},filepaths:Y.map(X=>_Ht.FernRegistry.docs.v1.write.FilePath(X)),images:U,basePath:D});return J.ok?(P=J.body.previewUrl,m=J.body.docsRegistrationId,await U0w(J.body.uploadUrls,r.absoluteFilePath,c,L0w),V0w(J.body.uploadUrls,r.absoluteFilePath)):await W0w(J.error,c)}else{let J=await g.docs.v2.write.startDocsRegister({domain:i,customDomains:n,authConfig:O,apiId:_Ht.FernRegistry.ApiId(""),orgId:_Ht.FernRegistry.OrgId(t),filepaths:Y.map(X=>_Ht.FernRegistry.docs.v1.write.FilePath(X)),images:U});return J.ok?(m=J.body.docsRegistrationId,await U0w(J.body.uploadUrls,r.absoluteFilePath,c,L0w),V0w(J.body.uploadUrls,r.absoluteFilePath)):W0w(J.error,c)}},async({ir:C,snippetsConfig:z,playgroundConfig:G,apiName:I,workspace:N})=>{let U=Kee({ir:C,snippetsConfig:z,playgroundConfig:G,context:c}),Y;b&&(Y=await Gx4({workspace:N,organization:t,context:c,snippetsConfig:z}));let J=await g.api.v1.register.registerApiDefinition({orgId:_Ht.FernRegistry.OrgId(t),apiId:_Ht.FernRegistry.ApiId(C.apiName.originalName),definition:{...U,snippetsConfiguration:d?void 0:U.snippetsConfiguration},definitionV2:void 0,dynamicIRs:Y});if(J.ok)return c.logger.debug(`Registered API Definition ${J.body.apiDefinitionId}`),J.body.dynamicIRs&&Y&&await Qx4({dynamicIRs:Y,dynamicIRUploadUrls:J.body.dynamicIRs,context:c,apiId:J.body.apiDefinitionId}),J.body.apiDefinitionId;switch(J.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return I!=null?c.failAndThrow(`Failed to publish docs because API definition (${I}) could not be uploaded. Please contact support@buildwithfern.com
2396
2396
  ${JSON.stringify(J.error)}`):c.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
2397
2397
  ${JSON.stringify(J.error)}`)}},async({api:C,snippetsConfig:z,apiName:G})=>{C.snippetsConfiguration=z;let I=await g.api.v1.register.registerApiDefinition({orgId:_Ht.FernRegistry.OrgId(t),apiId:_Ht.FernRegistry.ApiId(G??C.id),definition:void 0,definitionV2:{...C,snippetsConfiguration:d?void 0:C.snippetsConfiguration}});if(I.ok)return c.logger.debug(`Registered API Definition ${I.body.apiDefinitionId}`),I.body.apiDefinitionId;switch(I.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return G!=null?c.failAndThrow(`Failed to publish docs because API definition (${G}) could not be uploaded. Please contact support@buildwithfern.com
2398
2398
  ${JSON.stringify(I.error)}`):c.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
2399
- ${JSON.stringify(I.error)}`)}}).resolve();if(m==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.debug("Publishing docs...");let E=await g.docs.v2.write.finishDocsRegister(_Ht.FernRegistry.docs.v1.write.DocsRegistrationId(m),{docsDefinition:M});if(E.ok){let C=Yee(P),z=PAi(C,C);c.logger.info(Bs.green(`Published docs to ${z}`))}else switch(E.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${m} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+i,E.error)}}async function U0w(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=LIa(Object.entries(e),i),c=0;for(let s of u){await Promise.all(s.map(async([l,{uploadUrl:b}])=>{let g=za.of(l),O=$v(t,g);try{let m=nmd.lookup(O);await o7.put(b,await(0,H0w.readFile)(O),{headers:{"Content-Type":m===!1?"application/octet-stream":m}})}catch(m){r.failAndThrow(`Failed to upload ${O}`,m)}}));let o=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${o-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function V0w(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=za.of(i),u=$v(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function W0w(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function $x4(e){try{return new URL(Yee(e)).pathname}catch{return}}async function Gx4({workspace:e,organization:t,context:r,snippetsConfig:i}){let n={};if(!e)return;let a={typescript:i.typescriptSdk?.package,python:i.pythonSdk?.package,java:i.javaSdk?.coordinate,go:i.goSdk?.githubRepo,csharp:i.csharpSdk?.package,ruby:i.rubySdk?.gem,php:void 0,swift:void 0,rust:void 0};if(e.generatorsConfiguration?.groups)for(let u of e.generatorsConfiguration.groups)for(let c of u.generators){let d=$h.getPackageName({generatorInvocation:c});if(d&&c.language&&a[c.language]===d){let s=gx({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:d,version:void 0,context:r,sourceResolver:new vx(r,e)}),o=await aVa({ir:s,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:e7s({apiName:e.workspaceName??"",organization:t,generatorInvocation:c})});o?n[c.language]={dynamicIR:o}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}if(Object.keys(n).length>0)return n}async function Qx4({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:i}){if(Object.keys(t).length>0)for(let[n,a]of Object.entries(t)){let u=e[n]?.dynamicIR;u?(await fetch(a.uploadUrl,{method:"PUT",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream","Content-Length":JSON.stringify(u).length.toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${i}:${n}`):r.logger.warn(`Failed to upload dynamic IR for ${i}:${n}`):r.logger.warn(`Could not find matching dynamic IR to upload for ${i}:${n}`)}}async function amd({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:c,disableTemplates:d,dynamicSnippets:s}){let o=i.config.instances;if(i.config=QCi(i.config,{onError:g=>n.failAndThrow(g)},{substituteAsEmpty:c}),o.length===0){n.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(o.length>1&&u==null){n.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${o[0]?.url})`);return}let l=o.find(g=>g.url===u)??o[0];if(l==null){n.failAndThrow(`No docs instance with url ${u}. Failed to register.`);return}let b=[];l.customDomain!=null&&(typeof l.customDomain=="string"?b.push(l.customDomain):Array.isArray(l.customDomain)&&b.push(...l.customDomain)),await n.runInteractiveTask({name:l.url},async()=>{await $0w({docsWorkspace:i,customDomains:b,domain:l.url,token:a,organization:e,context:n,apiWorkspaces:t,ossWorkspaces:r,preview:c,editThisPage:l.editThisPage,isPrivate:l.private,disableTemplates:d,dynamicSnippets:s})})}var Ggw=ui(Ozi(),1);var BW={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function ZC(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function hHt({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith("$")&&t.exampleTypeReference?.(e,r);else if(Tw(e))for(let i of Object.values(e))hHt({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)hHt({example:i,visitor:t,nodePath:r})}function nkt(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function G0w({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),b1(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":Ko,"display-name":Ko,availability:Ko,headers:i=>{Q0w({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:Ko,auth:Ko,"path-parameters":i=>{XOo({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];Jx4({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:Ko,transport:Ko,source:Ko})}function Jx4({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=nkt(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),b1(t,{docs:ZC(i,n),"display-name":Ko,availability:Ko,"base-path":Ko,path:Ko,idempotent:Ko,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{XOo({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let c=[...n,"request"];if(typeof u=="string"){a(u,c,{location:"requestReference"});return}b1(u,{name:Ko,docs:ZC(i,c),"path-parameters":d=>{XOo({pathParameters:d,visitor:i,nodePath:[...c,"path-parameters"]})},"query-parameters":d=>{if(d!=null)for(let[s,o]of Object.entries(d)){let l=[...c,"query-parameters",s];i.queryParameter?.({queryParameterKey:s,queryParameter:o},l),typeof o=="string"?a(o,l):b1(o,{name:Ko,docs:ZC(i,l),availability:Ko,type:b=>{a(b,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":Ko,audiences:Ko,encoding:Ko,default:Ko,validation:Ko})}},"content-type":Ko,headers:d=>{Q0w({headers:d,visitor:i,nodePath:[...c,"headers"]})},body:d=>{if(d==null)return;let s=[...c,"body"];typeof d=="string"?a(d,s,{location:"requestReference"}):kB(d)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},s),b1(d,{extends:o=>{if(o==null)return;let l=typeof o=="string"?[o]:o;for(let b of l){let g=[...s,"extends",b];i.extension?.(b,g),a(b,g)}},properties:o=>{if(o!=null)for(let[l,b]of Object.entries(o)){let g=[...s,"properties",l];typeof b=="string"?a(b,g,{location:BW.InlinedRequestProperty}):b1(b,{name:Ko,docs:ZC(i,g),availability:Ko,type:O=>{a(O,[...g,"type"],{location:BW.InlinedRequestProperty,_default:b.default,validation:b.validation})},style:Ko,"content-type":Ko,audiences:Ko,encoding:Ko,default:Ko,validation:Ko})}},"extra-properties":Ko})):(ZC(i,s)(d.docs),a(d.type,s))}})},audiences:Ko,method:Ko,auth:Ko,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:BW.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:BW.StreamingResponse}))},response:u=>{if(u==null)return;let c=[...n,"response"];typeof u=="string"?a(u,c,{location:BW.Response}):b1(u,{docs:ZC(i,c),type:d=>{d!=null&&a(d,[...c,"type"],{location:BW.Response})},property:Ko,"status-code":Ko})},errors:u=>{if(u!=null)for(let c of u){let d=[...n,"errors",typeof c=="string"?c:c.error];typeof c=="string"?i.errorReference?.(c,d):b1(c,{docs:ZC(i,d),error:s=>{i.errorReference?.(s,[...d,"error"])}})}},examples:u=>{if(u!=null)for(let[c,d]of u.entries())Kx4({nodePathForExample:[...n,{key:"examples",arrayIndex:c}],visitor:i,service:r,endpoint:t,example:d})},pagination:Ko,source:Ko,transport:Ko})}function Kx4({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))hHt({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))hHt({example:o,visitor:t,nodePath:u});let c=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},c),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))hHt({example:o,visitor:t,nodePath:c});let d=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},d),n.request!=null&&hHt({example:n.request,visitor:t,nodePath:d});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},s),n.response!=null&&pen(i,n.response,{body:o=>{o.body!=null&&hHt({example:o.body,visitor:t,nodePath:s}),o.error!=null&&t.errorReference?.(o.error,[...s,"error"])},stream:o=>{for(let l of o.stream)hHt({example:l,visitor:t,nodePath:s})},events:o=>{for(let{data:l}of o.stream)hHt({example:l,visitor:t,nodePath:s})}}),n["code-samples"]!=null)for(let[o,l]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:l},[...e,{key:"code-samples",arrayIndex:o}])}function XOo({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),xLn(a)?typeof a=="string"?t.variableReference?.(a,u):b1(a,{docs:ZC(t,u),variable:c=>t.variableReference?.(c,[...u,"variable"]),availability:Ko}):typeof a=="string"?i(a,u):b1(a,{docs:ZC(t,u),type:c=>{i(c,[...u,"type"],{_default:a.default,validation:a.validation})},availability:Ko,encoding:Ko,default:Ko,validation:Ko,name:Ko,audiences:Ko})}}function Q0w({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):b1(a,{name:Ko,availability:Ko,type:c=>{i(c,u,{_default:a.default,validation:a.validation})},docs:ZC(t,u),audiences:Ko,encoding:Ko,env:Ko,default:Ko,validation:Ko})}}function J0w({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),omd({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function omd({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=nkt(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[c,d]of u.entries()){let s=[...i,{key:"examples",arrayIndex:c}];r.exampleType?.({typeName:e,typeDeclaration:t,example:d},s),hHt({example:d.value,nodePath:s,visitor:r})}};g6(t,{alias:u=>{typeof u=="string"?n(u,i):b1(u,{type:c=>{n(c,[...i,"type"])},docs:ZC(r,i),availability:Ko,audiences:Ko,examples:a,validation:Ko,encoding:Ko,source:Ko,inline:Ko})},object:u=>{b1(u,{docs:ZC(r,i),extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let o=[...i,"properties",d];typeof s=="string"?n(s,o):b1(s,{name:Ko,docs:ZC(r,o),availability:Ko,type:l=>{n(l,[...o,"type"],{_default:s.default,validation:s.validation})},audiences:Ko,encoding:Ko,default:Ko,validation:Ko,access:Ko})}},"extra-properties":Ko,availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},discriminatedUnion:u=>{b1(u,{docs:ZC(r,i),discriminant:Ko,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},union:c=>{for(let[d,s]of Object.entries(c)){let o=[...i,"union",d];typeof s=="string"?n(s,o):b1(s,{docs:ZC(r,o),name:Ko,key:Ko,type:l=>{typeof l=="string"&&n(l,[...i,"type"])},"display-name":Ko,availability:Ko})}},"base-properties":Ko,availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},undiscriminatedUnion:u=>{b1(u,{docs:ZC(r,i),discriminated:Ko,union:c=>{for(let[d,s]of c.entries()){let o=[...i,`union[${d}]`];typeof s!="string"&&b1(s,{docs:ZC(r,o),type:l=>{n(l,[...i,"type"])},"display-name":Ko,validation:Ko})}},availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},enum:u=>{b1(u,{docs:ZC(r,i),enum:c=>{for(let d of c){let s=[...i,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&b1(d,{docs:ZC(r,s),name:Ko,value:Ko,casing:Ko})}},availability:Ko,audiences:Ko,default:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})}})}function K0w({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),Yx4({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function Yx4({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=nkt(r);typeof t=="string"?n(t,i):b1(t,{docs:ZC(r,i),"status-code":Ko,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):omd({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let c=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},c)}}})}function Y0w({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function X0w({webhook:e,visitor:t,nodePathForWebhook:r}){let i=nkt(t);b1(e,{"display-name":Ko,method:Ko,examples:Ko,headers:n=>{Xx4({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(Zx4(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),b1(n,{name:Ko,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...u,"extends",s];t.extension?.(s,o),i(s,o)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let o=[...u,"properties",d];typeof s=="string"?i(s,o,{location:BW.InlinedRequestProperty}):b1(s,{name:Ko,docs:ZC(t,o),availability:Ko,type:l=>{i(l,[...o,"type"],{_default:s.default,validation:s.validation,location:BW.InlinedRequestProperty})},audiences:Ko,encoding:Ko,default:Ko,validation:Ko,access:Ko})}}})},audiences:Ko,availability:Ko,docs:ZC(t,r)})}function Xx4({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):b1(a,{name:Ko,availability:Ko,type:c=>{i(c,u,{_default:a.default,validation:a.validation})},docs:ZC(t,u),audiences:Ko,encoding:Ko,env:Ko,default:Ko,validation:Ko})}}function Zx4(e){return e.type!=null}function KQ(e,t){b1(e,{docs:ZC(t,[]),imports:r=>{Y0w({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{J0w({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&G0w({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))X0w({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:Ko,errors:r=>{K0w({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function umd(e,t){b1(e,{docs:Ko,imports:Ko,types:Ko,service:Ko,webhooks:Ko,errors:Ko,channel:Ko,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function smd(e,t){t.file?.(e,[]),b1(e,{version:Ko,product:Ko,name:Ko,"default-url":Ko,"display-name":Ko,imports:Ko,auth:Ko,"idempotency-headers":Ko,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{ntc(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:Ko,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Ko,headers:Ko,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Ko,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":Ko,"path-parameters":r=>{XOo({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var R7s=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function Z0w({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.definitionFile?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function k0w({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.packageMarker?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function egw({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.rootApiFile?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var cmd={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(den(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&kB(e.request.body)){let r=[];for(let[i,n]of Object.entries(e.request.body.properties??{}))typeof n!="string"&&n["content-type"]!=null&&r.push({severity:"fatal",message:`${i} has content-type, but the request is not multipart`});return r}return[]}}})};var QD=Aee({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var lmd={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new BS(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!kx4(r.request.body))return[];let a=[];for(let[u,c]of Object.entries(r.request.body.properties??{})){if(typeof c=="string"||c.style!=="exploded")continue;let d=og({relativeFilepath:i,definitionFile:n,casingsGenerator:QD,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:c.type,file:d});if(s==null)return[];tgw(s)||a.push({message:`${u} is exploded and must be a list. Did you mean list<${c.type}>?`,severity:"error"})}return a}}}}};function tgw(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?tgw(e.container.itemType):!1}function kx4(e){return e?.properties!=null}var fmd={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(Kmi(e.definition)),r=new Set;return t.forEach(i=>{let n=Bu(e.definition.absoluteFilePath,za.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],c=Bu(e.definition.absoluteFilePath,zd(a),za.of(n));return r.has(c)||u.push({severity:"fatal",message:`Import ${Bs.bold(i)} points to non-existent path ${Bs.bold(n)}.`}),u}}}}};function N7s(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(zLn(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var dmd={name:"matching-environment-urls",create:({workspace:e})=>{let t=N7s(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"fatal",message:`Environment ${r} is missing URL for ${Bs.bold(u)}`})};return sir(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let c of t)u.urls[c]==null&&a(c)}}),n}}}}};var pmd={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=eR4(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=e7i({referencedIn:i,importPath:za.of(r)});return n.filter(({chainWithoutStartingFilepath:c})=>c.length===0||c[0]===a).map(c=>({severity:"fatal",message:c.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[c.startingFilepath,...c.chainWithoutStartingFilepath,c.startingFilepath].join(" -> ")}`}))}}}}};function eR4(e){let t={};for(let r of M$t(e))t[r]=rgw(r,[r],e);return t}function rgw(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=e7i({referencedIn:e,importPath:za.of(a)});t.includes(u)?t[0]===u&&t[0]===tR4(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...rgw(u,[...t,u],r))}return i}function tR4(e){return e.reduce((t,r)=>r<t?r:t)}var F7s=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new BS(t)}isTypeComplex(t,r){let i=og({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:QD,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:Ao(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:Ao(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),kIi(t.declaration))return!0;if(hGt(t.declaration))return!1;if(wD(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(RLn(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Ao(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return rJt({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:Ao(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:Ao(t)}}};var _md={name:"no-complex-query-params",create:({workspace:e})=>{let t=new F7s(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"fatal",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var hmd={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===Ahu?[{severity:"fatal",message:`Path parameter ${Bs.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function ZOo({service:e,endpoint:t}){return e["base-path"]+t.path}var L7s=class{root=new ymd;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 ZOo({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},ymd=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var vmd={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new L7s;return V6(e,(r,i)=>{KQ(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${ZOo({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(c=>` - ${c.relativeFilepath} -> ${c.endpointId} ${Bs.dim(ZOo({service:c.service,endpoint:c.endpoint}))}`)].join(`
2399
+ ${JSON.stringify(I.error)}`)}}).resolve();if(m==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.debug("Publishing docs...");let E=await g.docs.v2.write.finishDocsRegister(_Ht.FernRegistry.docs.v1.write.DocsRegistrationId(m),{docsDefinition:M});if(E.ok){let C=Yee(P),z=PAi(C,C);c.logger.info(Bs.green(`Published docs to ${z}`))}else switch(E.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${m} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+i,E.error)}}async function U0w(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=LIa(Object.entries(e),i),c=0;for(let s of u){await Promise.all(s.map(async([l,{uploadUrl:b}])=>{let g=za.of(l),O=$v(t,g);try{let m=nmd.lookup(O);await o7.put(b,await(0,H0w.readFile)(O),{headers:{"Content-Type":m===!1?"application/octet-stream":m}})}catch(m){r.failAndThrow(`Failed to upload ${O}`,m)}}));let o=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${o-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function V0w(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=za.of(i),u=$v(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function W0w(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function $x4(e){try{return new URL(Yee(e)).pathname}catch{return}}async function Gx4({workspace:e,organization:t,context:r,snippetsConfig:i}){let n={};if(!e)return;let a={typescript:i.typescriptSdk?.package,python:i.pythonSdk?.package,java:i.javaSdk?.coordinate,go:i.goSdk?.githubRepo,csharp:i.csharpSdk?.package,ruby:i.rubySdk?.gem,php:void 0,swift:void 0,rust:void 0};if(e.generatorsConfiguration?.groups)for(let u of e.generatorsConfiguration.groups)for(let c of u.generators){let d=$h.getPackageName({generatorInvocation:c});if(d&&c.language&&a[c.language]===d){let s=gx({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:d,version:void 0,context:r,sourceResolver:new vx(r,e)}),o=await aVa({ir:s,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:e7s({apiName:e.workspaceName??"",organization:t,generatorInvocation:c})});o?n[c.language]={dynamicIR:o}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}if(Object.keys(n).length>0)return n}async function Qx4({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:i}){if(Object.keys(t).length>0)for(let[n,a]of Object.entries(t)){let u=e[n]?.dynamicIR;u?(await fetch(a.uploadUrl,{method:"PUT",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream","Content-Length":JSON.stringify(u).length.toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${i}:${n}`):r.logger.warn(`Failed to upload dynamic IR for ${i}:${n}`):r.logger.warn(`Could not find matching dynamic IR to upload for ${i}:${n}`)}}async function amd({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:c,disableTemplates:d,dynamicSnippets:s}){let o=i.config.instances;if(i.config=QCi(i.config,{onError:g=>n.failAndThrow(g)},{substituteAsEmpty:c}),o.length===0){n.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(o.length>1&&u==null){n.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${o[0]?.url})`);return}let l=o.find(g=>g.url===u)??o[0];if(l==null){n.failAndThrow(`No docs instance with url ${u}. Failed to register.`);return}let b=[];l.customDomain!=null&&(typeof l.customDomain=="string"?b.push(l.customDomain):Array.isArray(l.customDomain)&&b.push(...l.customDomain)),await n.runInteractiveTask({name:l.url},async()=>{await $0w({docsWorkspace:i,customDomains:b,domain:l.url,token:a,organization:e,context:n,apiWorkspaces:t,ossWorkspaces:r,preview:c,editThisPage:l.editThisPage,isPrivate:l.private,disableTemplates:d,dynamicSnippets:s})})}var Ggw=ui(Ozi(),1);var BW={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function ZC(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function hHt({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith("$")&&t.exampleTypeReference?.(e,r);else if(Tw(e))for(let i of Object.values(e))hHt({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)hHt({example:i,visitor:t,nodePath:r})}function nkt(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function G0w({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),b1(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":Ko,"display-name":Ko,availability:Ko,headers:i=>{Q0w({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:Ko,auth:Ko,"path-parameters":i=>{XOo({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];Jx4({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:Ko,transport:Ko,source:Ko})}function Jx4({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=nkt(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),b1(t,{docs:ZC(i,n),"display-name":Ko,availability:Ko,"base-path":Ko,path:Ko,idempotent:Ko,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{XOo({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let c=[...n,"request"];if(typeof u=="string"){a(u,c,{location:"requestReference"});return}b1(u,{name:Ko,docs:ZC(i,c),"path-parameters":d=>{XOo({pathParameters:d,visitor:i,nodePath:[...c,"path-parameters"]})},"query-parameters":d=>{if(d!=null)for(let[s,o]of Object.entries(d)){let l=[...c,"query-parameters",s];i.queryParameter?.({queryParameterKey:s,queryParameter:o},l),typeof o=="string"?a(o,l):b1(o,{name:Ko,docs:ZC(i,l),availability:Ko,type:b=>{a(b,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":Ko,audiences:Ko,encoding:Ko,default:Ko,validation:Ko})}},"content-type":Ko,headers:d=>{Q0w({headers:d,visitor:i,nodePath:[...c,"headers"]})},body:d=>{if(d==null)return;let s=[...c,"body"];typeof d=="string"?a(d,s,{location:"requestReference"}):kB(d)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},s),b1(d,{extends:o=>{if(o==null)return;let l=typeof o=="string"?[o]:o;for(let b of l){let g=[...s,"extends",b];i.extension?.(b,g),a(b,g)}},properties:o=>{if(o!=null)for(let[l,b]of Object.entries(o)){let g=[...s,"properties",l];typeof b=="string"?a(b,g,{location:BW.InlinedRequestProperty}):b1(b,{name:Ko,docs:ZC(i,g),availability:Ko,type:O=>{a(O,[...g,"type"],{location:BW.InlinedRequestProperty,_default:b.default,validation:b.validation})},style:Ko,"content-type":Ko,audiences:Ko,encoding:Ko,default:Ko,validation:Ko})}},"extra-properties":Ko})):(ZC(i,s)(d.docs),a(d.type,s))}})},audiences:Ko,method:Ko,auth:Ko,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:BW.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:BW.StreamingResponse}))},response:u=>{if(u==null)return;let c=[...n,"response"];typeof u=="string"?a(u,c,{location:BW.Response}):b1(u,{docs:ZC(i,c),type:d=>{d!=null&&a(d,[...c,"type"],{location:BW.Response})},property:Ko,"status-code":Ko})},errors:u=>{if(u!=null)for(let c of u){let d=[...n,"errors",typeof c=="string"?c:c.error];typeof c=="string"?i.errorReference?.(c,d):b1(c,{docs:ZC(i,d),error:s=>{i.errorReference?.(s,[...d,"error"])}})}},examples:u=>{if(u!=null)for(let[c,d]of u.entries())Kx4({nodePathForExample:[...n,{key:"examples",arrayIndex:c}],visitor:i,service:r,endpoint:t,example:d})},pagination:Ko,source:Ko,transport:Ko})}function Kx4({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))hHt({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))hHt({example:o,visitor:t,nodePath:u});let c=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},c),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))hHt({example:o,visitor:t,nodePath:c});let d=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},d),n.request!=null&&hHt({example:n.request,visitor:t,nodePath:d});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},s),n.response!=null&&pen(i,n.response,{body:o=>{o.body!=null&&hHt({example:o.body,visitor:t,nodePath:s}),o.error!=null&&t.errorReference?.(o.error,[...s,"error"])},stream:o=>{for(let l of o.stream)hHt({example:l,visitor:t,nodePath:s})},events:o=>{for(let{data:l}of o.stream)hHt({example:l,visitor:t,nodePath:s})}}),n["code-samples"]!=null)for(let[o,l]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:l},[...e,{key:"code-samples",arrayIndex:o}])}function XOo({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),xLn(a)?typeof a=="string"?t.variableReference?.(a,u):b1(a,{docs:ZC(t,u),variable:c=>t.variableReference?.(c,[...u,"variable"]),availability:Ko}):typeof a=="string"?i(a,u):b1(a,{docs:ZC(t,u),type:c=>{i(c,[...u,"type"],{_default:a.default,validation:a.validation})},availability:Ko,encoding:Ko,default:Ko,validation:Ko,name:Ko,audiences:Ko})}}function Q0w({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):b1(a,{name:Ko,availability:Ko,type:c=>{i(c,u,{_default:a.default,validation:a.validation})},docs:ZC(t,u),audiences:Ko,encoding:Ko,env:Ko,default:Ko,validation:Ko})}}function J0w({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),omd({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function omd({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=nkt(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[c,d]of u.entries()){let s=[...i,{key:"examples",arrayIndex:c}];r.exampleType?.({typeName:e,typeDeclaration:t,example:d},s),hHt({example:d.value,nodePath:s,visitor:r})}};g6(t,{alias:u=>{typeof u=="string"?n(u,i):b1(u,{type:c=>{n(c,[...i,"type"])},docs:ZC(r,i),availability:Ko,audiences:Ko,examples:a,validation:Ko,encoding:Ko,source:Ko,inline:Ko})},object:u=>{b1(u,{docs:ZC(r,i),extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let o=[...i,"properties",d];typeof s=="string"?n(s,o):b1(s,{name:Ko,docs:ZC(r,o),availability:Ko,type:l=>{n(l,[...o,"type"],{_default:s.default,validation:s.validation})},audiences:Ko,encoding:Ko,default:Ko,validation:Ko,access:Ko})}},"extra-properties":Ko,availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},discriminatedUnion:u=>{b1(u,{docs:ZC(r,i),discriminant:Ko,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},union:c=>{for(let[d,s]of Object.entries(c)){let o=[...i,"union",d];typeof s=="string"?n(s,o):b1(s,{docs:ZC(r,o),name:Ko,key:Ko,type:l=>{typeof l=="string"&&n(l,[...i,"type"])},"display-name":Ko,availability:Ko})}},"base-properties":Ko,availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},undiscriminatedUnion:u=>{b1(u,{docs:ZC(r,i),discriminated:Ko,union:c=>{for(let[d,s]of c.entries()){let o=[...i,`union[${d}]`];typeof s!="string"&&b1(s,{docs:ZC(r,o),type:l=>{n(l,[...i,"type"])},"display-name":Ko,validation:Ko})}},availability:Ko,audiences:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})},enum:u=>{b1(u,{docs:ZC(r,i),enum:c=>{for(let d of c){let s=[...i,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&b1(d,{docs:ZC(r,s),name:Ko,value:Ko,casing:Ko})}},availability:Ko,audiences:Ko,default:Ko,encoding:Ko,source:Ko,examples:a,inline:Ko})}})}function K0w({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),Yx4({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function Yx4({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=nkt(r);typeof t=="string"?n(t,i):b1(t,{docs:ZC(r,i),"status-code":Ko,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):omd({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let c=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},c)}}})}function Y0w({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function X0w({webhook:e,visitor:t,nodePathForWebhook:r}){let i=nkt(t);b1(e,{"display-name":Ko,method:Ko,examples:Ko,headers:n=>{Xx4({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(Zx4(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),b1(n,{name:Ko,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let o=[...u,"extends",s];t.extension?.(s,o),i(s,o)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let o=[...u,"properties",d];typeof s=="string"?i(s,o,{location:BW.InlinedRequestProperty}):b1(s,{name:Ko,docs:ZC(t,o),availability:Ko,type:l=>{i(l,[...o,"type"],{_default:s.default,validation:s.validation,location:BW.InlinedRequestProperty})},audiences:Ko,encoding:Ko,default:Ko,validation:Ko,access:Ko})}}})},audiences:Ko,availability:Ko,docs:ZC(t,r)})}function Xx4({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=nkt(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):b1(a,{name:Ko,availability:Ko,type:c=>{i(c,u,{_default:a.default,validation:a.validation})},docs:ZC(t,u),audiences:Ko,encoding:Ko,env:Ko,default:Ko,validation:Ko})}}function Zx4(e){return e.type!=null}function KQ(e,t){b1(e,{docs:ZC(t,[]),imports:r=>{Y0w({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{J0w({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&G0w({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))X0w({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:Ko,errors:r=>{K0w({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function umd(e,t){b1(e,{docs:Ko,imports:Ko,types:Ko,service:Ko,webhooks:Ko,errors:Ko,channel:Ko,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function smd(e,t){t.file?.(e,[]),b1(e,{version:Ko,product:Ko,name:Ko,"default-url":Ko,"display-name":Ko,imports:Ko,auth:Ko,"idempotency-headers":Ko,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{ntc(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:Ko,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Ko,headers:Ko,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Ko,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":Ko,"path-parameters":r=>{XOo({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var R7s=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function Z0w({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.definitionFile?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function k0w({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.packageMarker?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function egw({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(c,d)=>{for(let s of r){let o=s.rootApiFile?.[a];if(o!=null){let l=o(c,{relativeFilepath:e,contents:t});i(l.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var cmd={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(den(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&kB(e.request.body)){let r=[];for(let[i,n]of Object.entries(e.request.body.properties??{}))typeof n!="string"&&n["content-type"]!=null&&r.push({severity:"fatal",message:`${i} has content-type, but the request is not multipart`});return r}return[]}}})};var QD=Aee({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var lmd={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new BS(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!kx4(r.request.body))return[];let a=[];for(let[u,c]of Object.entries(r.request.body.properties??{})){if(typeof c=="string"||c.style!=="exploded")continue;let d=og({relativeFilepath:i,definitionFile:n,casingsGenerator:QD,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:c.type,file:d});if(s==null)return[];tgw(s)||a.push({message:`${u} is exploded and must be a list. Did you mean list<${c.type}>?`,severity:"error"})}return a}}}}};function tgw(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?tgw(e.container.itemType):!1}function kx4(e){return e?.properties!=null}var fmd={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(Kmi(e.definition)),r=new Set;return t.forEach(i=>{let n=Bu(e.definition.absoluteFilePath,za.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],c=Bu(e.definition.absoluteFilePath,zd(a),za.of(n));return r.has(c)||u.push({severity:"fatal",message:`Import ${Bs.bold(i)} points to non-existent path ${Bs.bold(n)}.`}),u}}}}};function N7s(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(zLn(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var dmd={name:"matching-environment-urls",create:({workspace:e})=>{let t=N7s(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"fatal",message:`Environment ${r} is missing URL for ${Bs.bold(u)}`})};return sir(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let c of t)u.urls[c]==null&&a(c)}}),n}}}}};var pmd={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=eR4(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=e7i({referencedIn:i,importPath:za.of(r)});return n.filter(({chainWithoutStartingFilepath:c})=>c.length===0||c[0]===a).map(c=>({severity:"fatal",message:c.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[c.startingFilepath,...c.chainWithoutStartingFilepath,c.startingFilepath].join(" -> ")}`}))}}}}};function eR4(e){let t={};for(let r of M$t(e))t[r]=rgw(r,[r],e);return t}function rgw(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=e7i({referencedIn:e,importPath:za.of(a)});t.includes(u)?t[0]===u&&t[0]===tR4(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...rgw(u,[...t,u],r))}return i}function tR4(e){return e.reduce((t,r)=>r<t?r:t)}var F7s=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new BS(t)}isTypeComplex(t,r){let i=og({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:QD,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:Ao(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:Ao(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),kIi(t.declaration))return!0;if(hGt(t.declaration))return!1;if(wD(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(RLn(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Ao(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return rJt({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:Ao(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:Ao(t)}}};var _md={name:"no-complex-query-params",create:({workspace:e})=>{let t=new F7s(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"fatal",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var hmd={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===Ahu?[{severity:"fatal",message:`Path parameter ${Bs.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function ZOo({service:e,endpoint:t}){return e["base-path"]+t.path}var L7s=class{root=new ymd;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 ZOo({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},ymd=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var vmd={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new L7s;return V6(e,(r,i)=>{KQ(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${ZOo({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(c=>` - ${c.relativeFilepath} -> ${c.endpointId} ${Bs.dim(ZOo({service:c.service,endpoint:c.endpoint}))}`)].join(`
2400
2400
  `)}]}}}}};var bmd={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:i,relativeFilepath:n})=>{let a=rR4({endpoint:t,service:r,relativeFilepath:n,definitionFile:i,workspace:e}),u=[];for(let[c,d]of Object.entries(a))d.length<=1||u.push({severity:"fatal",message:`Multiple request properties have the name ${Bs.bold(c)}. This is not suitable for code generation. Use the "name" property to deconflict.
2401
2401
  `+d.map(s=>` - ${iR4(s)}`).join(`
2402
2402
  `)});return u}}})};function rR4({endpoint:e,service:t,relativeFilepath:r,definitionFile:i,workspace:n}){let a={},u=(c,d)=>{(a[c]??=[]).push(d)};if(e.request!=null&&typeof e.request!="string"&&e.request.body!=null&&!kB(e.request.body)&&qhu({request:e.request,file:og({relativeFilepath:r,definitionFile:i,casingsGenerator:QD,rootApiFile:n.definition.rootApiFile.contents}),typeResolver:new BS(n)})&&u(tVa,{type:"referenced-body",propertyName:tVa}),t.headers!=null)for(let[c,d]of Object.entries(t.headers))u(Kor({headerKey:c,header:d}).name,{type:"service-header",headerKey:c,header:d});if(e.request!=null&&typeof e.request!="string"){if(e.request.headers!=null)for(let[c,d]of Object.entries(e.request.headers))u(Kor({headerKey:c,header:d}).name,{type:"endpoint-header",headerKey:c,header:d});if(e.request["query-parameters"]!=null)for(let[c,d]of Object.entries(e.request["query-parameters"]))u(NPi({queryParameterKey:c,queryParameter:d}).name,{type:"endpoint-query-parameter",queryParameterKey:c,queryParameter:d});if(e.request.body!=null&&kB(e.request.body)){let c=rJt({typeName:void 0,objectDeclaration:{extends:e.request.body.extends,properties:e.request.body.properties??{}},filepathOfDeclaration:r,definitionFile:i,workspace:n,typeResolver:new BS(n),smartCasing:!1});for(let d of c)u(d.name,{type:"inlined-body",property:d})}}return a}function iR4(e){switch(e.type){case"service-header":return`Service header "${e.headerKey}"`;case"endpoint-header":return`Endpoint header "${e.headerKey}"`;case"endpoint-query-parameter":return`Query Parameter "${e.queryParameterKey}"`;case"inlined-body":return`Body property: ${wXn({property:e.property,prefixBreadcrumbs:["<Request Body>"]})}`;case"referenced-body":return`Body property "${e.propertyName}"`;default:Ao(e)}}var gmd=ui(require("path"),1);var Omd={name:"no-duplicate-declarations",create:({workspace:e,logger:t})=>{let r=nR4(e),i={},n=({declaredName:a,relativeFilepath:u})=>{let c=gmd.default.dirname(u),d=r[c]?.[a];if(d==null)return t.error(`Could not find declarations for name: ${a}. This is an error in the Fern validator.`),[];let s=i[c]??=new Set;if(!s.has(a))return s.add(a),[];let o=d.indexOf(u);return d.filter((b,g)=>g!==o).map(b=>({severity:"fatal",message:`${a} is already declared in ${b===u?"this file":b}`}))};return{definitionFile:{typeName:(a,{relativeFilepath:u})=>n({declaredName:a,relativeFilepath:u}),errorDeclaration:({errorName:a},{relativeFilepath:u})=>n({declaredName:a,relativeFilepath:u}),httpEndpoint:({endpoint:a},{relativeFilepath:u})=>typeof a.request!="string"&&a.request?.name!=null?n({declaredName:a.request.name,relativeFilepath:u}):[]}}}};function nR4(e){let t={};return V6(e,(r,i)=>{let n=gmd.default.dirname(r),a=t[n]??={},u=c=>{(a[c]??=[]).push(r)};KQ(i,{typeName:c=>{u(c)},errorDeclaration:({errorName:c})=>{u(c)},httpEndpoint:({endpoint:c})=>{typeof c.request!="string"&&c.request?.name!=null&&u(c.request.name)}})}),t}function kOo(e){let t=new Set,r=new Set,i=[];for(let n of e)t.has(n)&&!r.has(n)&&(r.add(n),i.push(n)),t.add(n);return i}var mmd={name:"no-duplicate-enum-values",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>hGt(e)?kOo(e.enum.map(r=>typeof r=="string"?r:r.value)).map(r=>({severity:"fatal",message:`Duplicated enum value: ${Bs.bold(r)}.`})):[]}})};var Pmd={name:"no-duplicate-example-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>{if(typeof e=="string"||e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(yy);return kOo(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))},httpEndpoint:({endpoint:e})=>{if(e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(yy);return kOo(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))}}})};function igw(e){if(!e.isInlined)return e.name;switch(e.location){case"inlinedRequest":return"<Inlined Request>";default:Ao(e.location)}}var jmd={name:"no-duplicate-field-names",create:({workspace:e})=>{let t=new BS(e);return{definitionFile:{typeDeclaration:({typeName:r,declaration:i},{relativeFilepath:n,contents:a})=>{let u=[];return g6(i,{alias:P3e,enum:c=>{let d=ngw(c.enum,s=>AXn(s).name);for(let s of d)u.push({severity:"fatal",message:`Name "${s}" is used by multiple values.`})},object:c=>{let d=igw(r),s=rJt({typeName:d,objectDeclaration:c,filepathOfDeclaration:n,definitionFile:a,workspace:e,typeResolver:t,smartCasing:!1}),o=gHs(s,l=>l.name);for(let[l,b]of Object.entries(o))if(b.length>1){let g=[`Object has multiple properties named "${l}":`,...b.map(O=>` - ${wXn({property:O,prefixBreadcrumbs:[d]})}`)].join(`