fern-api 0.107.7 → 0.107.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -2428,7 +2428,7 @@ ${Ogy.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Dgf(th
2428
2428
  `+_ua.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?_ua.default.cyan(Igy(t,this.opt.mask)):_ua.default.italic(_ua.default.dim("[hidden]")):this.opt.mask?Igy(t,this.opt.mask):_ua.default.italic(_ua.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 uSu=$i(hse(),1);var I0y=$i(c0f(),1),oSu=require("child_process"),iZa=require("fs"),aSu=$i(require("path"),1),M0y=$i(require("os"),1),B0y=require("crypto"),J0f=$i(D0y(),1);var rSu=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var TKo=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var nSu=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var iSu=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function sSu(e="",t,r){let n=new K0f(e,r);n.runAsync((i,a)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function C0y(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function _AC(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var K0f=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=_AC(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??M0y.default.tmpdir(),r=(0,B0y.randomUUID)(),n=C0y(this.fileOptions.prefix),i=C0y(this.fileOptions.postfix),a=`${n}${r}${i}`,o=aSu.default.resolve(t,a),c=aSu.default.resolve(t)+aSu.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let f={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(f.mode=this.fileOptions.mode),(0,iZa.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new rSu(t)}}readTemporaryFile(){try{let t=(0,iZa.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,I0y.detect)(t)??"utf8";J0f.default.encodingExists(r)||(r="utf8"),this.text=J0f.default.decode(t,r)}}catch(t){throw new nSu(t)}}removeTemporaryFile(){try{(0,iZa.unlinkSync)(this.tempFile)}catch(t){throw new iSu(t)}}launchEditor(){try{let t=(0,oSu.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new TKo(t)}}launchEditorAsync(t){try{(0,oSu.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new TKo(r)}}};var T0y=$i(Drt(),1);var qKo=class extends yse{_run(t){this.done=t,this.editorResult=new T0y.Subject;let r=Vve(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?uSu.default.dim("Received"):uSu.default.dim("Press <enter> to launch your preferred editor."),t&&(r=uSu.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),sSu(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 x0y=require("stream");var N0y=$i(require("readline"),1),F0y=$i(R0y(),1),bua=class{constructor(t){this.rl||=N0y.default.createInterface(yAC(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 yAC(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new F0y.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var RKo=class extends bua{constructor(t={}){super(t),this.log=new x0y.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return bKo(this.rl,this.bottomBar.split(`
2429
2429
  `).length),this}updateBottomBar(t){return bKo(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+`
2430
2430
  `}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&&IEu(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var L4=$i(Drt(),1),L0y=$i(zJo(),1);var cSu=$i(Drt(),1),z0y=$i(zJo(),1),lSu=function(e,t,r){return typeof e[t]!="function"?(0,cSu.of)(e):(0,cSu.from)((0,z0y.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Q0y={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,a,o)=>{i==="__proto__"||i==="constructor"||(a===o.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},aZa=class extends bua{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,L4.from)(t):(0,L4.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,L4.from)(Object.entries(t).map(([i,a])=>({name:i,...a}))):n=(0,L4.from)([t]),this.process=n.pipe((0,L4.concatMap)(this.processQuestion.bind(this)),(0,L4.publish)()),this.process.connect(),this.process.pipe((0,L4.reduce)((i,a)=>(Q0y.set(i,a.name,a.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,L4.defer)(()=>(0,L4.of)(t).pipe((0,L4.concatMap)(this.setDefaultType.bind(this)),(0,L4.concatMap)(this.filterIfRunnable.bind(this)),(0,L4.concatMap)(()=>lSu(t,"message",this.answers)),(0,L4.concatMap)(()=>lSu(t,"default",this.answers)),(0,L4.concatMap)(()=>lSu(t,"choices",this.answers)),(0,L4.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,L4.defer)(()=>(0,L4.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,L4.defer)(()=>(0,L4.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Q0y.get(this.answers,t.name)!==void 0)return L4.EMPTY;if(t.when===!1)return L4.EMPTY;if(typeof t.when!="function")return(0,L4.of)(t);let{answers:r}=this;return(0,L4.defer)(()=>(0,L4.from)((0,L0y.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,L4.filter)(n=>n!=null)))}};function U0y(e){let t=function(r,n){let i;try{i=new aZa(t.prompts,e)}catch(o){return Promise.reject(o)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",mKo),this.registerPrompt("input",pua),this.registerPrompt("number",OKo),this.registerPrompt("confirm",AKo),this.registerPrompt("rawlist",PKo),this.registerPrompt("expand",wKo),this.registerPrompt("checkbox",jKo),this.registerPrompt("password",EKo),this.registerPrompt("editor",qKo)},t.restoreDefaultPrompts(),t}var Y0f=U0y();function bAC(e,t){Y0f.registerPrompt(e,t)}function gAC(){Y0f.restoreDefaultPrompts()}var mAC={prompt:Y0f,ui:{BottomBar:RKo,Prompt:aZa},createPromptModule:U0y,registerPrompt:bAC,restoreDefaultPrompts:gAC,Separator:YFe},fSu=mAC;var bZa=require("path"),OOy=require("fs"),AOy=require("readline"),Gmy="posthog-node";function JwC(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"]}={}){return a=>{if(!(i==="*"||i.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[MSu.POSTHOG_ID_TAG];if(c===void 0)return a;let f=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,f).toString();a.tags["PostHog Person URL"]=u;let s=a.exception?.values||[],l=s.map(A=>({...A,stacktrace:A.stacktrace?{...A.stacktrace,type:"raw",frames:(A.stacktrace.frames||[]).map(P=>({...P,platform:"node:javascript"}))}:void 0})),m={$exception_message:s[0]?.value||a.message,$exception_type:s[0]?.type,$exception_personURL:u,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:s[0]?.value||a.message,$sentry_exception_type:s[0]?.type,$sentry_tags:a.tags};return t&&r&&(m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:m}),a}}var MSu=class{constructor(t,r,n,i){this.name=Gmy,this.name=Gmy,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(JwC(t,{organization:r,projectId:c,prefix:n,severityAllowList:i}))}}};MSu.POSTHOG_ID_TAG="posthog_distinct_id";var ESu="0123456789abcdef",BSu=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,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>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|n>>>24,a[9]=n>>>16,a[10]=n>>>8,a[11]=n,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,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 n=new Uint8Array(16);for(let i=0;i<16;i+=4){let a=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=a>>>24,n[i+1]=a>>>16,n[i+2]=a>>>8,n[i+3]=a}return new e(n)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=ESu.charAt(this.bytes[r]>>>4),t+=ESu.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+=ESu.charAt(this.bytes[r]>>>4),t+=ESu.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 n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},qmf=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??KwC()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}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 BSu.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,BSu.ofInner(t)}},KwC=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Jmy,Rmf=()=>$wC().toString(),$wC=()=>(Jmy||(Jmy=new qmf)).generate();function YwC(e,t){let r=!1;return Object.assign(n=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function XwC(e,t){global.process.on("uncaughtException",YwC(e,t))}function ZwC(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var SSu,Kmy,DSu;function kwC(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return DSu&&r.length===Kmy||(Kmy=r.length,DSu=r.reduce((n,i)=>{SSu||(SSu={});let a=SSu[i];if(a)n[a[0]]=a[1];else{let o=e(i);for(let c=o.length-1;c>=0;c--){let u=o[c]?.filename,s=t[i];if(u&&s){n[u]=s,SSu[i]=[u,s];break}}}return n},{})),DSu}function ejC(e){return typeof Event<"u"&&POy(e,Event)}function tjC(e){return wOy(e,"Object")}function Vmf(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return POy(e,Error)}}function POy(e,t){try{return e instanceof t}catch{return!1}}function rjC(e){return wOy(e,"ErrorEvent")}function wOy(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function njC(e,t,r,n){let a=n&&n.mechanism||{handled:!0,type:"generic"},o=jOy(a,r,n);return{$exception_list:await Promise.all(o.map(async u=>{let s=await ljC(e,t,u);return s.value=s.value||"",s.type=s.type||"Error",s.mechanism=a,s}))}}function jOy(e,t,r){let n=ijC(e,t,r);return n.cause?[n,...jOy(e,n.cause,r)]:[n]}function ijC(e,t,r){if(Vmf(t))return t;if(e.synthetic=!0,tjC(t)){let i=ajC(t);if(i)return i;let a=ojC(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let n=r?.syntheticException||new Error(t);return n.message=`${t}`,n}function ajC(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(Vmf(r))return r}}function ojC(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(n+=` with message '${e.message}'`),n}else if("message"in e&&typeof e.message=="string")return e.message;let t=ujC(e);if(rjC(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=sjC(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function sjC(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function ujC(e,t=40){let r=Object.keys(cjC(e));r.sort();let n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return $my(n,t);for(let i=r.length;i>0;i--){let a=r.slice(0,i).join(", ");if(!(a.length>t))return i===r.length?a:$my(a,t)}return""}function $my(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function cjC(e){return Vmf(e)?{message:e.message,name:e.name,stack:e.stack,...Ymy(e)}:ejC(e)?{type:e.type,target:Xmy(e.target),currentTarget:Xmy(e.currentTarget),...Ymy(e)}:e}function Ymy(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 Xmy(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function ljC(e,t,r){let n={type:r.name||r.constructor.name,value:r.message},i=fjC(e,r);for(let a of t)i=await a(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function fjC(e,t){return djC(e(t.stack||"",1),e)}function djC(e,t){let r=kwC(t);return e.forEach(n=>{n.filename&&(n.chunk_id=r[n.filename])}),e}var pjC=2e3,hZa=class e{static async captureException(t,r,n,i,a){let o={...a};i||(o.$process_person_profile=!1);let c=await njC(this.stackParser,this.frameModifiers,r,n);t.capture({event:"$exception",distinctId:i||Rmf(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(XwC(this.onException.bind(this),this.onFatalError.bind(this)),ZwC(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(pjC)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function _jC(e=process.argv[1]?(0,bZa.dirname)(process.argv[1]):process.cwd(),t=bZa.sep==="\\"){let r=t?Zmy(e):e;return n=>{if(!n)return;let i=t?Zmy(n):n,{dir:a,base:o,ext:c}=bZa.posix.parse(i);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,c.length*-1));let f=decodeURIComponent(o);a||(a=".");let u=a.lastIndexOf("/node_modules");if(u>-1)return`${a.slice(u+14).replace(/\//g,".")}:${f}`;if(a.startsWith(r)){let s=a.slice(r.length+1).replace(/\//g,".");return s?`${s}:${f}`:f}return f}}function Zmy(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var TSu=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)}}},ISu=new TSu(25),EOy=new TSu(20),Wmf=7,hjC=1e3,yjC=1e4;async function vjC(e){let t={};for(let i=e.length-1;i>=0;i--){let a=e[i],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||OjC(o)||AjC(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(EOy.get(i))continue;let a=t[i];if(!a)continue;a.sort((f,u)=>f-u);let o=wjC(a);if(o.every(f=>PjC(i,f)))continue;let c=jjC(ISu,i,{});n.push(bjC(i,o,c))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&gjC(e,ISu),ISu.reduce(),e}function bjC(e,t,r){return new Promise(n=>{let i=(0,OOy.createReadStream)(e),a=(0,AOy.createInterface)({input:i});function o(){i.destroy(),n()}let c=0,f=0,u=t[f];if(u===void 0){o();return}let s=u[0],l=u[1];function m(){EOy.set(e,1),a.close(),a.removeAllListeners(),o()}i.on("error",m),a.on("error",m),a.on("close",o),a.on("line",A=>{if(c++,!(c<s)&&(r[c]=EjC(A,0),c>=l)){if(f===t.length-1){a.close(),a.removeAllListeners();return}f++;let P=t[f];if(P===void 0){a.close(),a.removeAllListeners();return}s=P[0],l=P[1]}})})}function gjC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;mjC(r.lineno,r,n)}}function mjC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=SOy(e);i<e;i++){let a=r[i];if(a===void 0){kmy(t);return}t.pre_context.push(a)}if(r[e]===void 0){kmy(t);return}t.context_line=r[e];let n=DOy(e);t.post_context=[];for(let i=e+1;i<=n;i++){let a=r[i];if(a===void 0)break;t.post_context.push(a)}}function kmy(e){delete e.pre_context,delete e.context_line,delete e.post_context}function OjC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function AjC(e){return e.lineno!==void 0&&e.lineno>yjC||e.colno!==void 0&&e.colno>hjC}function PjC(e,t){let r=ISu.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function wjC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=eOy(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let a=e[t+1];if(typeof a!="number")break;a<=n[1]?n[1]=a+Wmf:(i.push(n),n=eOy(a)),t++}return i}function eOy(e){return[SOy(e),DOy(e)]}function SOy(e){return Math.max(1,e-Wmf)}function DOy(e){return e+Wmf}function jjC(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function EjC(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,n);return a>n-5&&(a=n),a===n&&(i=Math.max(a-140,0)),r=r.slice(i,a),i>0&&(r=`...${r}`),a<n&&(r+="..."),r}var SjC="4.18.0",txe;(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"})(txe||(txe={}));var tOy;(function(e){e.Left="left",e.Right="right",e.Center="center"})(tOy||(tOy={}));var rOy;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(rOy||(rOy={}));var nOy;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(nOy||(nOy={}));var iOy;(function(e){e.Html="html",e.Text="text"})(iOy||(iOy={}));var aOy;(function(e){e.Number="number",e.Emoji="emoji"})(aOy||(aOy={}));var oOy;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(oOy||(oOy={}));var sOy;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(sOy||(sOy={}));var uOy;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(uOy||(uOy={}));var cOy;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(cOy||(cOy={}));var DjC=e=>{if("flags"in e){let t=IjC(e.flags),r=MjC(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,a])=>[i,COy(a)])),n=Object.fromEntries(Object.entries(t).map(([i,a])=>[i,CjC(i,a,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function CjC(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 IjC=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Hmf(r)]).filter(([,t])=>t!==void 0)),MjC=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?COy(n):void 0]}))},Hmf=e=>e===void 0?void 0:e.variant??e.enabled,COy=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},BjC=1,TjC=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"]),qjC="utf8";function RjC(e,t){if(!e||typeof e!="string"||NjC(e))throw new Error(t)}function NjC(e){return e.trim().length===0}function FjC(e){return e?.replace(/\/+$/,"")}async function xjC(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function lOy(){return new Date().getTime()}function Bmf(){return new Date().toISOString()}function qSu(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function zjC(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function QjC(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 LjC(e,t=0,r){let n=QjC(e);return r?.has(n)?!1:parseInt(n,16)/4294967295<t}function fOy(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var HKo=String.fromCharCode,dOy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",CSu={};function UjC(e,t){if(!CSu[e]){CSu[e]={};for(let r=0;r<e.length;r++)CSu[e][e.charAt(r)]=r}return CSu[e][t]}var pZa={compressToBase64:function(e){if(e==null)return"";let t=pZa._compress(e,6,function(r){return dOy.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:pZa._decompress(e.length,32,function(t){return UjC(dOy,e.charAt(t))})},compress:function(e){return pZa._compress(e,16,function(t){return HKo(t)})},_compress:function(e,t,r){if(e==null)return"";let n={},i={},a=[],o,c,f="",u="",s="",l=2,m=3,A=2,P=0,C=0,I;for(I=0;I<e.length;I+=1)if(f=e.charAt(I),Object.prototype.hasOwnProperty.call(n,f)||(n[f]=m++,i[f]=!0),u=s+f,Object.prototype.hasOwnProperty.call(n,u))s=u;else{if(Object.prototype.hasOwnProperty.call(i,s)){if(s.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=s.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=s.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[s]}else for(c=n[s],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++),n[u]=m++,s=String(f)}if(s!==""){if(Object.prototype.hasOwnProperty.call(i,s)){if(s.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=s.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=s.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[s]}else for(c=n[s],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++)}for(c=2,o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;for(;;)if(P=P<<1,C==t-1){a.push(r(P));break}else C++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:pZa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let n=[],i=[],a={val:r(0),position:t,index:1},o=4,c=4,f=3,u="",s,l,m,A,P,C,I;for(s=0;s<3;s+=1)n[s]=s;for(m=0,P=Math.pow(2,2),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;I=HKo(m);break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;I=HKo(m);break;case 2:return""}for(n[3]=I,l=I,i.push(I);;){if(a.index>e)return"";for(m=0,P=Math.pow(2,f),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(I=m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=HKo(m),I=c-1,o--;break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=HKo(m),I=c-1,o--;break;case 2:return i.join("")}if(o==0&&(o=Math.pow(2,f),f++),n[I])u=n[I];else if(I===c)u=l+l.charAt(0);else return null;i.push(u),n[c++]=l+u.charAt(0),o--,l=u,o==0&&(o=Math.pow(2,f),f++)}}},Nmf=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(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}},yZa=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()}},GKo=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function pOy(e){if(e instanceof yZa){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 Tmf(e){return typeof e=="object"&&(e instanceof yZa||e instanceof GKo)}function _Oy(e){return typeof e=="object"&&e instanceof yZa&&e.status===413}var Fmf;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Fmf||(Fmf={}));var xmf=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new Nmf,this._isInitialized=!1,RjC(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=FjC(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:Tmf},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(txe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(txe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(txe.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>console.log("PostHog Debug",n,i));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=Rmf();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",a,i)})}async captureStatelessImmediate(t,r,n,i){let a=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",a,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",a,i)})}async aliasStatelessImmediate(t,r,n,i){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,i)}groupIdentifyStateless(t,r,n,i,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...o||{}}});this.enqueue("capture",c,i)})}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`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",i)),this._events.emit("error",i)})}async getDecide(t,r={},n={},i={},a={}){await this._initPromise;let c=LjC(this.apiKey,BjC,TjC)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(u=>u.json()).then(u=>DjC(u)).catch(u=>{this._events.emit("error",u)})}async getFeatureFlagStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,n,i,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let f=Hmf(c.response);return f===void 0&&(f=!1),{response:f,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,n,i,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,n,i,a,o,[t]);if(!c)return;let f=c[t];return f===void 0?null:f}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,n,i,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let f=await this.getDecide(t,r,n,i,c);if(f!==void 0)return f.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"),f.quotaLimited?.includes(Fmf.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:f?.requestId}):f}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"}},i=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return i&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(i))),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(txe.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(txe.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(txe.Props,this.props)})}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let i=this.prepareMessage(t,r,n),a=this.getPersistedProperty(txe.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:i}),this.setPersistedProperty(txe.Queue,a),this._events.emit(t,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=qSu(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){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 i={api_key:this.apiKey,batch:[this.prepareMessage(t,r,n)],sent_at:Bmf()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${lOy()}&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(pZa.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(f){this._events.emit("error",f)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:Bmf(),uuid:n?.uuid?n.uuid:Rmf()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await pOy(t)})}async flush(){let t=fOy([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),fOy([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(txe.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),a=i.map(m=>m.message),o=()=>{let A=(this.getPersistedProperty(txe.Queue)||[]).slice(i.length);this.setPersistedProperty(txe.Queue,A),t=A},c={api_key:this.apiKey,batch:a,sent_at:Bmf()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${lOy()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,s=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(pZa.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:m=>_Oy(m)?!1:Tmf(m)};try{await this.fetchWithRetry(u,s,l)}catch(m){if(_Oy(m)&&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 m instanceof GKo||o(),this._events.emit("error",m),m}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){var a;(a=AbortSignal).timeout??(a.timeout=function(u){let s=new AbortController;return setTimeout(()=>s.abort(),u),s.signal});let o=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(o,qjC)}catch{c=new TextEncoder().encode(o).length}return await xjC(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(s){throw new GKo(s)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new yZa(f,c);return f},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(txe.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!Tmf(i))throw i;await pOy(i)}};return Promise.race([new Promise((i,a)=>{qSu(()=>{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)}),n()])}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}},zmf=zjC();if(!zmf){let e=Hmy();zmf=async(t,r)=>{let n=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:n.status,text:async()=>n.data,json:async()=>n.data}}}var IOy=zmf,RSu=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()}},MOy=new RSu(async()=>{try{return await import("crypto")}catch{return}});async function VjC(){return await MOy.getValue()}var WjC=new RSu(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await MOy.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function HjC(){return await WjC.getValue()}async function GjC(e){let t=await VjC();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await HjC();if(r){let n=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).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 JjC=60*1e3,KjC=1152921504606847e3,$jC=["is_not"],_Za=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},vse=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Qmf=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:a,customHeaders:o,...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=i,this.projectApiKey=n,this.host=a,this.poller=void 0,this.fetch=c.fetch||IOy,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,n={},i={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let f of this.featureFlags)if(t===f.key){c=f;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,n,i,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(f){f instanceof vse?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}return o}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let n;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),n==null)return null;try{return JSON.parse(n)}catch{return n}}}async getAllFlagsAndPayloads(t,r={},n={},i={}){await this.loadFeatureFlags();let a={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async f=>{try{let u=await this.computeFlagLocally(f,t,r,n,i);a[f.key]=u;let s=await this.computeFeatureFlagPayloadLocally(f.key,u);s&&(o[f.key]=s)}catch(u){u instanceof vse||u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${u}`)),c=!0}})),{response:a,payloads:o,fallbackToDecide:c}}async computeFlagLocally(t,r,n={},i={},a={}){if(t.ensure_experience_continuity)throw new vse("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let f=this.groupTypeMapping[String(c)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new vse("Flag has unknown group type index");if(!(f in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[f];return await this.matchFeatureFlagProperties(t,n[f],u)}else return await this.matchFeatureFlagProperties(t,r,i)}async matchFeatureFlagProperties(t,r,n){let i=t.filters||{},a=i.groups||[],o=!1,c,f=[...a].sort((u,s)=>{let l=!!u.variant,m=!!s.variant;return l&&m?0:l?-1:m?1:0});for(let u of f)try{if(await this.isConditionMatch(t,r,u,n)){let s=u.variant,l=i.multivariate?.variants||[];s&&l.some(m=>m.key===s)?c=s:c=await this.getMatchingVariant(t,r)||!0;break}}catch(s){if(s instanceof vse)o=!0;else throw s}if(c!==void 0)return c;if(o)throw new vse("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i){let a=n.rollout_percentage,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let f=c.type,u=!1;if(f==="cohort"?u=TOy(c,i,this.cohorts,this.debugMode):u=BOy(c,i,o),!u)return!1}if(a==null)return!0}return!(a!=null&&await hOy(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await hOy(t.key,r,"variant"),i=this.variantLookupTable(t).find(a=>n>=a.valueMin&&n<a.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{i=n+c.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:c.key}),n=i}),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(JjC,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 _Za(`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 _Za(`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 _Za(`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((n,i)=>(n[i.key]=i,n),{}),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 _Za&&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(),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=qSu(()=>{i.abort()},this.timeout),r.signal=i.signal}try{return await this.fetch(t,r)}finally{clearTimeout(n)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,n=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;i=qSu(()=>{a.abort()},this.timeout),n.signal=a.signal}try{return this.fetch(r,n)}finally{clearTimeout(i)}}};async function hOy(e,t,r=""){let n=await GjC(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/KjC}function BOy(e,t,r){let n=e.key,i=e.value,a=e.operator||"exact";if(n in t){if(a==="is_not_set")throw new vse("Operator is_not_set is not supported")}else throw new vse(`Property ${n} not found in propertyValues`);let o=t[n];if(o==null&&!$jC.includes(a))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${a} operator`),!1;function c(u,s){return Array.isArray(u)?u.map(l=>String(l).toLowerCase()).includes(String(s).toLowerCase()):String(u).toLowerCase()===String(s).toLowerCase()}function f(u,s,l){if(l==="gt")return u>s;if(l==="gte")return u>=s;if(l==="lt")return u<s;if(l==="lte")return u<=s;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(i,o);case"is_not":return!c(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":return yOy(String(i))&&String(o).match(String(i))!==null;case"not_regex":return yOy(String(i))&&String(o).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u!=null&&o!=null?typeof o=="string"?f(o,String(i),a):f(o,u,a):f(String(o),String(i),a)}case"is_date_after":case"is_date_before":{let u=YjC(String(i));if(u==null&&(u=vOy(i)),u==null)throw new vse(`Invalid date: ${i}`);let s=vOy(o);return["is_date_before"].includes(a)?s<u:s>u}default:throw new vse(`Unknown operator: ${a}`)}}function TOy(e,t,r,n=!1){let i=String(e.value);if(!(i in r))throw new vse("can't match cohort without a given cohort property value");let a=r[i];return qOy(a,t,r,n)}function qOy(e,t,r,n=!1){if(!e)return!0;let i=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let f=qOy(c,t,r,n);if(i==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof vse)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new vse("Can't match cohort without a given cohort property value");return i==="AND"}else{for(let c of a)try{let f;c.type==="cohort"?f=TOy(c,t,r,n):f=BOy(c,t);let u=c.negation||!1;if(i==="AND"){if(!f&&!u||f&&u)return!1}else if(f&&!u||!f&&u)return!0}catch(f){if(f instanceof vse)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new vse("can't match cohort without a given cohort property value");return i==="AND"}}function yOy(e){try{return new RegExp(e),!0}catch{return!1}}function vOy(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 vse(`${e} is in an invalid date format`)}else throw new vse(`The date provided ${e} must be a string, number, or date object`)}function YjC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let a=r.groups.interval;if(a=="h")n.setUTCHours(n.getUTCHours()-i);else if(a=="d")n.setUTCDate(n.getUTCDate()-i);else if(a=="w")n.setUTCDate(n.getUTCDate()-i*7);else if(a=="m")n.setUTCMonth(n.getUTCMonth()-i);else if(a=="y")n.setUTCFullYear(n.getUTCFullYear()-i);else return null;return n}else return null}var Lmf=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},XjC=100,bOy=30*1e3,ZjC=50*1e3,Umf=class extends xmf{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Lmf,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,XjC):bOy,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 Qmf({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new hZa(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||ZjC}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):IOy(t,r)}getLibraryVersion(){return SjC}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:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:u}=t,s=A=>{super.captureStateless(r,n,A,{timestamp:c,disableGeoip:f,uuid:u})},l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags,m=Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[I,T]of Object.entries(A))P[`$feature/${I}`]=T;let C=Object.keys(A||{}).filter(I=>A?.[I]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{s({...A,...i,$groups:a})});this.addPendingPromise(m)}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:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:u}=t,s=A=>super.captureStatelessImmediate(r,n,A,{timestamp:c,disableGeoip:f,uuid:u}),l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[I,T]of Object.entries(A))P[`$feature/${I}`]=T;let C=Object.keys(A||{}).filter(I=>A?.[I]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{s({...A,...i,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:i},{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:i},{disableGeoip:n})}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=bOy){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(n),i(),r(a>0)})})}async getFeatureFlag(t,r,n){let{groups:i,disableGeoip:a}=n||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:f,groupProperties:u}=n||{},s=this.addLocalPersonAndGroupProperties(r,i,f,u);f=s.allPersonProperties,u=s.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,i,f,u),m=l!==void 0,A,P;if(!m&&!o){let I=await super.getFeatureFlagDetailStateless(t,r,i,f,u,a);if(I===void 0)return;P=I.response,l=Hmf(P),A=I?.requestId}let C=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(C))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(C):this.distinctIdHasSentFlagCalls[r]=[C],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:P?.metadata?.id,$feature_flag_version:P?.metadata?.version,$feature_flag_reason:P?.reason?.description??P?.reason?.code,locally_evaluated:m,[`$feature/${t}`]:l,$feature_flag_request_id:A},groups:i,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,n,i){let{groups:a,disableGeoip:o}=i||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:f,personProperties:u,groupProperties:s}=i||{},l=this.addLocalPersonAndGroupProperties(r,a,u,s);u=l.allPersonProperties,s=l.allGroupProperties;let m;return this.featureFlagsPoller!==void 0&&(n||(n=await this.getFeatureFlag(t,r,{...i,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),n&&(m=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,n))),c==null&&(c=!1),f==null&&(f=!0),c==null&&(c=!1),!(m!==void 0)&&!c&&(m=await super.getFeatureFlagPayloadStateless(t,r,a,u,s,o)),m}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:n,disableGeoip:i}=r||{},{onlyEvaluateLocally:a,personProperties:o,groupProperties:c}=r||{},f=this.addLocalPersonAndGroupProperties(t,n,o,c);o=f.allPersonProperties,c=f.allGroupProperties,a==null&&(a=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,n,o,c),s={},l={},m=!0;if(u&&(s=u.response,l=u.payloads,m=u.fallbackToDecide),m&&!a){let A=await super.getFeatureFlagsAndPayloadsStateless(t,n,o,c,i);s={...s,...A.flags||{}},l={...l,...A.payloads||{}}}return{featureFlags:s,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:a}){super.groupIdentifyStateless(t,r,n,{disableGeoip:a},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,n,i){let a={distinct_id:t,...n||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...i?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,n){let i=new Error("PostHog syntheticException");hZa.captureException(this,t,{syntheticException:i},r,n)}},gOy=/\(error: (.*)\)/,ROy=50,NOy="?";function kjC(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return n=>{let i=n.match(r);if(i){let a,o,c,f,u;if(i[1]){c=i[1];let m=c.lastIndexOf(".");if(c[m-1]==="."&&m--,m>0){a=c.slice(0,m),o=c.slice(m+1);let A=a.indexOf(".Module");A>0&&(c=c.slice(A+1),a=a.slice(0,A))}f=void 0}o&&(f=a,u=o),o==="<anonymous>"&&(u=void 0,c=void 0),c===void 0&&(u=u||NOy,c=f?`${f}.${u}`:u);let s=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";return s?.match(/\/[A-Z]:/)&&(s=s.slice(1)),!s&&i[5]&&!l&&(s=i[5]),{filename:s?decodeURI(s):void 0,module:e?e(s):void 0,function:c,lineno:mOy(i[3]),colno:mOy(i[4]),in_app:e1C(s||"",l),platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function e1C(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 mOy(e){return parseInt(e||"",10)||void 0}function t1C(e){return[90,kjC(e)]}function r1C(e){let r=[t1C(e)].sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0)=>{let a=[],o=n.split(`
2431
- `);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let u=gOy.test(f)?f.replace(gOy,"$1"):f;if(!u.match(/\S*Error: /)){for(let s of r){let l=s(u);if(l){a.push(l);break}}if(a.length>=ROy)break}}return n1C(a)}}function n1C(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,ROy).map(r=>({...r,filename:r.filename||i1C(t).filename,function:r.function||NOy}))}function i1C(e){return e[e.length-1]||{}}hZa.stackParser=r1C(_jC());hZa.frameModifiers=[vjC];var vZa=class extends Umf{getLibraryId(){return"posthog-node"}};var NSu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new vZa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.107.7",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var JKo=class{async sendEvent(){}async identify(){}async flush(){}};var gZa=require("fs/promises"),QOy=require("os"),LOy=require("path");var FOy=$i(require("crypto")),xSu=new Uint8Array(256),FSu=xSu.length;function Gmf(){return FSu>xSu.length-16&&(FOy.default.randomFillSync(xSu),FSu=0),xSu.slice(FSu,FSu+=16)}var Hve=[];for(let e=0;e<256;++e)Hve.push((e+256).toString(16).slice(1));function xOy(e,t=0){return Hve[e[t+0]]+Hve[e[t+1]]+Hve[e[t+2]]+Hve[e[t+3]]+"-"+Hve[e[t+4]]+Hve[e[t+5]]+"-"+Hve[e[t+6]]+Hve[e[t+7]]+"-"+Hve[e[t+8]]+Hve[e[t+9]]+"-"+Hve[e[t+10]]+Hve[e[t+11]]+Hve[e[t+12]]+Hve[e[t+13]]+Hve[e[t+14]]+Hve[e[t+15]]}var zOy=$i(require("crypto")),Jmf={randomUUID:zOy.default.randomUUID};function a1C(e,t,r){if(Jmf.randomUUID&&!t&&!e)return Jmf.randomUUID();e=e||{};let n=e.random||(e.rng||Gmf)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return xOy(n)}var Irt=a1C;var o1C="id",s1C=".fern",KKo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new vZa(r),this.userId=t==null?void 0:f_f(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.107.7",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ql(L_.of((0,QOy.homedir)()),ru.of(s1C),ru.of(o1C));await Xv(t)||(await(0,gZa.mkdir)((0,LOy.dirname)(t),{recursive:!0}),await(0,gZa.writeFile)(t,Irt())),this.persistedDistinctId=(await(0,gZa.readFile)(t)).toString()}return this.persistedDistinctId}};var Kmf;async function mZa(){return Kmf==null&&(Kmf=await u1C()),Kmf}async function u1C(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new JKo;let r=await YOu();return r!=null?new KKo({token:r,posthogApiKey:e}):await mYa()!=null?new NSu({posthogApiKey:e}):new KKo({token:void 0,posthogApiKey:e})}catch{return new JKo}}function $Ko(e,t){return function(){return e.apply(t,arguments)}}var{toString:c1C}=Object.prototype,{getPrototypeOf:Ymf}=Object,{iterator:QSu,toStringTag:VOy}=Symbol,LSu=(e=>t=>{let r=c1C.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),zTr=e=>(e=e.toLowerCase(),t=>LSu(t)===e),USu=e=>t=>typeof t===e,{isArray:AZa}=Array,OZa=USu("undefined");function YKo(e){return e!==null&&!OZa(e)&&e.constructor!==null&&!OZa(e.constructor)&&rxe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var WOy=zTr("ArrayBuffer");function l1C(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&WOy(e.buffer),t}var f1C=USu("string"),rxe=USu("function"),HOy=USu("number"),XKo=e=>e!==null&&typeof e=="object",d1C=e=>e===!0||e===!1,zSu=e=>{if(LSu(e)!=="object")return!1;let t=Ymf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(VOy in e)&&!(QSu in e)},p1C=e=>{if(!XKo(e)||YKo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},_1C=zTr("Date"),h1C=zTr("File"),y1C=zTr("Blob"),v1C=zTr("FileList"),b1C=e=>XKo(e)&&rxe(e.pipe),g1C=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||rxe(e.append)&&((t=LSu(e))==="formdata"||t==="object"&&rxe(e.toString)&&e.toString()==="[object FormData]"))},m1C=zTr("URLSearchParams"),[O1C,A1C,P1C,w1C]=["ReadableStream","Request","Response","Headers"].map(zTr),j1C=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ZKo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),AZa(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(YKo(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function GOy(e,t){if(YKo(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var wua=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,JOy=e=>!OZa(e)&&e!==wua;function $mf(){let{caseless:e,skipUndefined:t}=JOy(this)&&this||{},r={},n=(i,a)=>{let o=e&&GOy(r,a)||a;zSu(r[o])&&zSu(i)?r[o]=$mf(r[o],i):zSu(i)?r[o]=$mf({},i):AZa(i)?r[o]=i.slice():(!t||!OZa(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&ZKo(arguments[i],n);return r}var E1C=(e,t,r,{allOwnKeys:n}={})=>(ZKo(t,(i,a)=>{r&&rxe(i)?e[a]=$Ko(i,r):e[a]=i},{allOwnKeys:n}),e),S1C=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),D1C=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},C1C=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Ymf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},I1C=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},M1C=e=>{if(!e)return null;if(AZa(e))return e;let t=e.length;if(!HOy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},B1C=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ymf(Uint8Array)),T1C=(e,t)=>{let n=(e&&e[QSu]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},q1C=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},R1C=zTr("HTMLFormElement"),N1C=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),UOy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),F1C=zTr("RegExp"),KOy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};ZKo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},x1C=e=>{KOy(e,(t,r)=>{if(rxe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(rxe(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},z1C=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return AZa(e)?n(e):n(String(e).split(t)),r},Q1C=()=>{},L1C=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function U1C(e){return!!(e&&rxe(e.append)&&e[VOy]==="FormData"&&e[QSu])}var V1C=e=>{let t=new Array(10),r=(n,i)=>{if(XKo(n)){if(t.indexOf(n)>=0)return;if(YKo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=AZa(n)?[]:{};return ZKo(n,(o,c)=>{let f=r(o,i+1);!OZa(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},W1C=zTr("AsyncFunction"),H1C=e=>e&&(XKo(e)||rxe(e))&&rxe(e.then)&&rxe(e.catch),$Oy=((e,t)=>e?setImmediate:t?((r,n)=>(wua.addEventListener("message",({source:i,data:a})=>{i===wua&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),wua.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",rxe(wua.postMessage)),G1C=typeof queueMicrotask<"u"?queueMicrotask.bind(wua):typeof process<"u"&&process.nextTick||$Oy,J1C=e=>e!=null&&rxe(e[QSu]),Zf={isArray:AZa,isArrayBuffer:WOy,isBuffer:YKo,isFormData:g1C,isArrayBufferView:l1C,isString:f1C,isNumber:HOy,isBoolean:d1C,isObject:XKo,isPlainObject:zSu,isEmptyObject:p1C,isReadableStream:O1C,isRequest:A1C,isResponse:P1C,isHeaders:w1C,isUndefined:OZa,isDate:_1C,isFile:h1C,isBlob:y1C,isRegExp:F1C,isFunction:rxe,isStream:b1C,isURLSearchParams:m1C,isTypedArray:B1C,isFileList:v1C,forEach:ZKo,merge:$mf,extend:E1C,trim:j1C,stripBOM:S1C,inherits:D1C,toFlatObject:C1C,kindOf:LSu,kindOfTest:zTr,endsWith:I1C,toArray:M1C,forEachEntry:T1C,matchAll:q1C,isHTMLForm:R1C,hasOwnProperty:UOy,hasOwnProp:UOy,reduceDescriptors:KOy,freezeMethods:x1C,toObjectSet:z1C,toCamelCase:N1C,noop:Q1C,toFiniteNumber:L1C,findKey:GOy,global:wua,isContextDefined:JOy,isSpecCompliantForm:U1C,toJSONObject:V1C,isAsyncFn:W1C,isThenable:H1C,setImmediate:$Oy,asap:G1C,isIterable:J1C};function PZa(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Zf.inherits(PZa,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:Zf.toJSONObject(this.config),code:this.code,status:this.status}}});var YOy=PZa.prototype,XOy={};["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=>{XOy[e]={value:e}});Object.defineProperties(PZa,XOy);Object.defineProperty(YOy,"isAxiosError",{value:!0});PZa.from=(e,t,r,n,i,a)=>{let o=Object.create(YOy);Zf.toFlatObject(e,o,function(s){return s!==Error.prototype},u=>u!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return PZa.call(o,c,f,r,n,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Qm=PZa;var ZOy=$i(ssa(),1),VSu=ZOy.default;function Xmf(e){return Zf.isPlainObject(e)||Zf.isArray(e)}function eAy(e){return Zf.endsWith(e,"[]")?e.slice(0,-2):e}function kOy(e,t,r){return e?e.concat(t).map(function(i,a){return i=eAy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function K1C(e){return Zf.isArray(e)&&!e.some(Xmf)}var $1C=Zf.toFlatObject(Zf,{},null,function(t){return/^is[A-Z]/.test(t)});function Y1C(e,t,r){if(!Zf.isObject(e))throw new TypeError("target must be an object");t=t||new(VSu||FormData),r=Zf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,I){return!Zf.isUndefined(I[C])});let n=r.metaTokens,i=r.visitor||s,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&Zf.isSpecCompliantForm(t);if(!Zf.isFunction(i))throw new TypeError("visitor must be a function");function u(P){if(P===null)return"";if(Zf.isDate(P))return P.toISOString();if(Zf.isBoolean(P))return P.toString();if(!f&&Zf.isBlob(P))throw new Qm("Blob is not supported. Use a Buffer instead.");return Zf.isArrayBuffer(P)||Zf.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function s(P,C,I){let T=P;if(P&&!I&&typeof P=="object"){if(Zf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Zf.isArray(P)&&K1C(P)||(Zf.isFileList(P)||Zf.endsWith(C,"[]"))&&(T=Zf.toArray(P)))return C=eAy(C),T.forEach(function(U,q){!(Zf.isUndefined(U)||U===null)&&t.append(o===!0?kOy([C],q,a):o===null?C:C+"[]",u(U))}),!1}return Xmf(P)?!0:(t.append(kOy(I,C,a),u(P)),!1)}let l=[],m=Object.assign($1C,{defaultVisitor:s,convertValue:u,isVisitable:Xmf});function A(P,C){if(!Zf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Zf.forEach(P,function(T,z){(!(Zf.isUndefined(T)||T===null)&&i.call(t,T,Zf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Zf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var h4i=Y1C;function tAy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function rAy(e,t){this._pairs=[],e&&h4i(e,this,t)}var nAy=rAy.prototype;nAy.append=function(t,r){this._pairs.push([t,r])};nAy.toString=function(t){let r=t?function(n){return t.call(this,n,tAy)}:tAy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var iAy=rAy;function X1C(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function jua(e,t,r){if(!t)return e;let n=r&&r.encode||X1C;Zf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Zf.isURLSearchParams(t)?t.toString():new iAy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Zmf=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Zf.forEach(this.handlers,function(n){n!==null&&t(n)})}},kmf=Zmf;var wZa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var uAy=$i(require("crypto"),1);var aAy=$i(require("url"),1),oAy=aAy.default.URLSearchParams;var eOf="abcdefghijklmnopqrstuvwxyz",sAy="0123456789",cAy={DIGIT:sAy,ALPHA:eOf,ALPHA_DIGIT:eOf+eOf.toUpperCase()+sAy},Z1C=(e=16,t=cAy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);uAy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},lAy={isNode:!0,classes:{URLSearchParams:oAy,FormData:VSu,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:cAy,generateString:Z1C,protocols:["http","https","file","data"]};var nOf={};yf(nOf,{hasBrowserEnv:()=>rOf,hasStandardBrowserEnv:()=>k1C,hasStandardBrowserWebWorkerEnv:()=>eEC,navigator:()=>tOf,origin:()=>tEC});var rOf=typeof window<"u"&&typeof document<"u",tOf=typeof navigator=="object"&&navigator||void 0,k1C=rOf&&(!tOf||["ReactNative","NativeScript","NS"].indexOf(tOf.product)<0),eEC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",tEC=rOf&&window.location.href||"http://localhost";var L7={...nOf,...lAy};function iOf(e,t){return h4i(e,new L7.classes.URLSearchParams,{visitor:function(r,n,i,a){return L7.isNode&&Zf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function rEC(e){return Zf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function nEC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function iEC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&Zf.isArray(i)?i.length:o,f?(Zf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Zf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Zf.isArray(i[o])&&(i[o]=nEC(i[o])),!c)}if(Zf.isFormData(e)&&Zf.isFunction(e.entries)){let r={};return Zf.forEachEntry(e,(n,i)=>{t(rEC(n),i,r,0)}),r}return null}var WSu=iEC;function aEC(e,t,r){if(Zf.isString(e))try{return(t||JSON.parse)(e),Zf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var aOf={transitional:wZa,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Zf.isObject(t);if(a&&Zf.isHTMLForm(t)&&(t=new FormData(t)),Zf.isFormData(t))return i?JSON.stringify(WSu(t)):t;if(Zf.isArrayBuffer(t)||Zf.isBuffer(t)||Zf.isStream(t)||Zf.isFile(t)||Zf.isBlob(t)||Zf.isReadableStream(t))return t;if(Zf.isArrayBufferView(t))return t.buffer;if(Zf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return iOf(t,this.formSerializer).toString();if((c=Zf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return h4i(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),aEC(t)):t}],transformResponse:[function(t){let r=this.transitional||aOf.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Zf.isResponse(t)||Zf.isReadableStream(t))return t;if(t&&Zf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Qm.from(c,Qm.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:L7.classes.FormData,Blob:L7.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Zf.forEach(["delete","get","head","post","put","patch"],e=>{aOf.headers[e]={}});var jZa=aOf;var oEC=Zf.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"]),fAy=e=>{let t={},r,n,i;return e&&e.split(`
2431
+ `);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let u=gOy.test(f)?f.replace(gOy,"$1"):f;if(!u.match(/\S*Error: /)){for(let s of r){let l=s(u);if(l){a.push(l);break}}if(a.length>=ROy)break}}return n1C(a)}}function n1C(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,ROy).map(r=>({...r,filename:r.filename||i1C(t).filename,function:r.function||NOy}))}function i1C(e){return e[e.length-1]||{}}hZa.stackParser=r1C(_jC());hZa.frameModifiers=[vjC];var vZa=class extends Umf{getLibraryId(){return"posthog-node"}};var NSu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new vZa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.107.8",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var JKo=class{async sendEvent(){}async identify(){}async flush(){}};var gZa=require("fs/promises"),QOy=require("os"),LOy=require("path");var FOy=$i(require("crypto")),xSu=new Uint8Array(256),FSu=xSu.length;function Gmf(){return FSu>xSu.length-16&&(FOy.default.randomFillSync(xSu),FSu=0),xSu.slice(FSu,FSu+=16)}var Hve=[];for(let e=0;e<256;++e)Hve.push((e+256).toString(16).slice(1));function xOy(e,t=0){return Hve[e[t+0]]+Hve[e[t+1]]+Hve[e[t+2]]+Hve[e[t+3]]+"-"+Hve[e[t+4]]+Hve[e[t+5]]+"-"+Hve[e[t+6]]+Hve[e[t+7]]+"-"+Hve[e[t+8]]+Hve[e[t+9]]+"-"+Hve[e[t+10]]+Hve[e[t+11]]+Hve[e[t+12]]+Hve[e[t+13]]+Hve[e[t+14]]+Hve[e[t+15]]}var zOy=$i(require("crypto")),Jmf={randomUUID:zOy.default.randomUUID};function a1C(e,t,r){if(Jmf.randomUUID&&!t&&!e)return Jmf.randomUUID();e=e||{};let n=e.random||(e.rng||Gmf)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return xOy(n)}var Irt=a1C;var o1C="id",s1C=".fern",KKo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new vZa(r),this.userId=t==null?void 0:f_f(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.107.8",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ql(L_.of((0,QOy.homedir)()),ru.of(s1C),ru.of(o1C));await Xv(t)||(await(0,gZa.mkdir)((0,LOy.dirname)(t),{recursive:!0}),await(0,gZa.writeFile)(t,Irt())),this.persistedDistinctId=(await(0,gZa.readFile)(t)).toString()}return this.persistedDistinctId}};var Kmf;async function mZa(){return Kmf==null&&(Kmf=await u1C()),Kmf}async function u1C(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new JKo;let r=await YOu();return r!=null?new KKo({token:r,posthogApiKey:e}):await mYa()!=null?new NSu({posthogApiKey:e}):new KKo({token:void 0,posthogApiKey:e})}catch{return new JKo}}function $Ko(e,t){return function(){return e.apply(t,arguments)}}var{toString:c1C}=Object.prototype,{getPrototypeOf:Ymf}=Object,{iterator:QSu,toStringTag:VOy}=Symbol,LSu=(e=>t=>{let r=c1C.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),zTr=e=>(e=e.toLowerCase(),t=>LSu(t)===e),USu=e=>t=>typeof t===e,{isArray:AZa}=Array,OZa=USu("undefined");function YKo(e){return e!==null&&!OZa(e)&&e.constructor!==null&&!OZa(e.constructor)&&rxe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var WOy=zTr("ArrayBuffer");function l1C(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&WOy(e.buffer),t}var f1C=USu("string"),rxe=USu("function"),HOy=USu("number"),XKo=e=>e!==null&&typeof e=="object",d1C=e=>e===!0||e===!1,zSu=e=>{if(LSu(e)!=="object")return!1;let t=Ymf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(VOy in e)&&!(QSu in e)},p1C=e=>{if(!XKo(e)||YKo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},_1C=zTr("Date"),h1C=zTr("File"),y1C=zTr("Blob"),v1C=zTr("FileList"),b1C=e=>XKo(e)&&rxe(e.pipe),g1C=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||rxe(e.append)&&((t=LSu(e))==="formdata"||t==="object"&&rxe(e.toString)&&e.toString()==="[object FormData]"))},m1C=zTr("URLSearchParams"),[O1C,A1C,P1C,w1C]=["ReadableStream","Request","Response","Headers"].map(zTr),j1C=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ZKo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),AZa(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(YKo(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function GOy(e,t){if(YKo(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var wua=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,JOy=e=>!OZa(e)&&e!==wua;function $mf(){let{caseless:e,skipUndefined:t}=JOy(this)&&this||{},r={},n=(i,a)=>{let o=e&&GOy(r,a)||a;zSu(r[o])&&zSu(i)?r[o]=$mf(r[o],i):zSu(i)?r[o]=$mf({},i):AZa(i)?r[o]=i.slice():(!t||!OZa(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&ZKo(arguments[i],n);return r}var E1C=(e,t,r,{allOwnKeys:n}={})=>(ZKo(t,(i,a)=>{r&&rxe(i)?e[a]=$Ko(i,r):e[a]=i},{allOwnKeys:n}),e),S1C=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),D1C=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},C1C=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Ymf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},I1C=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},M1C=e=>{if(!e)return null;if(AZa(e))return e;let t=e.length;if(!HOy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},B1C=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ymf(Uint8Array)),T1C=(e,t)=>{let n=(e&&e[QSu]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},q1C=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},R1C=zTr("HTMLFormElement"),N1C=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),UOy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),F1C=zTr("RegExp"),KOy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};ZKo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},x1C=e=>{KOy(e,(t,r)=>{if(rxe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(rxe(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},z1C=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return AZa(e)?n(e):n(String(e).split(t)),r},Q1C=()=>{},L1C=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function U1C(e){return!!(e&&rxe(e.append)&&e[VOy]==="FormData"&&e[QSu])}var V1C=e=>{let t=new Array(10),r=(n,i)=>{if(XKo(n)){if(t.indexOf(n)>=0)return;if(YKo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=AZa(n)?[]:{};return ZKo(n,(o,c)=>{let f=r(o,i+1);!OZa(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},W1C=zTr("AsyncFunction"),H1C=e=>e&&(XKo(e)||rxe(e))&&rxe(e.then)&&rxe(e.catch),$Oy=((e,t)=>e?setImmediate:t?((r,n)=>(wua.addEventListener("message",({source:i,data:a})=>{i===wua&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),wua.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",rxe(wua.postMessage)),G1C=typeof queueMicrotask<"u"?queueMicrotask.bind(wua):typeof process<"u"&&process.nextTick||$Oy,J1C=e=>e!=null&&rxe(e[QSu]),Zf={isArray:AZa,isArrayBuffer:WOy,isBuffer:YKo,isFormData:g1C,isArrayBufferView:l1C,isString:f1C,isNumber:HOy,isBoolean:d1C,isObject:XKo,isPlainObject:zSu,isEmptyObject:p1C,isReadableStream:O1C,isRequest:A1C,isResponse:P1C,isHeaders:w1C,isUndefined:OZa,isDate:_1C,isFile:h1C,isBlob:y1C,isRegExp:F1C,isFunction:rxe,isStream:b1C,isURLSearchParams:m1C,isTypedArray:B1C,isFileList:v1C,forEach:ZKo,merge:$mf,extend:E1C,trim:j1C,stripBOM:S1C,inherits:D1C,toFlatObject:C1C,kindOf:LSu,kindOfTest:zTr,endsWith:I1C,toArray:M1C,forEachEntry:T1C,matchAll:q1C,isHTMLForm:R1C,hasOwnProperty:UOy,hasOwnProp:UOy,reduceDescriptors:KOy,freezeMethods:x1C,toObjectSet:z1C,toCamelCase:N1C,noop:Q1C,toFiniteNumber:L1C,findKey:GOy,global:wua,isContextDefined:JOy,isSpecCompliantForm:U1C,toJSONObject:V1C,isAsyncFn:W1C,isThenable:H1C,setImmediate:$Oy,asap:G1C,isIterable:J1C};function PZa(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Zf.inherits(PZa,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:Zf.toJSONObject(this.config),code:this.code,status:this.status}}});var YOy=PZa.prototype,XOy={};["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=>{XOy[e]={value:e}});Object.defineProperties(PZa,XOy);Object.defineProperty(YOy,"isAxiosError",{value:!0});PZa.from=(e,t,r,n,i,a)=>{let o=Object.create(YOy);Zf.toFlatObject(e,o,function(s){return s!==Error.prototype},u=>u!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return PZa.call(o,c,f,r,n,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Qm=PZa;var ZOy=$i(ssa(),1),VSu=ZOy.default;function Xmf(e){return Zf.isPlainObject(e)||Zf.isArray(e)}function eAy(e){return Zf.endsWith(e,"[]")?e.slice(0,-2):e}function kOy(e,t,r){return e?e.concat(t).map(function(i,a){return i=eAy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function K1C(e){return Zf.isArray(e)&&!e.some(Xmf)}var $1C=Zf.toFlatObject(Zf,{},null,function(t){return/^is[A-Z]/.test(t)});function Y1C(e,t,r){if(!Zf.isObject(e))throw new TypeError("target must be an object");t=t||new(VSu||FormData),r=Zf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,I){return!Zf.isUndefined(I[C])});let n=r.metaTokens,i=r.visitor||s,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&Zf.isSpecCompliantForm(t);if(!Zf.isFunction(i))throw new TypeError("visitor must be a function");function u(P){if(P===null)return"";if(Zf.isDate(P))return P.toISOString();if(Zf.isBoolean(P))return P.toString();if(!f&&Zf.isBlob(P))throw new Qm("Blob is not supported. Use a Buffer instead.");return Zf.isArrayBuffer(P)||Zf.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function s(P,C,I){let T=P;if(P&&!I&&typeof P=="object"){if(Zf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Zf.isArray(P)&&K1C(P)||(Zf.isFileList(P)||Zf.endsWith(C,"[]"))&&(T=Zf.toArray(P)))return C=eAy(C),T.forEach(function(U,q){!(Zf.isUndefined(U)||U===null)&&t.append(o===!0?kOy([C],q,a):o===null?C:C+"[]",u(U))}),!1}return Xmf(P)?!0:(t.append(kOy(I,C,a),u(P)),!1)}let l=[],m=Object.assign($1C,{defaultVisitor:s,convertValue:u,isVisitable:Xmf});function A(P,C){if(!Zf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Zf.forEach(P,function(T,z){(!(Zf.isUndefined(T)||T===null)&&i.call(t,T,Zf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Zf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var h4i=Y1C;function tAy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function rAy(e,t){this._pairs=[],e&&h4i(e,this,t)}var nAy=rAy.prototype;nAy.append=function(t,r){this._pairs.push([t,r])};nAy.toString=function(t){let r=t?function(n){return t.call(this,n,tAy)}:tAy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var iAy=rAy;function X1C(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function jua(e,t,r){if(!t)return e;let n=r&&r.encode||X1C;Zf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Zf.isURLSearchParams(t)?t.toString():new iAy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Zmf=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Zf.forEach(this.handlers,function(n){n!==null&&t(n)})}},kmf=Zmf;var wZa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var uAy=$i(require("crypto"),1);var aAy=$i(require("url"),1),oAy=aAy.default.URLSearchParams;var eOf="abcdefghijklmnopqrstuvwxyz",sAy="0123456789",cAy={DIGIT:sAy,ALPHA:eOf,ALPHA_DIGIT:eOf+eOf.toUpperCase()+sAy},Z1C=(e=16,t=cAy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);uAy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},lAy={isNode:!0,classes:{URLSearchParams:oAy,FormData:VSu,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:cAy,generateString:Z1C,protocols:["http","https","file","data"]};var nOf={};yf(nOf,{hasBrowserEnv:()=>rOf,hasStandardBrowserEnv:()=>k1C,hasStandardBrowserWebWorkerEnv:()=>eEC,navigator:()=>tOf,origin:()=>tEC});var rOf=typeof window<"u"&&typeof document<"u",tOf=typeof navigator=="object"&&navigator||void 0,k1C=rOf&&(!tOf||["ReactNative","NativeScript","NS"].indexOf(tOf.product)<0),eEC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",tEC=rOf&&window.location.href||"http://localhost";var L7={...nOf,...lAy};function iOf(e,t){return h4i(e,new L7.classes.URLSearchParams,{visitor:function(r,n,i,a){return L7.isNode&&Zf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function rEC(e){return Zf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function nEC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function iEC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&Zf.isArray(i)?i.length:o,f?(Zf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Zf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Zf.isArray(i[o])&&(i[o]=nEC(i[o])),!c)}if(Zf.isFormData(e)&&Zf.isFunction(e.entries)){let r={};return Zf.forEachEntry(e,(n,i)=>{t(rEC(n),i,r,0)}),r}return null}var WSu=iEC;function aEC(e,t,r){if(Zf.isString(e))try{return(t||JSON.parse)(e),Zf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var aOf={transitional:wZa,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Zf.isObject(t);if(a&&Zf.isHTMLForm(t)&&(t=new FormData(t)),Zf.isFormData(t))return i?JSON.stringify(WSu(t)):t;if(Zf.isArrayBuffer(t)||Zf.isBuffer(t)||Zf.isStream(t)||Zf.isFile(t)||Zf.isBlob(t)||Zf.isReadableStream(t))return t;if(Zf.isArrayBufferView(t))return t.buffer;if(Zf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return iOf(t,this.formSerializer).toString();if((c=Zf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return h4i(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),aEC(t)):t}],transformResponse:[function(t){let r=this.transitional||aOf.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Zf.isResponse(t)||Zf.isReadableStream(t))return t;if(t&&Zf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Qm.from(c,Qm.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:L7.classes.FormData,Blob:L7.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Zf.forEach(["delete","get","head","post","put","patch"],e=>{aOf.headers[e]={}});var jZa=aOf;var oEC=Zf.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"]),fAy=e=>{let t={},r,n,i;return e&&e.split(`
2432
2432
  `).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||t[r]&&oEC[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var dAy=Symbol("internals");function kKo(e){return e&&String(e).trim().toLowerCase()}function HSu(e){return e===!1||e==null?e:Zf.isArray(e)?e.map(HSu):String(e)}function sEC(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var uEC=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function oOf(e,t,r,n,i){if(Zf.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Zf.isString(t)){if(Zf.isString(n))return t.indexOf(n)!==-1;if(Zf.isRegExp(n))return n.test(t)}}function cEC(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function lEC(e,t){let r=Zf.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,a,o){return this[n].call(this,t,i,a,o)},configurable:!0})})}var EZa=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(c,f,u){let s=kKo(f);if(!s)throw new Error("header name must be a non-empty string");let l=Zf.findKey(i,s);(!l||i[l]===void 0||u===!0||u===void 0&&i[l]!==!1)&&(i[l||f]=HSu(c))}let o=(c,f)=>Zf.forEach(c,(u,s)=>a(u,s,f));if(Zf.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(Zf.isString(t)&&(t=t.trim())&&!uEC(t))o(fAy(t),r);else if(Zf.isObject(t)&&Zf.isIterable(t)){let c={},f,u;for(let s of t){if(!Zf.isArray(s))throw TypeError("Object iterator must return a key-value pair");c[u=s[0]]=(f=c[u])?Zf.isArray(f)?[...f,s[1]]:[f,s[1]]:s[1]}o(c,r)}else t!=null&&a(r,t,n);return this}get(t,r){if(t=kKo(t),t){let n=Zf.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return sEC(i);if(Zf.isFunction(r))return r.call(this,i,n);if(Zf.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=kKo(t),t){let n=Zf.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||oOf(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(o){if(o=kKo(o),o){let c=Zf.findKey(n,o);c&&(!r||oOf(n,n[c],c,r))&&(delete n[c],i=!0)}}return Zf.isArray(t)?t.forEach(a):a(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let a=r[n];(!t||oOf(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return Zf.forEach(this,(i,a)=>{let o=Zf.findKey(n,a);if(o){r[o]=HSu(i),delete r[a];return}let c=t?cEC(a):String(a).trim();c!==a&&delete r[a],r[c]=HSu(i),n[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Zf.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Zf.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
2433
2433
  `)}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 n=new this(t);return r.forEach(i=>n.set(i)),n}static accessor(t){let n=(this[dAy]=this[dAy]={accessors:{}}).accessors,i=this.prototype;function a(o){let c=kKo(o);n[c]||(lEC(i,o),n[c]=!0)}return Zf.isArray(t)?t.forEach(a):a(t),this}};EZa.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Zf.reduceDescriptors(EZa.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Zf.freezeMethods(EZa);var _$=EZa;function e$o(e,t){let r=this||jZa,n=t||r,i=_$.from(n.headers),a=n.data;return Zf.forEach(e,function(c){a=c.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function t$o(e){return!!(e&&e.__CANCEL__)}function pAy(e,t,r){Qm.call(this,e??"canceled",Qm.ERR_CANCELED,t,r),this.name="CanceledError"}Zf.inherits(pAy,Qm,{__CANCEL__:!0});var Mrt=pAy;function bUr(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new Qm("Request failed with status code "+r.status,[Qm.ERR_BAD_REQUEST,Qm.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function sOf(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function uOf(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Eua(e,t,r){let n=!sOf(t);return e&&(n||r==!1)?uOf(e,t):t}var CAy=$i(dSu(),1),IAy=$i(require("http"),1),MAy=$i(require("https"),1),BAy=$i(require("util"),1),TAy=$i(cmf(),1),jAi=$i(require("zlib"),1);var Sua="1.12.2";function r$o(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var fEC=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function cOf(e,t,r){let n=r&&r.Blob||L7.classes.Blob,i=r$o(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=fEC.exec(e);if(!a)throw new Qm("Invalid URL",Qm.ERR_INVALID_URL);let o=a[1],c=a[2],f=a[3],u=Buffer.from(decodeURIComponent(f),c?"base64":"utf8");if(t){if(!n)throw new Qm("Blob is not supported",Qm.ERR_NOT_SUPPORT);return new n([u],{type:o})}return u}throw new Qm("Unsupported protocol "+i,Qm.ERR_NOT_SUPPORT)}var Cua=$i(require("stream"),1);var _Ay=$i(require("stream"),1);var lOf=Symbol("internals"),fOf=class extends _Ay.default.Transform{constructor(t){t=Zf.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Zf.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[lOf]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",n=>{n==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[lOf];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[lOf],a=i.maxRate,o=this.readableHighWaterMark,c=i.timeWindow,f=1e3/c,u=a/f,s=i.minChunkSize!==!1?Math.max(i.minChunkSize,u*.01):0,l=(A,P)=>{let C=Buffer.byteLength(A);i.bytesSeen+=C,i.bytes+=C,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(A)?process.nextTick(P):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(P)}},m=(A,P)=>{let C=Buffer.byteLength(A),I=null,T=o,z,U=0;if(a){let q=Date.now();(!i.ts||(U=q-i.ts)>=c)&&(i.ts=q,z=u-i.bytes,i.bytes=z<0?-z:0,U=0),z=u-i.bytes}if(a){if(z<=0)return setTimeout(()=>{P(null,A)},c-U);z<T&&(T=z)}T&&C>T&&C-T>s&&(I=A.subarray(T),A=A.subarray(0,T)),l(A,I?()=>{process.nextTick(P,null,I)}:P)};m(t,function A(P,C){if(P)return n(P);C?m(C,A):n(null)})}},dOf=fOf;var qAy=require("events");var yAy=$i(require("util"),1),vAy=require("stream");var{asyncIterator:hAy}=Symbol,dEC=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[hAy]?yield*e[hAy]():yield e},GSu=dEC;var pEC=L7.ALPHABET.ALPHA_DIGIT+"-_",n$o=typeof TextEncoder=="function"?new TextEncoder:new yAy.default.TextEncoder,Dua=`\r
2434
2434
  `,_EC=n$o.encode(Dua),hEC=2,pOf=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Zf.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${Dua}`;i?r=n$o.encode(String(r).replace(/\r?\n|\r\n?/g,Dua)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Dua}`,this.headers=n$o.encode(a+Dua),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+hEC,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Zf.isTypedArray(t)?yield t:yield*GSu(t),yield _EC}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},yEC=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+L7.generateString(i,pEC)}=r||{};if(!Zf.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=n$o.encode("--"+a+Dua),c=n$o.encode("--"+a+"--"+Dua),f=c.byteLength,u=Array.from(e.entries()).map(([l,m])=>{let A=new pOf(l,m);return f+=A.size,A});f+=o.byteLength*u.length,f=Zf.toFiniteNumber(f);let s={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(s["Content-Length"]=f),t&&t(s),vAy.Readable.from((async function*(){for(let l of u)yield o,yield*l.encode();yield c})())},bAy=yEC;var gAy=$i(require("stream"),1),_Of=class extends gAy.default.Transform{__transform(t,r,n){this.push(t),n()}_transform(t,r,n){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,r)}this.__transform(t,r,n)}},mAy=_Of;var vEC=(e,t)=>Zf.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(a){n(a)}},n)}:e,OAy=vEC;function bEC(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,a=0,o;return t=t!==void 0?t:1e3,function(f){let u=Date.now(),s=n[a];o||(o=u),r[i]=f,n[i]=u;let l=a,m=0;for(;l!==i;)m+=r[l++],l=l%e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),u-o<t)return;let A=s&&u-s;return A?Math.round(m*1e3/A):void 0}}var AAy=bEC;function gEC(e,t){let r=0,n=1e3/t,i,a,o=(u,s=Date.now())=>{r=s,i=null,a&&(clearTimeout(a),a=null),e(...u)};return[(...u)=>{let s=Date.now(),l=s-r;l>=n?o(u,s):(i=u,a||(a=setTimeout(()=>{a=null,o(i)},n-l)))},()=>i&&o(i)]}var PAy=gEC;var wAi=(e,t,r=3)=>{let n=0,i=AAy(50,250);return PAy(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,f=o-n,u=i(f),s=o<=c;n=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:f,rate:u||void 0,estimated:u&&c&&s?(c-o)/u:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},SZa=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},DZa=e=>(...t)=>Zf.asap(()=>e(...t));function hOf(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),n=e.slice(t+1);if(/;base64/i.test(r)){let a=n.length,o=n.length;for(let m=0;m<o;m++)if(n.charCodeAt(m)===37&&m+2<o){let A=n.charCodeAt(m+1),P=n.charCodeAt(m+2);(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102)&&(P>=48&&P<=57||P>=65&&P<=70||P>=97&&P<=102)&&(a-=2,m+=2)}let c=0,f=o-1,u=m=>m>=2&&n.charCodeAt(m-2)===37&&n.charCodeAt(m-1)===51&&(n.charCodeAt(m)===68||n.charCodeAt(m)===100);f>=0&&(n.charCodeAt(f)===61?(c++,f--):u(f)&&(c++,f-=3)),c===1&&f>=0&&(n.charCodeAt(f)===61||u(f))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(n,"utf8")}var wAy={flush:jAi.default.constants.Z_SYNC_FLUSH,finishFlush:jAi.default.constants.Z_SYNC_FLUSH},mEC={flush:jAi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:jAi.default.constants.BROTLI_OPERATION_FLUSH},jAy=Zf.isFunction(jAi.default.createBrotliDecompress),{http:OEC,https:AEC}=TAy.default,PEC=/https:?/,EAy=L7.protocols.map(e=>e+":"),SAy=(e,[t,r])=>(e.on("end",r).on("error",r),t);function wEC(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function RAy(e,t,r){let n=t;if(!n&&n!==!1){let i=CAy.default.getProxyForUrl(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));let a=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let i=n.hostname||n.host;e.hostname=i,e.host=i,e.port=n.port,e.path=r,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(a){RAy(a,t,a.href)}}var jEC=typeof process<"u"&&Zf.kindOf(process)==="process",EEC=e=>new Promise((t,r)=>{let n,i,a=(f,u)=>{i||(i=!0,n&&n(f,u))},o=f=>{a(f),t(f)},c=f=>{a(f,!0),r(f)};e(o,c,f=>n=f).catch(c)}),SEC=({address:e,family:t})=>{if(!Zf.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},DAy=(e,t)=>SEC(Zf.isObject(e)?e:{address:e,family:t}),NAy=jEC&&function(t){return EEC(async function(n,i,a){let{data:o,lookup:c,family:f}=t,{responseType:u,responseEncoding:s}=t,l=t.method.toUpperCase(),m,A=!1,P;if(c){let Se=OAy(c,jt=>Zf.isArray(jt)?jt:[jt]);c=(jt,bt,ze)=>{Se(jt,bt,(Me,Zt,dt)=>{if(Me)return ze(Me);let Ar=Zf.isArray(Zt)?Zt.map(Ft=>DAy(Ft)):[DAy(Zt,dt)];bt.all?ze(Me,Ar):ze(Me,Ar[0].address,Ar[0].family)})}}let C=new qAy.EventEmitter,I=()=>{t.cancelToken&&t.cancelToken.unsubscribe(T),t.signal&&t.signal.removeEventListener("abort",T),C.removeAllListeners()};a((Se,jt)=>{m=!0,jt&&(A=!0,I())});function T(Se){C.emit("abort",!Se||Se.type?new Mrt(null,t,P):Se)}C.once("abort",i),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(T),t.signal&&(t.signal.aborted?T():t.signal.addEventListener("abort",T)));let z=Eua(t.baseURL,t.url,t.allowAbsoluteUrls),U=new URL(z,L7.hasBrowserEnv?L7.origin:void 0),q=U.protocol||EAy[0];if(q==="data:"){if(t.maxContentLength>-1){let jt=String(t.url||z||"");if(hOf(jt)>t.maxContentLength)return i(new Qm("maxContentLength size of "+t.maxContentLength+" exceeded",Qm.ERR_BAD_RESPONSE,t))}let Se;if(l!=="GET")return bUr(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=cOf(t.url,u==="blob",{Blob:t.env&&t.env.Blob})}catch(jt){throw Qm.from(jt,Qm.ERR_BAD_REQUEST,t)}return u==="text"?(Se=Se.toString(s),(!s||s==="utf8")&&(Se=Zf.stripBOM(Se))):u==="stream"&&(Se=Cua.default.Readable.from(Se)),bUr(n,i,{data:Se,status:200,statusText:"OK",headers:new _$,config:t})}if(EAy.indexOf(q)===-1)return i(new Qm("Unsupported protocol "+q,Qm.ERR_BAD_REQUEST,t));let V=_$.from(t.headers).normalize();V.set("User-Agent","axios/"+Sua,!1);let{onUploadProgress:$,onDownloadProgress:re}=t,Y=t.maxRate,k,ne;if(Zf.isSpecCompliantForm(o)){let Se=V.getContentType(/boundary=([-_\w\d]{10,70})/i);o=bAy(o,jt=>{V.set(jt)},{tag:`axios-${Sua}-boundary`,boundary:Se&&Se[1]||void 0})}else if(Zf.isFormData(o)&&Zf.isFunction(o.getHeaders)){if(V.set(o.getHeaders()),!V.hasContentLength())try{let Se=await BAy.default.promisify(o.getLength).call(o);Number.isFinite(Se)&&Se>=0&&V.setContentLength(Se)}catch{}}else if(Zf.isBlob(o)||Zf.isFile(o))o.size&&V.setContentType(o.type||"application/octet-stream"),V.setContentLength(o.size||0),o=Cua.default.Readable.from(GSu(o));else if(o&&!Zf.isStream(o)){if(!Buffer.isBuffer(o))if(Zf.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(Zf.isString(o))o=Buffer.from(o,"utf-8");else return i(new Qm("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Qm.ERR_BAD_REQUEST,t));if(V.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return i(new Qm("Request body larger than maxBodyLength limit",Qm.ERR_BAD_REQUEST,t))}let Oe=Zf.toFiniteNumber(V.getContentLength());Zf.isArray(Y)?(k=Y[0],ne=Y[1]):k=ne=Y,o&&($||k)&&(Zf.isStream(o)||(o=Cua.default.Readable.from(o,{objectMode:!1})),o=Cua.default.pipeline([o,new dOf({maxRate:Zf.toFiniteNumber(k)})],Zf.noop),$&&o.on("progress",SAy(o,SZa(Oe,wAi(DZa($),!1,3)))));let he;if(t.auth){let Se=t.auth.username||"",jt=t.auth.password||"";he=Se+":"+jt}if(!he&&U.username){let Se=U.username,jt=U.password;he=Se+":"+jt}he&&V.delete("authorization");let me;try{me=jua(U.pathname+U.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Se){let jt=new Error(Se.message);return jt.config=t,jt.url=t.url,jt.exists=!0,i(jt)}V.set("Accept-Encoding","gzip, compress, deflate"+(jAy?", br":""),!1);let ve={path:me,method:l,headers:V.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:he,protocol:q,family:f,beforeRedirect:wEC,beforeRedirects:{}};!Zf.isUndefined(c)&&(ve.lookup=c),t.socketPath?ve.socketPath=t.socketPath:(ve.hostname=U.hostname.startsWith("[")?U.hostname.slice(1,-1):U.hostname,ve.port=U.port,RAy(ve,t.proxy,q+"//"+U.hostname+(U.port?":"+U.port:"")+ve.path));let Ce,Be=PEC.test(ve.protocol);if(ve.agent=Be?t.httpsAgent:t.httpAgent,t.transport?Ce=t.transport:t.maxRedirects===0?Ce=Be?MAy.default:IAy.default:(t.maxRedirects&&(ve.maxRedirects=t.maxRedirects),t.beforeRedirect&&(ve.beforeRedirects.config=t.beforeRedirect),Ce=Be?AEC:OEC),t.maxBodyLength>-1?ve.maxBodyLength=t.maxBodyLength:ve.maxBodyLength=1/0,t.insecureHTTPParser&&(ve.insecureHTTPParser=t.insecureHTTPParser),P=Ce.request(ve,function(jt){if(P.destroyed)return;let bt=[jt],ze=+jt.headers["content-length"];if(re||ne){let Ft=new dOf({maxRate:Zf.toFiniteNumber(ne)});re&&Ft.on("progress",SAy(Ft,SZa(ze,wAi(DZa(re),!0,3)))),bt.push(Ft)}let Me=jt,Zt=jt.req||P;if(t.decompress!==!1&&jt.headers["content-encoding"])switch((l==="HEAD"||jt.statusCode===204)&&delete jt.headers["content-encoding"],(jt.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":bt.push(jAi.default.createUnzip(wAy)),delete jt.headers["content-encoding"];break;case"deflate":bt.push(new mAy),bt.push(jAi.default.createUnzip(wAy)),delete jt.headers["content-encoding"];break;case"br":jAy&&(bt.push(jAi.default.createBrotliDecompress(mEC)),delete jt.headers["content-encoding"])}Me=bt.length>1?Cua.default.pipeline(bt,Zf.noop):bt[0];let dt=Cua.default.finished(Me,()=>{dt(),I()}),Ar={status:jt.statusCode,statusText:jt.statusMessage,headers:new _$(jt.headers),config:t,request:Zt};if(u==="stream")Ar.data=Me,bUr(n,i,Ar);else{let Ft=[],Xe=0;Me.on("data",function(cr){Ft.push(cr),Xe+=cr.length,t.maxContentLength>-1&&Xe>t.maxContentLength&&(A=!0,Me.destroy(),i(new Qm("maxContentLength size of "+t.maxContentLength+" exceeded",Qm.ERR_BAD_RESPONSE,t,Zt)))}),Me.on("aborted",function(){if(A)return;let cr=new Qm("stream has been aborted",Qm.ERR_BAD_RESPONSE,t,Zt);Me.destroy(cr),i(cr)}),Me.on("error",function(cr){P.destroyed||i(Qm.from(cr,null,t,Zt))}),Me.on("end",function(){try{let cr=Ft.length===1?Ft[0]:Buffer.concat(Ft);u!=="arraybuffer"&&(cr=cr.toString(s),(!s||s==="utf8")&&(cr=Zf.stripBOM(cr))),Ar.data=cr}catch(cr){return i(Qm.from(cr,null,t,Ar.request,Ar))}bUr(n,i,Ar)})}C.once("abort",Ft=>{Me.destroyed||(Me.emit("error",Ft),Me.destroy())})}),C.once("abort",Se=>{i(Se),P.destroy(Se)}),P.on("error",function(jt){i(Qm.from(jt,null,t,P))}),P.on("socket",function(jt){jt.setKeepAlive(!0,1e3*60)}),t.timeout){let Se=parseInt(t.timeout,10);if(Number.isNaN(Se)){i(new Qm("error trying to parse `config.timeout` to int",Qm.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(Se,function(){if(m)return;let bt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",ze=t.transitional||wZa;t.timeoutErrorMessage&&(bt=t.timeoutErrorMessage),i(new Qm(bt,ze.clarifyTimeoutError?Qm.ETIMEDOUT:Qm.ECONNABORTED,t,P)),T()})}if(Zf.isStream(o)){let Se=!1,jt=!1;o.on("end",()=>{Se=!0}),o.once("error",bt=>{jt=!0,P.destroy(bt)}),o.on("close",()=>{!Se&&!jt&&T(new Mrt("Request stream has been aborted",t,P))}),o.pipe(P)}else P.end(o)})};var FAy=L7.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,L7.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(L7.origin),L7.navigator&&/(msie|trident)/i.test(L7.navigator.userAgent)):()=>!0;var xAy=L7.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let o=[e+"="+encodeURIComponent(t)];Zf.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Zf.isString(n)&&o.push("path="+n),Zf.isString(i)&&o.push("domain="+i),a===!0&&o.push("secure"),document.cookie=o.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 zAy=e=>e instanceof _$?{...e}:e;function QTr(e,t){t=t||{};let r={};function n(u,s,l,m){return Zf.isPlainObject(u)&&Zf.isPlainObject(s)?Zf.merge.call({caseless:m},u,s):Zf.isPlainObject(s)?Zf.merge({},s):Zf.isArray(s)?s.slice():s}function i(u,s,l,m){if(Zf.isUndefined(s)){if(!Zf.isUndefined(u))return n(void 0,u,l,m)}else return n(u,s,l,m)}function a(u,s){if(!Zf.isUndefined(s))return n(void 0,s)}function o(u,s){if(Zf.isUndefined(s)){if(!Zf.isUndefined(u))return n(void 0,u)}else return n(void 0,s)}function c(u,s,l){if(l in t)return n(u,s);if(l in e)return n(void 0,u)}let f={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(u,s,l)=>i(zAy(u),zAy(s),l,!0)};return Zf.forEach(Object.keys({...e,...t}),function(s){let l=f[s]||i,m=l(e[s],t[s],s);Zf.isUndefined(m)&&l!==c||(r[s]=m)}),r}var JSu=e=>{let t=QTr({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=_$.from(o),t.url=jua(Eua(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Zf.isFormData(r)){if(L7.hasStandardBrowserEnv||L7.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(Zf.isFunction(r.getHeaders)){let f=r.getHeaders(),u=["content-type","content-length"];Object.entries(f).forEach(([s,l])=>{u.includes(s.toLowerCase())&&o.set(s,l)})}}if(L7.hasStandardBrowserEnv&&(n&&Zf.isFunction(n)&&(n=n(t)),n||n!==!1&&FAy(t.url))){let f=i&&a&&xAy.read(a);f&&o.set(i,f)}return t};var DEC=typeof XMLHttpRequest<"u",QAy=DEC&&function(e){return new Promise(function(r,n){let i=JSu(e),a=i.data,o=_$.from(i.headers).normalize(),{responseType:c,onUploadProgress:f,onDownloadProgress:u}=i,s,l,m,A,P;function C(){A&&A(),P&&P(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let I=new XMLHttpRequest;I.open(i.method.toUpperCase(),i.url,!0),I.timeout=i.timeout;function T(){if(!I)return;let U=_$.from("getAllResponseHeaders"in I&&I.getAllResponseHeaders()),V={data:!c||c==="text"||c==="json"?I.responseText:I.response,status:I.status,statusText:I.statusText,headers:U,config:e,request:I};bUr(function(re){r(re),C()},function(re){n(re),C()},V),I=null}"onloadend"in I?I.onloadend=T:I.onreadystatechange=function(){!I||I.readyState!==4||I.status===0&&!(I.responseURL&&I.responseURL.indexOf("file:")===0)||setTimeout(T)},I.onabort=function(){I&&(n(new Qm("Request aborted",Qm.ECONNABORTED,e,I)),I=null)},I.onerror=function(q){let V=q&&q.message?q.message:"Network Error",$=new Qm(V,Qm.ERR_NETWORK,e,I);$.event=q||null,n($),I=null},I.ontimeout=function(){let q=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",V=i.transitional||wZa;i.timeoutErrorMessage&&(q=i.timeoutErrorMessage),n(new Qm(q,V.clarifyTimeoutError?Qm.ETIMEDOUT:Qm.ECONNABORTED,e,I)),I=null},a===void 0&&o.setContentType(null),"setRequestHeader"in I&&Zf.forEach(o.toJSON(),function(q,V){I.setRequestHeader(V,q)}),Zf.isUndefined(i.withCredentials)||(I.withCredentials=!!i.withCredentials),c&&c!=="json"&&(I.responseType=i.responseType),u&&([m,P]=wAi(u,!0),I.addEventListener("progress",m)),f&&I.upload&&([l,A]=wAi(f),I.upload.addEventListener("progress",l),I.upload.addEventListener("loadend",A)),(i.cancelToken||i.signal)&&(s=U=>{I&&(n(!U||U.type?new Mrt(null,e,I):U),I.abort(),I=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));let z=r$o(i.url);if(z&&L7.protocols.indexOf(z)===-1){n(new Qm("Unsupported protocol "+z+":",Qm.ERR_BAD_REQUEST,e));return}I.send(a||null)})};var CEC=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,a=function(u){if(!i){i=!0,c();let s=u instanceof Error?u:this.reason;n.abort(s instanceof Qm?s:new Mrt(s instanceof Error?s.message:s))}},o=t&&setTimeout(()=>{o=null,a(new Qm(`timeout ${t} of ms exceeded`,Qm.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(a):u.removeEventListener("abort",a)}),e=null)};e.forEach(u=>u.addEventListener("abort",a));let{signal:f}=n;return f.unsubscribe=()=>Zf.asap(c),f}},LAy=CEC;var IEC=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let n=0,i;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},MEC=async function*(e,t){for await(let r of BEC(e))yield*IEC(r,t)},BEC=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},yOf=(e,t,r,n)=>{let i=MEC(e,t),a=0,o,c=f=>{o||(o=!0,n&&n(f))};return new ReadableStream({async pull(f){try{let{done:u,value:s}=await i.next();if(u){c(),f.close();return}let l=s.byteLength;if(r){let m=a+=l;r(m)}f.enqueue(new Uint8Array(s))}catch(u){throw c(u),u}},cancel(f){return c(f),i.return()}},{highWaterMark:2})};var UAy=64*1024,{isFunction:KSu}=Zf,TEC=(({Request:e,Response:t})=>({Request:e,Response:t}))(Zf.global),{ReadableStream:VAy,TextEncoder:WAy}=Zf.global,HAy=(e,...t)=>{try{return!!e(...t)}catch{return!1}},qEC=e=>{e=Zf.merge.call({skipUndefined:!0},TEC,e);let{fetch:t,Request:r,Response:n}=e,i=t?KSu(t):typeof fetch=="function",a=KSu(r),o=KSu(n);if(!i)return!1;let c=i&&KSu(VAy),f=i&&(typeof WAy=="function"?(P=>C=>P.encode(C))(new WAy):async P=>new Uint8Array(await new r(P).arrayBuffer())),u=a&&c&&HAy(()=>{let P=!1,C=new r(L7.origin,{body:new VAy,method:"POST",get duplex(){return P=!0,"half"}}).headers.has("Content-Type");return P&&!C}),s=o&&c&&HAy(()=>Zf.isReadableStream(new n("").body)),l={stream:s&&(P=>P.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(P=>{!l[P]&&(l[P]=(C,I)=>{let T=C&&C[P];if(T)return T.call(C);throw new Qm(`Response type '${P}' is not supported`,Qm.ERR_NOT_SUPPORT,I)})});let m=async P=>{if(P==null)return 0;if(Zf.isBlob(P))return P.size;if(Zf.isSpecCompliantForm(P))return(await new r(L7.origin,{method:"POST",body:P}).arrayBuffer()).byteLength;if(Zf.isArrayBufferView(P)||Zf.isArrayBuffer(P))return P.byteLength;if(Zf.isURLSearchParams(P)&&(P=P+""),Zf.isString(P))return(await f(P)).byteLength},A=async(P,C)=>{let I=Zf.toFiniteNumber(P.getContentLength());return I??m(C)};return async P=>{let{url:C,method:I,data:T,signal:z,cancelToken:U,timeout:q,onDownloadProgress:V,onUploadProgress:$,responseType:re,headers:Y,withCredentials:k="same-origin",fetchOptions:ne}=JSu(P),Oe=t||fetch;re=re?(re+"").toLowerCase():"text";let he=LAy([z,U&&U.toAbortSignal()],q),me=null,ve=he&&he.unsubscribe&&(()=>{he.unsubscribe()}),Ce;try{if($&&u&&I!=="get"&&I!=="head"&&(Ce=await A(Y,T))!==0){let Me=new r(C,{method:"POST",body:T,duplex:"half"}),Zt;if(Zf.isFormData(T)&&(Zt=Me.headers.get("content-type"))&&Y.setContentType(Zt),Me.body){let[dt,Ar]=SZa(Ce,wAi(DZa($)));T=yOf(Me.body,UAy,dt,Ar)}}Zf.isString(k)||(k=k?"include":"omit");let Be=a&&"credentials"in r.prototype,Se={...ne,signal:he,method:I.toUpperCase(),headers:Y.normalize().toJSON(),body:T,duplex:"half",credentials:Be?k:void 0};me=a&&new r(C,Se);let jt=await(a?Oe(me,ne):Oe(C,Se)),bt=s&&(re==="stream"||re==="response");if(s&&(V||bt&&ve)){let Me={};["status","statusText","headers"].forEach(Ft=>{Me[Ft]=jt[Ft]});let Zt=Zf.toFiniteNumber(jt.headers.get("content-length")),[dt,Ar]=V&&SZa(Zt,wAi(DZa(V),!0))||[];jt=new n(yOf(jt.body,UAy,dt,()=>{Ar&&Ar(),ve&&ve()}),Me)}re=re||"text";let ze=await l[Zf.findKey(l,re)||"text"](jt,P);return!bt&&ve&&ve(),await new Promise((Me,Zt)=>{bUr(Me,Zt,{data:ze,headers:_$.from(jt.headers),status:jt.status,statusText:jt.statusText,config:P,request:me})})}catch(Be){throw ve&&ve(),Be&&Be.name==="TypeError"&&/Load failed|fetch/i.test(Be.message)?Object.assign(new Qm("Network Error",Qm.ERR_NETWORK,P,me),{cause:Be.cause||Be}):Qm.from(Be,Be&&Be.code,P,me)}}},REC=new Map,vOf=e=>{let t=e?e.env:{},{fetch:r,Request:n,Response:i}=t,a=[n,i,r],o=a.length,c=o,f,u,s=REC;for(;c--;)f=a[c],u=s.get(f),u===void 0&&s.set(f,u=c?new Map:qEC(t)),s=u;return u},ZnU=vOf();var bOf={http:NAy,xhr:QAy,fetch:{get:vOf}};Zf.forEach(bOf,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var GAy=e=>`- ${e}`,FEC=e=>Zf.isFunction(e)||e===null||e===!1,$Su={getAdapter:(e,t)=>{e=Zf.isArray(e)?e:[e];let{length:r}=e,n,i,a={};for(let o=0;o<r;o++){n=e[o];let c;if(i=n,!FEC(n)&&(i=bOf[(c=String(n)).toLowerCase()],i===void 0))throw new Qm(`Unknown adapter '${c}'`);if(i&&(Zf.isFunction(i)||(i=i.get(t))))break;a[c||"#"+o]=i}if(!i){let o=Object.entries(a).map(([f,u])=>`adapter ${f} `+(u===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
@@ -2627,7 +2627,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
2627
2627
  1. you did not perform an installation for Firefox before running the script (e.g. \`npx puppeteer browsers install firefox\`) or
2628
2628
  2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
2629
2629
  For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n}};var Q7y=$i(require("fs"),1);var $kC={force:!0,recursive:!0,maxRetries:5};async function ERu(e){await Q7y.default.promises.rm(e,$kC)}var SRu=class extends Ito{constructor(t){super(t,"chrome")}launch(t={}){return this.puppeteer.configuration.logLevel==="warn"&&process.platform==="darwin"&&process.arch==="x64"&&W7y.default.cpus()[0]?.model.includes("Apple")&&console.warn(["\x1B[1m\x1B[43m\x1B[30m","Degraded performance warning:\x1B[0m\x1B[33m","Launching Chrome on Mac Silicon (arm64) from an x64 Node installation results in","Rosetta translating the Chrome binary, even if Chrome is already arm64. This would","result in huge performance issues. To resolve this, you must run Puppeteer with","a version of Node built for arm64."].join(`
2630
- `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:n=[],pipe:i=!1,debuggingPort:a,channel:o,executablePath:c}=t,f=[];r?Array.isArray(r)?f.push(...this.defaultArgs(t).filter(A=>!r.includes(A))):f.push(...n):f.push(...this.defaultArgs(t)),f.some(A=>A.startsWith("--remote-debugging-"))||(i?(ky(!a,"Browser should be launched with either pipe or debugging port - not both."),f.push("--remote-debugging-pipe")):f.push(`--remote-debugging-port=${a||0}`));let u=!1,s=f.findIndex(A=>A.startsWith("--user-data-dir"));s<0&&(u=!0,f.push(`--user-data-dir=${await(0,V7y.mkdtemp)(this.getProfilePath())}`),s=f.length-1);let l=f[s].split("=",2)[1];ky(typeof l=="string","`--user-data-dir` is malformed");let m=c;return m||(ky(o||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),m=o?this.executablePath(o):this.resolveExecutablePath(t.headless??!0)),{executablePath:m,args:f,isTempUserDataDir:u,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await ERu(t)}catch(n){throw Fv(n),n}}defaultArgs(t={}){let r=L7y("--disable-features",t.args);t.args&&r.length>0&&U7y(t.args,"--disable-features");let i=["Translate","AcceptCHFrame","MediaRouter","OptimizationHints","RenderDocument",...process.env.PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES==="true"?[]:["ProcessPerSiteUpToMainFrameThreshold","IsolateSandboxedIframes"],...r].filter(A=>A!==""),a=L7y("--enable-features",t.args);t.args&&a.length>0&&U7y(t.args,"--enable-features");let o=["PdfOopif",...a].filter(A=>A!==""),c=["--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-crash-reporter","--disable-default-apps","--disable-dev-shm-usage","--disable-hang-monitor","--disable-infobars","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-search-engine-choice-screen","--disable-sync","--enable-automation","--export-tagged-pdf","--force-color-profile=srgb","--generate-pdf-document-outline","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain",`--disable-features=${i.join(",")}`,`--enable-features=${o.join(",")}`].filter(A=>A!==""),{devtools:f=!1,headless:u=!f,args:s=[],userDataDir:l,enableExtensions:m=!1}=t;return l&&c.push(`--user-data-dir=${H7y.default.resolve(l)}`),f&&c.push("--auto-open-devtools-for-tabs"),u&&c.push(u==="shell"?"--headless":"--headless=new","--hide-scrollbars","--mute-audio"),c.push(m?"--enable-unsafe-extension-debugging":"--disable-extensions"),s.every(A=>A.startsWith("-"))&&c.push("about:blank"),c.push(...s),c}executablePath(t,r=!0){return t?ARu({browser:q1.CHROME,channel:YkC(t)}):this.resolveExecutablePath(void 0,r)}};function YkC(e){switch(e){case"chrome":return E3.STABLE;case"chrome-dev":return E3.DEV;case"chrome-beta":return E3.BETA;case"chrome-canary":return E3.CANARY}}function L7y(e,t=[]){return t.filter(r=>r.startsWith(e.endsWith("=")?e:`${e}=`)).map(r=>r.split(new RegExp(`${e}=\\s*`))[1]?.trim()).filter(r=>r)}function U7y(e,t){let r=new RegExp(`^${t}=.*`),n=0;for(;n<e.length;)r.test(e[n])?e.splice(n,1):n++;return e}var G7y=$i(require("fs"),1),Mto=require("fs/promises"),J7y=$i(require("os"),1),uBf=$i(require("path"),1);hI();F8();var DRu=class e extends Ito{constructor(t){super(t,"firefox")}static getPreferences(t){return{...t,"fission.webContentIsolationStrategy":0}}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:n=[],executablePath:i,pipe:a=!1,extraPrefsFirefox:o={},debuggingPort:c=null}=t,f=[];r?Array.isArray(r)?f.push(...this.defaultArgs(t).filter(A=>!r.includes(A))):f.push(...n):f.push(...this.defaultArgs(t)),f.some(A=>A.startsWith("--remote-debugging-"))||(a&&ky(c===null,"Browser should be launched with either pipe or debugging port - not both."),f.push(`--remote-debugging-port=${c||0}`));let u,s=!0,l=f.findIndex(A=>["-profile","--profile"].includes(A));if(l!==-1){if(u=f[l+1],!u)throw new Error("Missing value for profile command line argument");s=!1}else u=await(0,Mto.mkdtemp)(this.getProfilePath()),f.push("--profile"),f.push(u);await XMf(q1.FIREFOX,{path:u,preferences:e.getPreferences(o)});let m;return this.puppeteer._isPuppeteerCore||i?(ky(i,"An `executablePath` must be specified for `puppeteer-core`"),m=i):m=this.executablePath(void 0),{isTempUserDataDir:s,userDataDir:u,args:f,executablePath:m}}async cleanUserDataDir(t,r){if(r.isTemp)try{await ERu(t)}catch(n){throw Fv(n),n}else try{let n=".puppeteer",i=["prefs.js","user.js"],a=await Promise.allSettled(i.map(async o=>{let c=uBf.default.join(t,o+n);if(G7y.default.existsSync(c)){let f=uBf.default.join(t,o);await(0,Mto.unlink)(f),await(0,Mto.rename)(c,f)}}));for(let o of a)if(o.status==="rejected")throw o.reason}catch(n){Fv(n)}}executablePath(t,r=!0){return this.resolveExecutablePath(void 0,r)}defaultArgs(t={}){let{devtools:r=!1,headless:n=!r,args:i=[],userDataDir:a=null}=t,o=[];switch(J7y.default.platform()){case"darwin":o.push("--foreground");break;case"win32":o.push("--wait-for-browser");break}return a&&(o.push("--profile"),o.push(a)),n&&o.push("--headless"),r&&o.push("--devtools"),i.every(c=>c.startsWith("-"))&&o.push("about:blank"),o.push(...i),o}};var Bto=class extends jTu{#e;#t;defaultBrowserRevision;configuration={};constructor(t){let{configuration:r,...n}=t;switch(super(n),r&&(this.configuration=r),this.configuration.defaultBrowser){case"firefox":this.defaultBrowserRevision=Leo.firefox;break;default:this.configuration.defaultBrowser="chrome",this.defaultBrowserRevision=Leo.chrome;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.trimCache=this.trimCache.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{browser:r=this.defaultBrowser}=t;switch(this.#t=r,r){case"chrome":this.defaultBrowserRevision=Leo.chrome;break;case"firefox":this.defaultBrowserRevision=Leo.firefox;break;default:throw new Error(`Unknown product: ${r}`)}return this.#e=this.#r(r),this.#e.launch(t)}#r(t){if(this.#e&&this.#e.browser===t)return this.#e;switch(t){case"chrome":return new SRu(this);case"firefox":return new DRu(this);default:throw new Error(`Unknown product: ${t}`)}}executablePath(t){return t===void 0?this.#r(this.lastLaunchedBrowser).executablePath(void 0,!1):typeof t=="string"?this.#r("chrome").executablePath(t,!1):this.#r(t.browser??this.lastLaunchedBrowser).resolveExecutablePath(t.headless,!1)}get browserVersion(){return this.configuration?.[this.lastLaunchedBrowser]?.version??this.defaultBrowserRevision}get defaultDownloadPath(){return this.configuration.cacheDirectory}get lastLaunchedBrowser(){return this.#t??this.defaultBrowser}get defaultBrowser(){return this.configuration.defaultBrowser??"chrome"}get product(){return this.lastLaunchedBrowser}defaultArgs(t={}){return this.#r(t.browser??this.lastLaunchedBrowser).defaultArgs(t)}async trimCache(){let t=tqr();if(!t)throw new Error("The current platform is not supported.");let r=this.configuration.cacheDirectory,n=await sBf({cacheDir:r}),i=[{product:"chrome",browser:q1.CHROME,currentBuildId:""},{product:"firefox",browser:q1.FIREFOX,currentBuildId:""}];for(let c of i){let f=this.configuration?.[c.product]?.version??Leo[c.product];c.currentBuildId=await yRu(c.browser,t,f)}let a=new Set(i.map(c=>`${c.browser}_${c.currentBuildId}`)),o=new Set(i.map(c=>c.browser));for(let c of n)o.has(c.browser)&&(a.has(`${c.browser}_${c.buildId}`)||await oBf({browser:c.browser,platform:t,cacheDir:r,buildId:c.buildId}))}};var CRu=require("child_process"),Y7y=$i(require("fs"),1),X7y=$i(require("os"),1),Z7y=require("path"),k7y=require("stream"),e8y=$i(oee(),1);R_t();cxe();hI();dee();N8();var XkC=function(e,t,r){for(var n=arguments.length>2,i=0;i<t.length;i++)r=n?t[i].call(e,r):t[i].call(e);return n?r:void 0},K7y=function(e,t,r,n,i,a){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var c=n.kind,f=c==="getter"?"get":c==="setter"?"set":"value",u=!t&&e?n.static?e:e.prototype:null,s=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),l,m=!1,A=r.length-1;A>=0;A--){var P={};for(var C in n)P[C]=C==="access"?{}:n[C];for(var C in n.access)P.access[C]=n.access[C];P.addInitializer=function(T){if(m)throw new TypeError("Cannot add initializers after decoration has completed");a.push(o(T||null))};var I=(0,r[A])(c==="accessor"?{get:s.get,set:s.set}:s[f],P);if(c==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(l=o(I.get))&&(s.get=l),(l=o(I.set))&&(s.set=l),(l=o(I.init))&&i.unshift(l)}else(l=o(I))&&(c==="field"?i.unshift(l):s[f]=l)}u&&Object.defineProperty(u,n.name,s),m=!0},ZkC=function(e,t,r){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})},kkC=30,$7y=30,eeI=(0,e8y.default)("puppeteer:ffmpeg"),t8y=(()=>{let e=k7y.PassThrough,t=[],r,n,i;return class extends e{static{let o=typeof Symbol=="function"&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;K7y(this,n={value:ZkC(async function(c){let f=await new Promise(u=>{this.#t.stdin.write(c,u)});f&&console.log(`ffmpeg failed to write: ${f.message}.`)},"#writeFrame")},r,{kind:"method",name:"#writeFrame",static:!1,private:!0,access:{has:c=>#o in c,get:c=>c.#o},metadata:o},null,t),K7y(this,null,i,{kind:"method",name:"stop",static:!1,private:!1,access:{has:c=>"stop"in c,get:c=>c.stop},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}#e=XkC(this,t);#t;#r=new AbortController;#n;#i;constructor(o,c,f,{ffmpegPath:u,speed:s,scale:l,crop:m,format:A,fps:P,loop:C,delay:I,quality:T,colors:z,path:U,overwrite:q}={}){super({allowHalfOpen:!1}),u??="ffmpeg",A??="webm",P??=$7y,C||=-1,I??=-1,T??=kkC,z??=256,q??=!0,this.#i=P;let{error:V}=(0,CRu.spawnSync)(u);if(V)throw V;let $=[`crop='min(${c},iw):min(${f},ih):0:0'`,`pad=${c}:${f}:0:0`];s&&$.push(`setpts=${1/s}*PTS`),m&&$.push(`crop=${m.width}:${m.height}:${m.x}:${m.y}`),l&&$.push(`scale=iw*${l}:-1:flags=lanczos`);let re=this.#a(A,P,C,I,T,z),Y=re.indexOf("-vf");Y!==-1&&$.push(re.splice(Y,2).at(-1)??""),U&&Y7y.default.mkdirSync((0,Z7y.dirname)(U),{recursive:q}),this.#t=(0,CRu.spawn)(u,[["-loglevel","error"],["-avioflags","direct"],["-fpsprobesize","0","-probesize","32","-analyzeduration","0","-fflags","nobuffer"],["-f","image2pipe","-vcodec","png","-i","pipe:0"],["-an"],["-threads","1"],["-framerate",`${P}`],["-b:v","0"],re,["-vf",$.join()],[q?"-y":"-n"],"pipe:1"].flat(),{stdio:["pipe","pipe","pipe"]}),this.#t.stdout.pipe(this),this.#t.stderr.on("data",ne=>{eeI(ne.toString("utf8"))}),this.#e=o;let{client:k}=this.#e.mainFrame();k.once(Bx.Disconnected,()=>{this.stop().catch(Fv)}),this.#n=YTy(w3(k,"Page.screencastFrame").pipe(vca(ne=>{k.send("Page.screencastFrameAck",{sessionId:ne.sessionId})}),Qrt(ne=>ne.metadata.timestamp!==void 0),R8(ne=>({buffer:Buffer.from(ne.data,"base64"),timestamp:ne.metadata.timestamp})),tqy(2,1),rqy(([{timestamp:ne,buffer:Oe},{timestamp:he}])=>FI(Array(Math.round(P*Math.max(he-ne,0))).fill(Oe))),R8(ne=>(this.#o(ne),[ne,performance.now()])),vIu(Ska(this.#r.signal,"abort"))),{defaultValue:[Buffer.from([]),performance.now()]})}#a(o,c,f,u,s,l){let m=[["-vcodec","vp9"],["-crf",`${s}`],["-deadline","realtime","-cpu-used",`${Math.min(X7y.default.cpus().length/2,8)}`]];switch(o){case"webm":return[...m,["-f","webm"]].flat();case"gif":return c=$7y===c?20:"source_fps",f===1/0&&(f=0),u!==-1&&(u/=10),[["-vf",`fps=${c},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${l}[p];[s1][p]paletteuse=dither=bayer`],["-loop",`${f}`],["-final_delay",`${u}`],["-f","gif"]].flat();case"mp4":return[...m,["-movflags","hybrid_fragmented"],["-f","mp4"]].flat()}}get#o(){return n.value}async stop(){if(this.#r.signal.aborted)return;await this.#e._stopScreencast().catch(Fv),this.#r.abort();let[o,c]=await this.#n;await Promise.all(Array(Math.max(1,Math.round(this.#i*(performance.now()-c)/1e3))).fill(o).map(this.#o.bind(this))),this.#t.stdin.end(),await new Promise(f=>{this.#t.once("close",f)})}async[(r=[IYo()],i=[IYo()],lee)](){await this.stop()}}})();var r8y=$i(require("fs"),1),n8y=$i(require("path"),1);KAi();oCe.value={fs:r8y.default,path:n8y.default,ScreenRecorder:t8y};var reI=new Bto({isPuppeteerCore:!0}),{connect:OUU,defaultArgs:AUU,executablePath:PUU,launch:wUU}=reI;var ZQy=require("os"),kQy=require("path"),e5y=$i(XQy(),1);function CTf(e){let t=process.env[e];if(t!==void 0)switch(t.toLowerCase()){case"":case"0":case"false":case"off":return!1;default:return!0}}function $nI(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}function YnI(e){if(e&&!$nI(e))throw new Error(`Unsupported browser ${e}`);switch(e){case"firefox":return"firefox";default:return"chrome"}}function XnI(e){switch(e){case"silent":return"silent";case"error":return"error";default:return"warn"}}function DTf(e,t,r={}){if(t.skipDownload)return{skipDownload:!0};let n={},i=e.replaceAll("-","_").toUpperCase();return n.version=process.env[`PUPPETEER_${i}_VERSION`]??t[e]?.version??r.version,n.downloadBaseUrl=process.env[`PUPPETEER_${i}_DOWNLOAD_BASE_URL`]??t[e]?.downloadBaseUrl??r.downloadBaseUrl,n.skipDownload=CTf(`PUPPETEER_${i}_SKIP_DOWNLOAD`)??CTf(`PUPPETEER_SKIP_${i}_DOWNLOAD`)??t[e]?.skipDownload??r.skipDownload,n}var t5y=()=>{let e=(0,e5y.cosmiconfigSync)("puppeteer",{searchStrategy:"global"}).search(),t=e?e.config:{};return t.logLevel=XnI(process.env.PUPPETEER_LOGLEVEL??t.logLevel),t.defaultBrowser=YnI(process.env.PUPPETEER_BROWSER??t.defaultBrowser),t.executablePath=process.env.PUPPETEER_EXECUTABLE_PATH??t.executablePath,t.executablePath&&(t.skipDownload=!0),t.skipDownload=CTf("PUPPETEER_SKIP_DOWNLOAD")??t.skipDownload,t.chrome=DTf("chrome",t),t["chrome-headless-shell"]=DTf("chrome-headless-shell",t),t.firefox=DTf("firefox",t,{skipDownload:!0}),t.cacheDirectory=process.env.PUPPETEER_CACHE_DIR??t.cacheDirectory??(0,kQy.join)((0,ZQy.homedir)(),".cache","puppeteer"),t.temporaryDirectory=process.env.PUPPETEER_TMP_DIR??t.temporaryDirectory,t.experiments??={},t};var ZnI=t5y(),knI=new Bto({isPuppeteerCore:!1,configuration:ZnI}),{connect:rWU,defaultArgs:nWU,executablePath:iWU,launch:r5y,trimCache:aWU}=knI;var eiI="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",tiI={"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 pZo(e,t=3,r=1e3,n=2){try{return await e()}catch(i){if(t>0)return await new Promise(a=>setTimeout(a,r)),pZo(e,t-1,r*n,n);throw i}}async function n5y(){try{return await r5y({headless:!0,args:["--ignore-certificate-errors"]})}catch{throw new Error("Could not create a Puppeteer instance")}}async function riI(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(tiI),await r.setUserAgent(eiI),await r.setJavaScriptEnabled(!0),await pZo(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let n=await pZo(()=>r.content());return await r.close(),n}catch{throw new Error("Failed to download page from Puppeteer")}}async function niI(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 ITf({url:e,browser:t}){try{let r;if(t?r=await riI(t,e):r=await pZo(()=>niI(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function i5y(e){try{let t=await pZo(()=>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 iiI=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function a5y(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,Wto.join)(process.cwd(),"fern");try{let r=await aiI(e,(0,Wto.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function aiI(e,t){let r=siI(e),n=(0,Wto.join)(t,r);if(!oiI(r))throw new Error(`${r} - file extension not supported`);if((0,YRu.existsSync)(n))return n;try{(0,YRu.mkdirSync)((0,Wto.dirname)(n),{recursive:!0})}catch{throw new Error(`${n} - failed to create directory`)}try{let i=await i5y(e);return uBy(n,i),n}catch{throw new Error(`${n}: failed to download file from source`)}}function oiI(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let n=r.toLowerCase();return!(n&&!iiI.includes(n))}function siI(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 n=r.split("?");if(n.length===0)return"image";let i=n[0];return i&&decodeURIComponent(i.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function uiI(e){let t=[];return Vv(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 o5y(e,t){let r=jka(e),n=uiI(r);if(n!=null){let i=await Promise.all(n.map(async a=>{let o=await a5y(a.properties.src);return o.success&&o.data?o.data[1]:""}));t.push(...i)}for(let i=t.length-1;i>=0;i--)t[i]||t.splice(i,1)}var s5y=28;async function u5y(e,t){e=new URL(e);let r=[];if(t){let i=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),i.push(await a.content()),await a.click(".rm-ThemeToggle"),i.push(await a.content())}catch{}await Promise.all(i.map(async a=>await o5y(a,r)))}let n=[...new Set(r).values()];if(n.length!==0){if(n.length===1&&n[0]!=null){let i=ru.of(uAe(n[0]));return{light:i,dark:i,height:s5y}}if(n[0]!=null&&n[1]!=null){let i=ru.of(uAe(n[0])),a=ru.of(uAe(n[1]));return{light:i,dark:a,height:s5y}}}}var XRu=class extends Rua{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:O$o});let n=await this.getHastForUrl(this.url),i=mTy(n)??[];if(i.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${i.length} tabs:`);for(let s of i)this.logger.debug(` - Tab: ${s.name} (${s.url})`)}for(let s of i){let l=await this.scrapeTab({name:s.name,url:s.url});if(!l)continue;let m=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(s.name),tabConfig:{slug:s.url,displayName:s.name}}),A=Ql(this.absolutePathToFernDirectory,ru.of(this.kebabCaseWithoutEmojis(s.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:A,sections:l});let P=await this.getNavigationItems({absolutePathToOutputDirectory:A,sections:l});for(let C of P)m.addItem({item:C})}let a=await n5y(),o=await u5y(this.url,a);o!=null&&r.setLogo({logo:o});let c=await $Sy(n);r.setTitle({title:c});let f=await HSy(n);if(f!=null){let s=await this.getAndCreateAssetsDirectory(),l=await fetch(f);if(l.ok){let m=Buffer.from(await l.arrayBuffer()),A=Ql(s,ru.of("favicon"));await(0,S6i.writeFile)(A,new Uint8Array(m)),r.setFavicon({favicon:GNe(this.absolutePathToFernDirectory,A)})}}let u=await ATy(n);r.setColors({colors:u}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Ql(this.absolutePathToFernDirectory,ru.of("assets"));return await(0,S6i.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let n=new URL(r,this.url),i=await this.getHastForUrl(n),a=vTy(i);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let o=bTy(a);return this.logger.debug(`Successfully scraped tab: ${t}`),o}catch(n){this.logger.error(`Failed to scrape tab ${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.error(`Stack trace: ${n.stack}`)}}async getHastForUrl(t){let r=await ITf({url:t});return jka(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let n of r){this.logger.debug(`Processing section: ${n.group}`);let i=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n});await(0,S6i.mkdir)(i,{recursive:!0}),await Promise.all(n.pages.filter(a=>a.type==="page").map(async a=>{let o=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${o.toString()}`);let c=await ITf({url:o}),f=await yTy({logger:this.logger,html:c,url:o});if(f.success&&f.data){let u=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:i,page:a.slug});await(0,S6i.writeFile)(u,f.data.mdx),f.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${f.data.images.imageURLs.length} images to download for ${o.toString()}`),await Promise.all(Object.entries(f.data.images.imageURLToFilename).map(async([s,l])=>{try{let m=await fetch(s);if(!m.ok){this.logger.warn(`Failed to download image ${s}, status: ${m.status}`);return}let A=Buffer.from(await m.arrayBuffer()),P=Ql(i,ru.of(l)),C=Wg(P);await(0,S6i.mkdir)(C,{recursive:!0}),await(0,S6i.writeFile)(P,new Uint8Array(A)),this.logger.debug(`Saved image to ${P}`)}catch(m){this.logger.warn(`Error downloading image ${s}: ${m}`)}})))}else this.logger.warn(`Failed to parse page ${o.toString()}, skipping`)})),await Promise.all(n.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:i,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let n=[];for(let i of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i}),o={section:i.group,contents:[],slug:this.kebabCaseWithoutEmojis(i.group)};for(let c of i.pages)if(c.type==="page")o.contents.push({page:c.page,path:GNe(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let f=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});o.contents.push(...f)}n.push(o)}return n}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Ql(t,ru.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Ql(t,ru.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 c5y=require("fs/promises");async function MTf({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:n,organization:i}){let a=new Nua;a.setInstance({companyName:i}),await new XRu({url:e,context:r,builder:a,absolutePathToFernDirectory:Ql(L_.of(process.cwd()),ru.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,c5y.writeFile)(Ql(L_.of(t),ru.of(kye),ru.of(QNe)),JSON.stringify({version:n,organization:i},void 0,4))}var BTf=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:n})=>{if(!e||!Cia(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let i=L_.of(fV());await MTf({readmeUrl:e,outputPath:i,taskContext:r,versionOfCli:n,organization:t})};var l5y="0.0.0";var f5y={[tw.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,X9(e)])),[tw.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"]),[tw.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"]),[tw.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"]),[tw.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"]),[tw.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","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[tw.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"]),[tw.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"]),[tw.GenerationLanguage.SWIFT]:new Set([])};var liI=["go","ruby"];function _Ce({generationLanguage:e,keywords:t,smartCasing:r}){let n={generateName:(i,a)=>{let o=l=>({unsafeName:l,safeName:fiI({name:l,keywords:diI({generationLanguage:e,keywords:t})})}),c=$A(i),f=X9(c),u=Vna(i),s=zna(c);return r&&(!hiI(s)&&(e==null||liI.includes(e))&&(c=s.map((l,m)=>{if(m>0){let A=ZRu(l);if(A!=null)return A;if(kRu(l))return l.toUpperCase()}return l}).join(""),f=X9(s.map((l,m)=>{let A=ZRu(l);return A??(kRu(l)?l.toUpperCase():m===0?X9(l):l)}).join(""))),u=i.split(" ").map(l=>l.split(/(\d+)/).map(Vna).join("")).join("_")),{originalName:i,camelCase:o(a?.casingOverrides?.camel??c),snakeCase:o(a?.casingOverrides?.snake??u),screamingSnakeCase:o(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:o(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:i,wireValue:a,opts:o})=>({name:n.generateName(i,o),wireValue:a})};return n}function fiI({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":_iI(e)?"_"+e:e}function diI({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return f5y[e]}var piI=/^[0-9]/;function _iI(e){return piI.test(e)}function hiI(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=ZRu(n)!=null||kRu(n),a=ZRu(t)!=null||kRu(t);return i&&a})}function ZRu(e){return viI.get(e.toUpperCase())}function kRu(e){return yiI.has(e.toUpperCase())}var yiI=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"]),viI=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function TTf({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:BAe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return tsa(e.auth,{single:n=>{let i=d5y({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:BAe.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:BAe.Any,schemes:n.map(i=>d5y({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function d5y({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let n=(a,o)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return yGo(c,{header:f=>q7.header({key:a,docs:o,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:Mh.primitive({v1:yw.String,v2:l0.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>p5y({key:a,casingsGenerator:r,docs:o,rawScheme:f}),tokenBearer:f=>eNu({key:a,casingsGenerator:r,docs:o,rawScheme:f}),inferredBearer(f){return eNu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:f=>eNu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return eNu({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return p5y({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function eNu({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return q7.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function p5y({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return q7.basic({key:e,docs:r,username:t.generateName(n?.username?.name??"username"),usernameEnvVar:n?.username?.env,password:t.generateName(n?.password?.name??"password"),passwordEnvVar:n?.password?.env})}function ZX(e){let t=giI(e),{value:r,done:n}=qTf(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...biI(t)]}}function*biI(e){let t;do{let{value:r}=qTf(e,"}"),n=qTf(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*giI(e){for(let t of e)yield t}function qTf(e,t){let r="",n=e.next();for(;n.done!==!0&&n.value!==t;)r+=n.value,n=e.next();return{value:r,done:n.done??!1}}function _Zo({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:jLr(n,{singleBaseUrl:()=>mJ.singleBaseUrl(miI({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>mJ.multipleBaseUrls(OiI({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,a])=>[i,jLr(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function miI({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>jLr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:_5y(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function OiI({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>jLr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:Bg(a.urls,o=>_5y(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function _5y(e){return e.endsWith("/")?e.slice(0,-1):e}function D6i(e){let t=2166136261;function r(i,a){if(typeof i=="object"&&i!=null){if(a>64){n("[MaxDepthExceeded]");return}if(Array.isArray(i)){n("[");for(let o=0;o<i.length;o++)o>0&&n(","),r(i[o],a+1);n("]")}else n("{"),Object.keys(i).sort().forEach((c,f)=>{f>0&&n(","),n(c),n(":"),r(i[c],a+1)}),n("}")}else n(String(i))}function n(i){for(let a=0;a<i.length;a++){let o=i.charCodeAt(a);t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function oVr({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 h5y({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return sVr({containerType:t});switch(t.type){case"list":{let o=x8({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:fB.literal({literal:t.literal._visit({boolean:o=>b0.boolean(o),string:o=>b0.string({original:o}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:o=>o,string:o=>o,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return sVr({containerType:t});let o=x8({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return sVr({containerType:t});let o=x8({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=x8({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=x8({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),c=x8({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:ku(t)}}function sVr({containerType:e}){switch(e.type){case"list":return{type:"success",example:fB.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:fB.literal({literal:e.literal._visit({boolean:t=>b0.boolean(t),string:t=>b0.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:fB.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:fB.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:fB.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:fB.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:ku(e)}}function v5y({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return EiI({fieldName:e,default_:AiI(t.v2),validation:PiI(t.v2)});case"BASE_64":return{type:"success",example:b0.base64(FP.BASE64),jsonExample:FP.BASE64};case"BOOLEAN":return{type:"success",example:b0.boolean(FP.BOOLEAN),jsonExample:FP.BOOLEAN};case"DATE":return{type:"success",example:b0.date(FP.DATE),jsonExample:FP.DATE};case"DATE_TIME":return{type:"success",example:b0.datetime({datetime:new Date(FP.DATE_TIME),raw:FP.DATE_TIME}),jsonExample:FP.DATE_TIME};case"DOUBLE":return SiI({fieldName:e,validation:wiI(t.v2)});case"FLOAT":return{type:"success",example:b0.float(FP.FLOAT),jsonExample:FP.FLOAT};case"INTEGER":return DiI({fieldName:e,validation:jiI(t.v2)});case"UINT_64":return{type:"success",example:b0.uint64(FP.INT64),jsonExample:FP.INT64};case"UINT":return{type:"success",example:b0.uint(FP.UINT),jsonExample:FP.UINT};case"BIG_INTEGER":return{type:"success",example:b0.bigInteger(FP.INT64.toString()),jsonExample:`${FP.INT64}`};case"LONG":return{type:"success",example:b0.long(FP.INT64),jsonExample:FP.INT64};case"UUID":return{type:"success",example:b0.uuid(FP.UUID),jsonExample:FP.UUID};default:ku(t.v1)}}function AiI(e){if(e?.type==="string")return e.default}function PiI(e){if(e?.type==="string")return e.validation}function wiI(e){if(e?.type==="double")return e.validation}function jiI(e){if(e?.type==="integer")return e.validation}function y5y(e){if(e<=FP.SAMPLE_STRINGS.length){let t=FP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return FP.SAMPLE_STRINGS[FP.SAMPLE_STRINGS.length-1]+".".repeat(e-FP.SAMPLE_STRINGS.length)}function EiI({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:b0.string({original:t}),jsonExample:t};if(r){let i=r.minLength,a=r.maxLength;if(i){let o=y5y(i);return{type:"success",example:b0.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=y5y(a);return{type:"success",example:b0.string({original:o}),jsonExample:o}}}let n=e??FP.STRING;return{type:"success",example:b0.string({original:n}),jsonExample:n}}function SiI({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:b0.double(r),jsonExample:r};if(n)return{type:"success",example:b0.double(n),jsonExample:n}}return{type:"success",example:b0.double(FP.DOUBLE),jsonExample:FP.DOUBLE}}function DiI({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:b0.integer(r),jsonExample:r};if(n)return{type:"success",example:b0.integer(n),jsonExample:n}}return{type:"success",example:b0.integer(FP.INT),jsonExample:FP.INT}}function fla({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=x8({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:f}=o;return{type:"success",example:dN.alias({value:c}),jsonExample:f}}case"enum":{let o=r.shape.values[0];return o==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dN.enum({value:o.name}),jsonExample:o.name.wireValue}}case"object":{let o={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let m=t[l.typeId];if(m==null)continue;let A=fla({fieldName:e,typeDeclaration:m,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});A!=null&&A.type==="success"&&A.example.type==="object"&&(Object.assign(o,A.jsonExample),c.push(...A.example.properties))}let f=CiI({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:u,jsonExample:s}=f;return{type:"success",example:dN.object({properties:[...c,...u.properties],extraProperties:u.extraProperties}),jsonExample:Object.assign({},o,s)}}case"undiscriminatedUnion":{let o=0;for(let c of r.shape.members){let f=x8({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(f.type==="failure"){++o;continue}let{example:u,jsonExample:s}=f;return{type:"success",example:dN.undiscriminatedUnion({index:o,singleUnionType:u}),jsonExample:s}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let s of r.shape.baseProperties){let l=x8({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});l.type==="success"&&(c[s.name.wireValue]=l.jsonExample)}let f=r.shape.baseProperties.map(s=>{let l=x8({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(l.type==="failure")throw new Error(`Failed to generate example for union base property ${s.name.wireValue}`);let{example:m}=l;return{name:s.name,value:m}}),u=r.shape.extends.flatMap(s=>{let l=t[s.typeId];if(l==null)throw new Error(`Failed to find extended type declaration with id ${s.typeId}`);let m=fla({fieldName:e,typeDeclaration:l,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(m==null||m.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${l.name.typeId}`);if(m.example.type!=="object")throw new Error(`Extended type declaration ${l.name.typeId} is not an object`);return m.example.properties});for(let s of r.shape.types){let l=s.shape._visit({noProperties:()=>({type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.noProperties()},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,...c}}),samePropertiesAsObject:m=>{let A=t[m.typeId];if(A==null)return{type:"failure",message:`Failed to find type declaration with id ${m.typeId}`};let P=fla({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:A,typeDeclarations:t,skipOptionalProperties:a});if(P==null)return{type:"failure",message:"Failed to generate example for type reference"};if(P.type==="failure")return P;let{example:C,jsonExample:I}=P;return{type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.samePropertiesAsObject({typeId:A.name.typeId,object:C.type==="object"?C:{properties:[],extraProperties:void 0}})},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,...typeof I=="object"?I:{},...c}}},singleProperty:m=>{let A=x8({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:m.type,typeDeclarations:t,skipOptionalProperties:a});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;return{type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.singleProperty(P)},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,[m.name.wireValue]:C,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(l.type!=="failure")return l}}}return{type:"failure",message:"Failed to generate example for type reference"}}function CiI({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:o}){let c={},f=[];for(let u of[...r.properties??[],...r.extendedProperties??[]]){let s=x8({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:o});if(s.type==="failure"&&!oVr({typeDeclarations:n,typeReference:u.valueType}))return{type:"failure",message:`Failed to generate required property ${u.name.wireValue} b/c ${s.message}`};if(s.type==="failure")continue;let{example:l,jsonExample:m}=s;f.push({name:u.name,originalTypeDeclaration:t.name,value:l,propertyAccess:u.propertyAccess}),c[u.name.wireValue]=m}return{type:"success",example:dN.object({properties:f,extraProperties:void 0}),jsonExample:c}}function x8({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:`Exceeded max depth of ${n}`};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=fla({fieldName:e,typeDeclaration:o,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:f,jsonExample:u}=c;return{type:"success",example:{jsonExample:u,shape:nw.named({shape:f,typeName:o.name})},jsonExample:u}}case"container":{let o=h5y({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure"){let{example:u,jsonExample:s}=sVr({containerType:t.container});return{type:"success",example:{jsonExample:s,shape:nw.container(u)},jsonExample:s}}let{example:c,jsonExample:f}=o;return{type:"success",example:{jsonExample:f,shape:nw.container(c)},jsonExample:f}}case"primitive":{let{jsonExample:o,example:c}=v5y({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:nw.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:nw.unknown(o)},jsonExample:o}}}}function dla(e,t){let r=[];for(let n of e){let i=x8({fieldName:n.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function Hto(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&oVr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=x8({fieldName:n.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function tNu(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&oVr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=x8({fieldName:n.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,shape:n.allowMultiple?cse.exploded():cse.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var RTf=Mh.primitive({v1:yw.String,v2:l0.string({default:void 0,validation:void 0})});function Gto({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let o={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:K5.ok(iU.body(void 0)),docs:void 0},c=dla(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let f=dla(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;o.servicePathParameters=f.example;let u=dla(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;o.rootPathParameters=u.example;let s=tNu(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(s.type==="failure")return s;o.queryParameters=s.example;let l=Hto(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let m=Hto(r.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(m.type==="failure")return m;if(o.serviceHeaders=m.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 A={},P=[];if(t.requestBody.extends!=null)for(let C of t.requestBody.extends){let I=n[C.typeId];if(I==null)throw new Error(`Failed to find extended type declaration with id ${C.typeId}`);let T=fla({typeDeclaration:I,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});T!=null&&T.type==="success"&&Object.assign(A,T.jsonExample)}for(let C of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let I=x8({fieldName:C.name.wireValue,typeReference:C.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(I.type==="failure"&&!oVr({typeDeclarations:n,typeReference:C.valueType}))return{type:"failure",message:`Failed to generate required property ${C.name.wireValue} b/c ${I.message}`};if(I.type==="failure")continue;let{example:T,jsonExample:z}=I;P.push({name:C.name,originalTypeDeclaration:void 0,value:T}),A[C.name.wireValue]=z}o.request=RAe.inlinedRequestBody({jsonExample:A,properties:P,extraProperties:void 0});break}case"reference":{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.request=RAe.reference(P);break}default:ku(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 A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"streamParameter":{let A;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":A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1});break;default:ku(t.response.body.nonStreamResponse)}if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"streaming":{let A;switch(t.response.body.value.type){case"sse":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.sse([{data:{...P,jsonExample:C},event:""}]));break}case"json":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.stream([{...P,jsonExample:C}]));break}case"text":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.stream([{...P,jsonExample:C}]));break}default:ku(t.response.body.value)}break}case"text":{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:ku(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=K5.error({body:void 0,error:a.declaration.name});else{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.response=K5.error({body:P,error:a.declaration.name})}try{return{type:"success",example:{id:D6i(o),url:IiI(t,o),...o},jsonExample:void 0}}catch(A){return{type:"failure",message:`Parse failure with exceptions ${A}`}}}function IiI(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=o});let n=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function NTf({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=dla(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(a.type==="failure")return a;i.pathParameters.push(...a.example);let o=dla(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let c=tNu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(c.type==="failure")return c;i.queryParameters=c.example;let f=Hto(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;i.headers.push(...f.example);let u=Hto(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(u.type==="failure")return u;i.headers.push(...u.example);let l=t.messages.filter(P=>P.origin==="client")[0];if(l!=null){let P=b5y({message:l,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:l.type,body:P})}let A=t.messages.filter(P=>P.origin==="server")[0];if(A!=null){let P=b5y({message:A,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:A.type,body:P})}return{type:"success",example:{...i,url:MiI(t,i)},jsonExample:void 0}}function b5y({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=x8({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return grt.reference(n.example)}function MiI(e,t){let r={};[...t.pathParameters].forEach(i=>{let a=i.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=o});let n=e.path.head+e.path.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function Jto(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function C6i(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function g5y({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let n=e.types,i={pathParameters:{},queryParameters:{},headers:{}};for(let o of t.pathParameters){let{userExample:c,autoExample:f}=Jto(o.v2Examples);c!==void 0?i.pathParameters[o.name.originalName]=c:f!==void 0&&(i.pathParameters[o.name.originalName]=f)}for(let o of t.queryParameters){let{userExample:c,autoExample:f}=Jto(o.v2Examples);if(c!==void 0)i.queryParameters[o.name.name.originalName]=c;else if(f!==void 0){if(r&&oVr({typeReference:o.valueType,typeDeclarations:n}))continue;i.queryParameters[o.name.name.originalName]=f}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let o of a){let{userExample:c,autoExample:f}=Jto(o.v2Examples);if(c!==void 0)i.headers[o.name.wireValue]=c;else if(f!==void 0){if(r&&oVr({typeReference:o.valueType,typeDeclarations:n}))continue;i.headers[o.name.wireValue]=f}}return i}function m5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:a}=g5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},f={endpoint:{method:e.method,path:BiI(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:i,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}case"inlinedRequestBody":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}case"reference":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}default:ku(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:f}}function BiI(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:a}=Jto(n.v2Examples),o=i??a,c;o==null?c=n.name.originalName:c=typeof o=="string"?o:JSON.stringify(o),t[n.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${t[n.pathParameter]}`)+n.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function rNu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,n={},i={},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:Mne.json(hZo(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let o=r.body,{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?hZo(s):s;n[u]={...a,body:Mne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?hZo(s):s;i[u]={...a,body:Mne.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?hZo(s):s;n[u]={...a,body:Mne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?hZo(s):s;i[u]={...a,body:Mne.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c))n[u]={...a,body:Mne.stream([s])};for(let[u,s]of Object.entries(f))i[u]={...a,body:Mne.stream([s])}}break}case"streamParameter":break;default:ku(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:a}}function hZo(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var Kto=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},TiI=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function nNu({key:e,displayName:t,request:r,response:n,exampleStore:i,userOrAutoStore:a}){if(!i.has(e)){let o={displayName:t,request:r,response:n,codeSamples:void 0};return a[e]=o,TiI({exampleStore:i,key:e,example:o}),!0}return!1}function O5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let n={},i={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:f}=m5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u=Object.keys(o)[0],s=Object.values(o)[0],l=Object.keys(c)[0],m=Object.values(c)[0],A=qiI({endpoint:e,userRequestExamples:o,baseRequestExample:f,firstUserRequestName:u,firstUserRequestExample:s,firstAutoRequestName:l,firstAutoRequestExample:m,userResults:n,autoResults:i,exampleStore:a});if(RiI({endpoint:e,userRequestExamples:o,requestExamplesUsed:A,userResults:n,exampleStore:a}),Object.keys(n).length===0&&Object.keys(i).length===0){let{baseExample:P}=rNu({endpoint:e}),C=Kto(l??"base","base",void 0);nNu({key:C,displayName:l??"base",request:m??f,response:P,exampleStore:a,userOrAutoStore:i})}return{userFullExamples:n,autoFullExamples:i}}function qiI({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:n,firstUserRequestExample:i,firstAutoRequestName:a,firstAutoRequestExample:o,userResults:c,autoResults:f,exampleStore:u}){let s=e.v2Responses?.responses??[e.response],l=new Set;for(let m of s){let A=!1,{userResponseExamples:P,autoResponseExamples:C,baseExample:I}=rNu({endpoint:e,responseObject:m}),T=Object.keys(C)[0],z=Object.values(C)[0];for(let[U,q]of Object.entries(P)){let V,$;t[U]?($=t[U],l.add(U),V=Kto(U,U,m?.statusCode)):o&&a?($=o,V=Kto(a,U,m?.statusCode)):($=r,V=Kto("base",U,m?.statusCode)),nNu({key:V,displayName:U,request:$,response:q,exampleStore:u,userOrAutoStore:c})&&(A=!0)}if(!A){let U=$A(`${e.name.originalName}_example`);n&&i&&l.add(n);let q=Kto(n??a??"base",T??"base",m?.statusCode);nNu({key:q,displayName:n??a??U,request:i??o??r,response:z??I,exampleStore:u,userOrAutoStore:f})&&(A=!0)}}return l}function RiI({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=rNu({endpoint:e}),f=Object.values(a)[0],u=Object.keys(a)[0],s=Object.keys(o)[0],l=Object.values(o)[0],m=Object.entries(t).filter(([A])=>!r.has(A));for(let[A,P]of m){let C=Kto(A,u??s??"base",f?f.statusCode:l?l.statusCode:c.statusCode);nNu({key:C,displayName:A,request:P,response:f??l??c,exampleStore:i,userOrAutoStore:n})}}function yZo({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){let o=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=Gto({ir:e,service:i,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&o.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 f=e.errors[c.error.errorId];if(!f)continue;let u=Gto({ir:e,service:i,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:f}});u.type==="success"&&o.push({example:u.example})}a.autogeneratedExamples=o}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=NTf({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;i.examples=[...i.examples,o]}return e}function FTf({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:o,autoFullExamples:c}=O5y({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(u=>u.request!=null||u.response!=null))continue;let f=Object.values(a.v2Examples.userSpecifiedExamples).filter(u=>u!=null).flatMap(u=>u.codeSamples??[]);for(let[u,s]of Object.entries(c))c[u]={...s,codeSamples:f};for(let[u,s]of Object.entries(o))o[u]={...s,codeSamples:f}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=o}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=NTf({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;i.examples=[...i.examples,o]}return e}function P5y({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:b$({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?tee.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=b$({filteredIr:e,exampleTypeReference:r});return n!==void 0?tee.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function b$({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:nw.container(fB.list({...n,list:n.list.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:nw.container(fB.set({...n,set:n.set.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?b$({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:nw.container(fB.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?b$({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:nw.container(fB.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:nw.container(fB.map({...n,map:n.map.map(i=>{let a=b$({filteredIr:e,exampleTypeReference:i.key}),o=b$({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&o!==void 0?{key:a,value:o}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=b$({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:nw.named({...r,shape:dN.enum(n)})}),object:n=>({...t,shape:nw.named({...r,shape:dN.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:b$({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=P5y({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=b$({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function xTf({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function NiI({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function A5y({filteredIr:e,headers:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function FiI({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=b$({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=b$({filteredIr:e,exampleTypeReference:r});return n!==void 0?RAe.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function xiI({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>K5.ok(iU.body(n!=null?b$({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>K5.ok(iU.stream(n.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(pj))),sse:n=>K5.ok(iU.sse(n.map(({event:i,data:a})=>{let o=b$({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:i,data:o}:void 0}).filter(pj))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>K5.error({error:r,body:n!=null?b$({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function zTf({filteredIr:e,example:t}){return{...t,rootPathParameters:xTf({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:xTf({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:xTf({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:A5y({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:A5y({filteredIr:e,headers:t.endpointHeaders}),queryParameters:NiI({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?FiI({filteredIr:e,requestBody:t.request}):void 0,response:xiI({filteredIr:e,response:t.response})}}function w5y({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dN.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dN.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:b$({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=P5y({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dN.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=b$({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dN.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function QTf(e,t){if(t==null)return e;let r=Una(e.types,c=>t.hasType(c)),n=Object.fromEntries(Object.entries(r).map(([c,f])=>{let u=[];if(f.userProvidedExamples=f.userProvidedExamples.map(s=>w5y({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),f.shape.type==="object"){for(let s of f.shape.properties)t.hasProperty(c,s.name.wireValue)&&u.push(s);return[c,{...f,shape:YE.object({...f.shape,properties:u})}]}return[c,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,f])=>{let u=f.filter(s=>t.hasWebhook(s)).map(s=>{let l=s.id;return s.payload.type==="inlinedPayload"&&l!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(m=>t.hasWebhookPayloadProperty(l,m.name.wireValue))}),s});return[c,u]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,f])=>[c,{...f}])):{},o=e.environments;if(o){switch(o.environments.type){case"singleBaseUrl":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}o.defaultEnvironment&&(t.hasEnvironmentId(o.defaultEnvironment)||(o.defaultEnvironment=void 0))}return{...e,environments:o,types:n,errors:Una(e.errors,c=>t.hasError(c)),services:Bg(Una(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(u=>({...u,example:zTf({filteredIr:t,example:u.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?zTf({filteredIr:t,example:u.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(u=>t.hasQueryParameter(f.id,u.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(u=>t.hasRequestProperty(f.id,u.name.wireValue))}}:f))})),websocketChannels:a,webhookGroups:i,serviceTypeReferenceInfo:ziI(e.serviceTypeReferenceInfo,t)}}function ziI(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}function pla(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Krt(e){return e.allParts.map(t=>t.originalName).join("/")}var pB={generateTypeId:e=>`type_${Krt(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${Krt(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${Krt(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${Krt(e)}`,generateSubpackageId:e=>`subpackage_${Krt(e)}`,generateEndpointId:(e,t)=>{let r=Krt(e.fernFilepath),n=t.name.originalName;return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${Krt(e)}`,generateWebhookId:(e,t)=>`webhooks_${Krt(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${Krt(e)}`};function $to(e){return e.type!=null}var iNu=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:n,environments:i,services:a,endpoints:o,webhooks:c,subpackages:f,queryParameters:u,requestProperties:s,webhookPayloadProperties:l,channels:m}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=o,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=f,this.requestProperties=s,this.queryParameters=u,this.channels=m}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=pB.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=pB.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=pB.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var _la=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=QiI(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let o=pB.generateTypeId(t),c={typeId:o,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[o]=c,this.typesReferencedByService[o]==null&&(this.typesReferencedByService[o]=new Set),this.properties[o]={typeId:o,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=pB.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){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=pB.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&TJ(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=pB.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,f=new Set;for(let u of[...t.headers,...r.headers])TJ(u.valueType,o,f);for(let u of[...t.pathParameters,...r.pathParameters])TJ(u.valueType,o,f);for(let u of r.queryParameters)TJ(u.valueType,o,f);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=pla(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:u}}r.requestBody!=null&&R7._visit(r.requestBody,{inlinedRequestBody:u=>{for(let s of u.extends)aNu(s,o,f);for(let s of u.properties)TJ(s.valueType,o,f);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&rU(n.request.body)){let s=pla(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:s}}},reference:({requestBodyType:u})=>{TJ(u,o,f)},fileUpload:({properties:u})=>{for(let s of u)Bne._visit(s,{file:xc,bodyProperty:({valueType:l})=>{TJ(l,o,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+s.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&fN._visit(r.response.body,{fileDownload:xc,json:u=>{TJ(u.responseBodyType,o,f)},streaming:u=>{u._visit({sse:s=>TJ(s.payload,o,f),json:s=>TJ(s.payload,o,f),text:xc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:s=>TJ(s.payload,o,f),json:s=>TJ(s.payload,o,f),text:xc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&TJ(u.nonStreamResponse.value.responseBodyType,o,f)},text:xc,bytes:xc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{c.add(pB.generateErrorId(u.error)),f.add(u.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:i,referencedTypes:o,referencedErrors:c,referencedSubpackages:f}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=pB.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let o=a.id;this.endpointsNeededForAudience.add(o),this.endpoints[o]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(i),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,n){let i=r.id;if(i==null)return;let a=new Set,o=new Set;r.payload!=null&&Cve._visit(r.payload,{inlinedPayload:c=>{for(let f of c.extends)aNu(f,a,o);for(let f of c.properties)TJ(f.valueType,a,o);if(n?.payload!=null&&typeof n.payload=="object"&&!$to(n.payload)){let f=pla(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:f}}},reference:({payloadType:c})=>{TJ(c,a,o)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),o.add(t),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:o}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t))}addChannel(t,r,n,i){if(r==null)return;let a=new Set,o=new Set;for(let c of n.messages)Dfe._visit(c.body,{reference:({bodyType:f})=>{TJ(f,a,o)},inlinedBody:f=>{for(let u of f.extends)aNu(u,a,o);for(let u of f.properties)TJ(u.valueType,a,o)},_other:()=>{}});for(let c of n.queryParameters)TJ(c.valueType,a,o);o.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:o}}markChannelForAudiences(t,r,n){r!=null&&this.hasAudience(n)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(c);for(let u of f.referencedErrors){if(r.has(u))continue;r.add(u);let s=this.getErrorNode(u);this.addReferencedTypes(t,s.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(c);this.addReferencedTypes(t,f.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(c);this.addReferencedTypes(t,f.referencedTypes)}let n={},i={},a={},o={};if(this.audiences.type==="filtered"){for(let[c,f]of Object.entries(this.properties)){if(!t.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}u.size>0&&(n[c]=u),n[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}i[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.parametersByAudience[s];l?.forEach(m=>{u.add(m)})}a[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}o[c]=u.size>0?u:void 0}}return new iNu({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:o,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t]??=new Set;if(n.has(r))return;n.add(r);let i=this.getTypeNode(t);for(let a of i.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let o=i.descendantsByAudience[a];if(o!=null)o.forEach(c=>{t.add(c)});else{i.allDescendants.forEach(c=>{t.add(c)});break}}else i.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}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(n=>r.audiences.has(n));default:ku(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(pB.generateSubpackageId(n))}}};function QiI(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:ku(e)}}function TJ(e,t,r){Mh._visit(e,{container:n=>{LiI(n,t,r)},named:n=>{aNu(n,t,r)},primitive:xc,unknown:xc,_other:xc})}function aNu(e,t,r){t.add(pB.generateTypeId(e)),r.add(e.fernFilepath)}function LiI(e,t,r){Xw._visit(e,{list:n=>{TJ(n,t,r)},map:n=>{TJ(n.keyType,t,r),TJ(n.valueType,t,r)},optional:n=>{TJ(n,t,r)},nullable:n=>{TJ(n,t,r)},set:n=>{TJ(n,t,r)},literal:xc,_other:xc})}var UiI=[np.AvailabilityStatus.GeneralAvailability];function bPi(e){return e!==void 0&&!UiI.includes(e.status)}var LTf=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},vZo=class{errors;constructor(){this.errors=new LTf}async check({from:t,to:r}){let n=this.toInternalIr(t),i=this.toInternalIr(r),a=D6i(n),o=D6i(i);if(a===o)return{bump:"no_change",isBreaking:!1,errors:[]};let c=this.checkBreaking({from:n,to:i});return{bump:c.isBreaking?"major":"minor",isBreaking:c.isBreaking,errors:c.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}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 n=this.errors.hasErrors();return{bump:n?"major":"minor",isBreaking:n,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(bPi(i.availability))continue;let a=r[n];if(!a){this.errors.add(`Type "${n}" was removed.`);continue}if(bPi(a.availability)){this.errors.add(`Type "${n}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:i,to:a})||this.errors.add(`Type "${n}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){let a=Object.values(r).find(o=>o.name.errorId===i.name.errorId);if(!a){this.errors.add(`Error "${i.name.errorId}" with status code "${i.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:i,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[n,i]of Object.entries(t)){if(bPi(i.availability)||(i.endpoints?.every(o=>bPi(o.availability))??!1))continue;let a=r[n];if(!a){this.errors.add(`Service "${n}" was removed.`);continue}if(bPi(a.availability)){this.errors.add(`Service "${n}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:n,from:i,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:n}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:n})}checkEndpointsBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.endpoints.map(o=>[o.id,o])),a=Object.fromEntries(n.endpoints.map(o=>[o.id,o]));for(let[o,c]of Object.entries(i)){if(bPi(c.availability))continue;let f=a[o];if(!f){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(bPi(f.availability)){this.errors.add(`Endpoint "${o}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:o,from:c,to:f})}}checkEndpointBreakingChanges({id:t,from:r,to:n}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:n.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:n.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:n.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:n.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),r.requestBody!=null&&(n.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:n.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(n.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:n.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&n.pagination==null||r.pagination==null&&n.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.originalName,o])),a=Object.fromEntries(n.map(o=>[o.name.originalName,o]));for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Path parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Path parameter "${o}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(n.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Query parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Query parameter "${o}" type changed in endpoint "${t}".`),c.allowMultiple!==f.allowMultiple&&this.errors.add(`Query parameter "${o}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(n.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Header "${o}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Header "${o}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:n}){r!==n&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:n}){this.areHttpPathsCompatible({from:r,to:n})||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 n=0;n<t.parts.length;n++){let i=t.parts[n];if(i==null)return!1;let a=r.parts[n];if(a==null||i.pathParameter!==a.pathParameter||i.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:n}){switch(r.type){case"inlinedRequestBody":if(n.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:n}))return;break;case"reference":if(n.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:n}))return;break;case"fileUpload":if(n.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:n}))return;break;case"bytes":if(n.type==="bytes")return;break;default:ku(r)}this.errors.add(`Request body type changed from "${r.type}" to "${n.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let n=this.getInlinedRequestBody(t),i=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:n,to:i}),Object.entries(n).every(([a,o])=>{let c=i[a];return c?this.areTypeReferencesCompatible({from:o,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 n=this.getFileUploadRequest(t.properties),i=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:n,to:i});for(let[a,o]of Object.entries(n)){let c=i[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(o==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o!=="file"&&o!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:o,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:n}){if(r.statusCode!==n.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${n.statusCode}".`),!(r.body==null&&n.body==null)){if(r.body==null||n.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(n.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"fileDownload":if(n.body.type==="fileDownload")return;break;case"text":if(n.body.type==="text")return;break;case"bytes":if(n.body.type==="bytes")return;break;case"streaming":if(n.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"streamParameter":if(n.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:n.body.streamResponse});return}break;default:ku(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${n.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:ku(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bPi(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:ku(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 n=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),i=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(n).length!==Object.keys(i).length?!1:Object.values(n).every(a=>{let o=i[a.name.wireValue];return o?this.areNameAndWireValuesCompatible({from:a.name,to:o.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let n=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),i=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(n).map(([a,o])=>[a,o.valueType])),to:Object.fromEntries(Object.entries(i).map(([a,o])=>[a,o.valueType]))}),Object.values(n).every(a=>{let o=i[a.name.wireValue];return o?this.areObjectPropertiesCompatible({from:a,to:o}):(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 n=new Set(t.extends.map(u=>this.getKeyForDeclaration(u))),i=new Set(r.extends.map(u=>this.getKeyForDeclaration(u)));for(let u of n)if(!i.has(u))return this.errors.add(`Extended type "${u}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(u=>[u.name.wireValue,u])),o=Object.fromEntries(r.baseProperties.map(u=>[u.name.wireValue,u]));for(let u of Object.values(a)){let s=o[u.name.wireValue];if(!s)return this.errors.add(`Union type with discriminant value "${u.name.wireValue}" no longer has a property named "${u.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:u,to:s}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([u,s])=>[u,s.valueType])),to:Object.fromEntries(Object.entries(o).map(([u,s])=>[u,s.valueType]))});let c=Object.fromEntries(t.types.map(u=>[u.discriminantValue.wireValue,u])),f=Object.fromEntries(r.types.map(u=>[u.discriminantValue.wireValue,u]));return Object.values(c).every(u=>{let s=f[u.discriminantValue.wireValue];return s?this.areSingleUnionTypesCompatible({from:u.shape,to:s.shape}):(this.errors.add(`Union type for discriminant value "${u.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:ku(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((n,i)=>{let a=r.members[i];return a?this.areTypeReferencesCompatible({from:n.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${i} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||i==="file"||i==="fileArray"||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" 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:ku(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:ku(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:ku(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((n,i)=>{let a=r.allParts[i];return a==null?!1:this.areNamesCompatible({from:n,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let n of[...t.extendedProperties??[],...t.properties])r[n.name.wireValue]=n.valueType;return r}getFileUploadRequest(t){let r={};for(let n of t)switch(n.type){case"file":r[n.value.key.wireValue]="file";break;case"bodyProperty":r[n.name.wireValue]=n.valueType;break;default:ku(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>i.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function hla(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:a}=WiI(e.environments,t.environments,r),{services:o,websocketChannels:c}=HiI(e,t,i,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:n,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:o,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:ViI(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(f=>!e.rootPackage.subpackages?.includes(f))],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??[]],generationMetadata:e.generationMetadata??t.generationMetadata}}function ViI(e,t){let r=e;for(let[n,i]of Object.entries(t))r[n]==null?r[n]=i:r[n]={name:i.name,displayName:i.displayName,fernFilepath:i.fernFilepath,hasEndpointsInTree:r[n].hasEndpointsInTree||i.hasEndpointsInTree,navigationConfig:r[n].navigationConfig??i.navigationConfig,docs:r[n].docs??i.docs,service:r[n].service??i.service,subpackages:[...r[n].subpackages??[],...(i.subpackages??[]).filter(a=>!r[n]?.subpackages?.includes(a))],webhooks:r[n].webhooks??i.webhooks,websocket:r[n].websocket??i.websocket,errors:[...r[n].errors??[],...i.errors??[]],types:[...r[n].types??[],...i.types??[]]};return r}function WiI(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 n=j5y(e),i=j5y(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:mJ.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=n?t.defaultEnvironment:e.defaultEnvironment,o=e.environments,c=t.environments;if(o.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let f=n?c:o,u=n?o:c,s={},{deconflictedEnvironments2:l,changedBaseUrlIds2:m}=GiI(f,u,r);if(f.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let A="Base",P=r.generateName("Base");return f.environments.forEach(C=>{s[C.id]=A}),{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[{id:A,name:P},...l.environments.map(C=>({id:C.id,name:C.name}))],environments:f.environments.map(C=>({id:C.id,name:C.name,urls:{[A]:C.url,...Object.fromEntries(l.environments.map(I=>[I.id,I.url]))},docs:void 0}))})},changedBaseUrlIds1:n?m:s,changedBaseUrlIds2:n?s:m}}if(o.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||o.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let f=o.type==="singleBaseUrl"?o:c,u=o.type==="multipleBaseUrls"?o:c,{deconflictedEnvironments1:s,changedBaseUrlIds1:l}=JiI(f,u,r);return{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[...u.baseUrls,...s.environments.map(m=>({id:m.id,name:m.name}))],environments:u.environments.map(m=>({...m,urls:{...m.urls,...Object.fromEntries(s.environments.map(A=>[A.id,A.url]))}}))})},changedBaseUrlIds1:o.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:o.type==="singleBaseUrl"?void 0:l}}if(o.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:f,changedBaseUrlIds:u}=KiI(o,c,r);return{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[...o.baseUrls,...f.baseUrls],environments:o.environments.flatMap(s=>f.environments.map(l=>({...s,urls:{...s.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:u}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function HiI(e,t,r,n){if(r!=null)for(let[o,c]of Object.entries(r)){for(let f of Object.values(e.services))for(let u of Object.values(f.endpoints))u.baseUrl==o&&(u.baseUrl=c),u.v2BaseUrls?.includes(o)&&(u.v2BaseUrls=u.v2BaseUrls.map(s=>s===o?c:s));for(let f of Object.values(e.websocketChannels??{}))f.baseUrl==o&&(f.baseUrl=c)}if(n!=null)for(let[o,c]of Object.entries(n)){for(let f of Object.values(t.services))for(let u of Object.values(f.endpoints))u.baseUrl==o&&(u.baseUrl=c),u.v2BaseUrls?.includes(o)&&(u.v2BaseUrls=u.v2BaseUrls.map(s=>s===o?c:s));for(let f of Object.values(t.websocketChannels??{}))f.baseUrl==o&&(f.baseUrl=c)}let i=e.services;for(let[o,c]of Object.entries(t.services))i[o]==null?i[o]=c:i[o]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...i[o].endpoints??[],...c.endpoints],pathParameters:[...i[o].pathParameters??[],...c.pathParameters??[]],headers:[...i[o].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...i[o].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:i,websocketChannels:a}}function GiI(e,t,r){let n={},i=new Set(e.environments.map(u=>u.id)),a=new Set(e.environments.map(u=>u.name)),o=new Map(e.environments.map(u=>[u.url,u.id])),c=t.environments.filter(u=>{let s=o.get(u.url);return s!=null?(n[u.id]=s,!1):!0}).map(u=>{if(i.has(u.id)||a.has(u.name)){let s=UTf(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u});return{deconflictedEnvironments2:mJ.singleBaseUrl({environments:c}),changedBaseUrlIds2:n}}function JiI(e,t,r){let n={},i=new Set(t.baseUrls.map(f=>f.id)),a=new Set(t.baseUrls.map(f=>f.name)),o=e.environments.map(f=>{if(i.has(f.id)||a.has(f.name)){let u=UTf(f.id,i);return n[f.id]=u,{...f,id:u,name:r.generateName(u)}}return f});return{deconflictedEnvironments1:mJ.singleBaseUrl({environments:o}),changedBaseUrlIds1:n}}function KiI(e,t,r){let n={},i=new Set(e.baseUrls.map(u=>u.id)),a=new Set(e.baseUrls.map(u=>u.name)),o=t.baseUrls.map(u=>{if(i.has(u.id)||a.has(u.name)){let s=UTf(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u}),c=t.environments.map(u=>({...u,urls:Object.fromEntries(Object.entries(u.urls).map(([s,l])=>[n[s]??s,l]))}));return{deconflictedEnvironments:mJ.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:n}}function j5y(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 UTf(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}var gO=class e{breadcrumbs=[];context;static STRING=np.TypeReference.primitive({v1:"STRING",v2:np.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=np.TypeReference.container(np.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var S5y=require("fs/promises");var VTf=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:n,position:i,lineStart:a}=t;this._map[r]={line:n,position:i,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,a=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:o,position:c,lineStart:f}=r;this._path.length===0?this._map["."+n]={line:o,position:c,lineStart:f}:this._fragments.push({path:this._path.join(".")+"."+n,line:o,position:c,lineStart:f})}else if(i==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,f=>{c++,!((!f.children||f.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(f,f.path):(o.children.push({...f,path:f.path.slice(a.length+1)}),o.line=f.line,o.position=f.position,o.lineStart=f.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(i==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,f=n.length;this.iterFragments(a,u=>{c.has(u.position)||(f--,c.add(u.position),this._path.length===1?this.resolveNode(u,`${a}.${f}`):(o.children.push({...u,path:f.toString()}),o.line=u.line,o.position=u.position,o.lineStart=u.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:a}=r;this._map["."]={line:n,position:i,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},E5y=VTf;var gPi;(function(e){e.WARNING="warning",e.ERROR="error"})(gPi||(gPi={}));var I6i=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new WTf({logger:t,relativePathToFile:ru.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let a=i.path?i.path.join("->"):"",o=`${i.message}|${i.level||gPi.WARNING}|${a}`;r.has(o)?n++:(r.add(o),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===gPi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gPi.WARNING&&!t))switch(r.level){case gPi.ERROR:if(this.logger.log(oE.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),i=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(oE.Debug,` - at location (${i})`)}break}}},WTf=class{logger;relativePathToFile;map=new E5y;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,S5y.readFile)(this.relativePathToFile,"utf-8");jg.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(oE.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 hee=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=_Ce({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((i,a)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||a===0&&i==="components"||a===1&&i==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(i)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=$A(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:gPi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[o]}return i==null?(n||this.errorCollector.collect({level:gPi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}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,n,i=!1,a=null,o;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),s=u[0];if(n=u[1],!s)return{resolved:!1};o=s;let l=await fetch(s);if(!l.ok)return{resolved:!1};try{let m=await l.text();try{a=JSON.parse(m),r=a}catch{a=jg.load(m),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let c=n??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let f=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of f){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,u,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,n,i));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(n.has(o))return t;n.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(n.delete(o),c.resolved)return c.value}else{let c=`${i}${o}`;if(n.has(c))return t;n.add(c);let f=r,u=o.substring(2).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~"));for(let s of u){if(typeof f!="object"||f===null)return t;f=f[s]}if(f!=null){let s=await this.resolveNestedExternalReferences(f,r,n,i);return n.delete(o),s}n.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,n,i):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let a=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([a,t.example])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.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:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return yLr.ReadOnly;if(i)return yLr.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let a=i;if(this.isReferenceObject(i)){let c=this.resolveReference({reference:i});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,n=n&&o.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new Sse.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let i=new Sse.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:Ine.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Mh.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(([n])=>n!==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 n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}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||"summary"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 n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var UD=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}};var Sse={};yf(Sse,{AudienceExtension:()=>oNu,FernAvailabilityExtension:()=>sNu,FernEnumExtension:()=>uNu,FernIgnoreExtension:()=>yla,FernOptionalExtension:()=>cNu,FernTypeExtension:()=>pNu,FernTypeNameExtension:()=>_Nu,SdkGroupNameExtension:()=>lNu,SdkMethodNameExtension:()=>fNu,ServerFromOperationNameExtension:()=>dNu});var oNu=class extends UD{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var sNu=class extends UD{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),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 Ine.InDevelopment;case"PRE_RELEASE":case"BETA":return Ine.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return Ine.GeneralAvailability;case"DEPRECATED":return Ine.Deprecated;default:return}}};var $iI=nl.object({snake:nl.string().optional(),camel:nl.string().optional(),screamingSnake:nl.string().optional(),pascal:nl.string().optional()}),YiI=nl.object({description:nl.string().optional(),name:nl.string().optional(),casing:$iI.optional()}),D5y=nl.record(YiI);var uNu=class extends UD{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=D5y.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 yla=class extends UD{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),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 cNu=class extends UD{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),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 lNu=class extends UD{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var fNu=class extends UD{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var dNu=class extends UD{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var pNu=class extends UD{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var _Nu=class extends UD{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var rqr=class extends gO{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new _la(n),this.ir={auth:{docs:void 0,requirement:np.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:np.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,generationMetadata:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new yla({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new yla({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):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,n=FTf({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let i=yZo({ir:t,exampleGeneration:r});return{...t,...i,...n}}return{...t,...n}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>n.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>i.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),a=await this.context.resolveMaybeExternalReference(n);if(a.resolved){if(n=a.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:a}){let o=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:n}),f=[...o].map(l=>this.context.casingsGenerator.generateName(l)),u=f[f.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>$A(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:f,finalpart:u,endpointGroupDisplayName:i})),this.ir.services[c.service]?.endpoints.push(t);let s=this.ir.services[c.service];s!=null&&(this.irGraph.addEndpoint(s,t),this.irGraph.markEndpointForAudience(s.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let a=i?.join(".")??r,o=this.getOrCreatePackage({group:i});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let a=$A(i?.join(".")),o=$A(r),c=this.context.namespace?`${$A(this.context.namespace)}/`:"",f=a?`channel_${c}${a}`:`channel_${c}${o}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[f]:t},f!==""?u.websocket==null&&(u.websocket=f):this.ir.rootPackage.websocket="";let s=this.context.createFernFilepath();this.irGraph.addChannel(s,f,t),n!=null&&this.irGraph.markChannelForAudiences(s,f,n)}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[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=Object.keys(i).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...i,[o]:n})}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,n])=>[r,n.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 n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:ZX(""),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(i=>$A(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let a=r[i]??"",c=`subpackage_${r.slice(0,i+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 f=this.ir.subpackages[c];n.subpackages.includes(c)||n.subpackages.push(c),n=f}return n}};var z6={};yf(z6,{AbstractConverters:()=>GTf,ExampleConverter:()=>eht,SchemaConverters:()=>HTf,ServersConverter:()=>$rt});var GTf={};yf(GTf,{AbstractMediaTypeObjectConverter:()=>vNu,AbstractParameterConverter:()=>bNu});var eht=class e extends gO{MAX_DEPTH=12;EXAMPLE_STRING=FP.STRING;EXAMPLE_NUMBER=FP.DOUBLE;EXAMPLE_BOOLEAN=FP.BOOLEAN;EXAMPLE_INTEGER=FP.INT;EXAMPLE_DATE=FP.DATE;EXAMPLE_DATE_TIME=FP.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:f=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=f}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,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,validExample:n??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 n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,validExample:n,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}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):n!=null&&(c=n);let f;return o!=null?typeof o=="boolean"?f=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:f=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):i!=null&&(f=i),c!==void 0&&f!==void 0?(t<c||t>f)&&(t=c+(f-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):f!==void 0&&t>f&&(t=f-Math.abs(f*.1)),Number(Number(t).toPrecision(3))}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,n=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)??n,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,n=this.example??t.example,a=(Array.isArray(n)?n:[n]).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()),o=a.every(c=>c?.isValid??!1)&&!r;return{isValid:o,coerced:!1,validExample:a.map(c=>c.validExample),errors:o?[]: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,n=Object.entries(t.properties??{}).map(([f,u])=>{if(typeof u!="object")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(u)&&!this.isRequiredProperty({key:f,resolvedSchema:t}))return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in u&&u.readOnly===!0&&"writeOnly"in u&&u.writeOnly===!0)return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in u&&u.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in u&&u.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(f in r)||!("nullable"in u)&&r[f]==null||"nullable"in u&&u.nullable===!0&&r[f]===void 0,l=!t.required?.includes(f);if(s&&l){if(this.example===void 0&&this.generateOptionalProperties){let m=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:u,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:f,result:m.convert()}}return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let A=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:u,example:r[f],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:f,result:A}}}),i=(t.allOf??[]).map((f,u)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${u}]`],context:this.context,schema:{...t,...f,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=n.every(f=>f.result.isValid)&&i.every(f=>f.isValid),o=Object.fromEntries(n.map(({key:f,result:u})=>[f,u.validExample]).filter(([f,u])=>u!==void 0));for(let f of i)if(typeof f.validExample=="object"&&f.validExample!==null){let u=f.validExample;o={...o,...Object.fromEntries(Object.entries(u).filter(([s,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let f=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},u=new Set(Object.keys(o??{}));Object.keys(r).filter(l=>!u.has(l)).forEach(l=>{let A=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:A})})}for(let{key:f,result:u}of c)u.validExample!==void 0&&o[f]===void 0&&(o[f]=u.validExample);if(Object.keys(o).length===0){let f=i.find(u=>u.validExample!==void 0&&(typeof u.validExample!="object"||u.validExample===null));f&&(o=f.validExample)}return{isValid:a,coerced:!1,validExample:o,errors:[...n.flatMap(({result:f})=>f.errors),...i.flatMap(f=>f.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((o,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:o},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(o=>o?.isValid??!1),a=r.find(o=>o.isValid)?.validExample??r[0]?.validExample??null;return{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(o=>o?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let i=[],a=null;for(let f=0;f<n.length;f++){let u=n[f];if(!u)continue;let s=r==="oneOf"?{...t,...u,oneOf:void 0}:u,m=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${f}]`],context:this.context,schema:s,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(m.isValid&&!m.coerced)return{isValid:!0,coerced:!1,validExample:m.validExample,errors:[]};i.push(m),m.isValid&&a===null&&(a=m)}let o=a!==null,c=a?.validExample??i[0]?.validExample;return{isValid:o,coerced:!1,validExample:c,errors:o?[]:i.flatMap(f=>f.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}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 HTf={};yf(HTf,{ArraySchemaConverter:()=>ero,EnumSchemaConverter:()=>Yto,ObjectSchemaConverter:()=>Xto,OneOfSchemaConverter:()=>Zto,PrimitiveSchemaConverter:()=>kto,SchemaConverter:()=>M6i,SchemaOrReferenceConverter:()=>pPe});function C5y(e){return ree({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Mh.primitive({v1:"BASE_64",v2:l0.base64({})});case"BOOLEAN":return Mh.primitive({v1:"BOOLEAN",v2:l0.boolean({default:void 0})});case"DATE":return Mh.primitive({v1:"DATE",v2:l0.date({})});case"DATE_TIME":return Mh.primitive({v1:"DATE_TIME",v2:l0.dateTime({})});case"FLOAT":return Mh.primitive({v1:"FLOAT",v2:l0.float({})});case"DOUBLE":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:void 0,validation:void 0})});case"UINT":return Mh.primitive({v1:"UINT",v2:l0.uint({})});case"UINT_64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({})});case"INTEGER":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:void 0,validation:void 0})});case"LONG":return Mh.primitive({v1:"LONG",v2:l0.long({default:void 0})});case"STRING":return Mh.primitive({v1:"STRING",v2:l0.string({default:void 0,validation:void 0})});case"UUID":return Mh.primitive({v1:"UUID",v2:l0.uuid({})});case"BIG_INTEGER":return Mh.primitive({v1:"BIG_INTEGER",v2:l0.bigInteger({default:void 0})});default:return}},unknown:()=>Mh.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Mh.container(Xw.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Mh.container(Xw.list(t))},optional:t=>{if(t!=null)return Mh.container(Xw.optional(t))},nullable:t=>{if(t!=null)return Mh.container(Xw.nullable(t))},set:t=>{if(t!=null)return Mh.container(Xw.set(t))},literal:t=>Mh.container(Xw.literal(t._visit({string:r=>Sfe.string(r),boolean:r=>Sfe.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var Yto=class extends gO{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let a=i.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.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 n=this.context.getAsString(this.schema.default);return{type:YE.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r})}}};var hNu=class extends gO{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}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=Mh.container(Xw.map({keyType:gO.STRING,valueType:Mh.unknown()}));return{type:YE.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new pPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Mh.container(Xw.map({keyType:gO.STRING,valueType:r.type})),i=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])i.add(a);for(let a of Object.keys(r.inlinedTypes))i.add(a);return{type:YE.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};function bZo({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let a=[],o={},c={},f=new Set;for(let[u,s]of Object.entries(e??{})){let l=[...r,"properties",u];if(typeof s!="object"){i.collect({message:`Schema property ${u} should be an object`,path:l});continue}let m=XiI(r,s,n)??n.convertBreadcrumbsToName(l),A="nullable"in s?s.nullable:!1,C=new pPe({context:n,breadcrumbs:l,schemaOrReference:s,schemaIdOverride:m,wrapAsOptional:!t.includes(u),wrapAsNullable:A}).convert();if(C!=null){a.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:C.type,docs:s.description,availability:C.availability,propertyAccess:n.getPropertyAccess(s),v2Examples:C.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...C.inlinedTypes},C.schema?.typeDeclaration.referencedTypes!=null&&C.schema.typeDeclaration.referencedTypes.forEach(I=>{f.add(I)});for(let I of C.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(o))f.add(u);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:f}}function XiI(e,t,r){return r.isReferenceObject(t)?void 0:new Sse.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var Xto=class extends gO{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:YE.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:a}=bZo({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=i,f=this.schema.required!=null&&this.schema.required.length>0,u=n,s=a;for(let[l,m]of(this.schema.allOf??[]).entries()){let A=[...this.breadcrumbs,"allOf",l.toString()],P;if(this.context.isReferenceObject(m)){let U=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:A});if(U==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(m)}`);continue}if(P=U,typeof P.additionalProperties=="boolean"&&P.additionalProperties&&(t=!0),!f||Object.keys(P.properties??{}).every(q=>!this.schema.required?.includes(q))){this.addTypeReferenceToExtends({reference:m,breadcrumbs:A,extends_:o,referencedTypes:c});continue}}else P=m;typeof P.additionalProperties=="boolean"&&P.additionalProperties&&(t=!0);let{convertedProperties:C,inlinedTypesFromProperties:I,referencedTypes:T,propertiesByAudience:z}=bZo({properties:P.properties??{},required:[...this.schema.required??[],...P.required??[]],breadcrumbs:A,context:this.context,errorCollector:this.context.errorCollector});r.push(...C),u={...u,...I},s={...s,...z},T.forEach(U=>{c.add(U)})}for(let l of Object.keys(u))c.add(l);return{type:YE.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(pj),extendedProperties:[],extraProperties:t}),propertiesByAudience:s,referencedTypes:c,inlinedTypes:u}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&n.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&i.add(o)}};var yNu=class extends UD{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Zto=class extends gO{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new yNu({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,n]of Object.entries(this.schema.discriminator?.mapping??{})){let i=this.context.resolveReference({reference:{$ref:n},breadcrumbs:this.breadcrumbs});if(i.resolved&&!Object.keys(i.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,n={};for(let[f,u]of Object.entries(this.schema.discriminator.mapping??{})){let s=new pPe({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",f]}),l=this.context.getTypeIdFromSchemaReference({$ref:u});l!=null&&r.add(l);let m=s.convert();if(m?.type!=null&&l!=null){for(let P of Object.keys(m?.inlinedTypes??{}))r.add(P);for(let P of m.schema?.typeDeclaration.referencedTypes??[])r.add(P);let A=this.context.casingsGenerator.generateNameAndWireValue({name:f,wireValue:f});t.push({docs:void 0,discriminantValue:A,availability:m.availability,displayName:f,shape:Efe.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:f})}),n={...n,...m.inlinedTypes}}}let{convertedProperties:i,referencedTypes:a,inlinedTypesFromProperties:o}=bZo({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[f,u]of(this.schema.allOf??[]).entries()){let s=[...this.breadcrumbs,"allOf",f.toString()];if(this.context.isReferenceObject(u)){let l=this.context.convertReferenceToTypeReference({reference:u,breadcrumbs:s});if(l.ok){let A=this.context.typeReferenceToDeclaredTypeName(l.reference);A!=null&&c.push(A)}let m=this.context.getTypeIdFromSchemaReference(u);m!=null&&r.add(m);continue}}for(let f of Object.keys({...n,...o}))r.add(f);return{type:YE.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...n,...o}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={},i=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let m;if(this.context.isReferenceObjectWithIdentifier(o))m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let P=this.getDiscriminatorKeyForRef(o);m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:P,displayNameOverrideSource:"discriminator_key"})}else m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});m.ok&&t.push({type:m.reference,docs:o.description});let A=this.context.getTypeIdFromSchemaReference(o);A!=null&&r.add(A);continue}let c=this.extendSubSchema(o),f=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),u=o.title,l=new M6i({context:this.context,id:f,nameOverride:u,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(l!=null){let m=l.convertedSchema.typeDeclaration.shape;m.type==="alias"&&this.typeReferenceIsWrappedPrimitive(m.aliasOf)?t.push({type:m.aliasOf,docs:o.description}):m.type==="object"&&m.properties.length===0?t.push({type:Mh.container(Xw.map({keyType:gO.STRING,valueType:Mh.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(f,u),docs:o.description}),n={...n,...l.inlinedTypes,[f]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}return{type:YE.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}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 n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new pPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:YE.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.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 Mh.container(Xw.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,n])=>n===t.$ref)?.[0]}};var kto=class extends gO{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return Mh.container(Xw.literal(Sfe.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Mh.primitive({v1:yw.Date,v2:l0.date({})});if(this.schema.format==="date-time")return Mh.primitive({v1:yw.DateTime,v2:l0.dateTime({})})}return Mh.primitive({v1:"STRING",v2:l0.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Mh.primitive({v1:"FLOAT",v2:l0.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Mh.primitive({v1:"LONG",v2:l0.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Mh.primitive({v1:"UINT",v2:l0.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Mh.primitive({v1:"FLOAT",v2:l0.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Mh.primitive({v1:"LONG",v2:l0.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Mh.primitive({v1:"UINT",v2:l0.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Mh.primitive({v1:"INTEGER",v2:l0.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?Mh.container(Xw.literal(Sfe.boolean(t))):Mh.primitive({v1:"BOOLEAN",v2:l0.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 ZiI=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],M6i=class e extends gO{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=a,this.nameOverride=o,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 n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let f=this.tryConvertMapSchema();if(f!=null)return f;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let s=this.tryConvertUntypedSchema();if(s!=null)return s;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 Sse.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new Yto({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.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 i=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(i?.convertedSchema.typeDeclaration?.shape.type!=="object")return i}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let i of this.schema.allOf??[]){if(this.context.isReferenceObject(i))return;r=TWa(r,i,(a,o)=>{if(o===i)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new kto({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new ero({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.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 Zto({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 hNu({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 Xto({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:YE.alias({aliasOf:Mh.unknown(),resolvedType:Mh.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new Sse.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=C5y(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){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:n?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=[...ZiI,...t];return Object.keys(this.schema).every(i=>r.includes(i))}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 n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let a=this.context.resolveExample(i),o=this.generateOrValidateExample({example:a});r[`${this.id}_example_${n}`]=o}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let n=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:i,errors:a}=n.convert();return r||a.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),i}};var pPe=class extends gO{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=a,this.wrapAsNullable=o}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),n=new M6i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),i=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=n.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:i}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:i}}}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 Mh.container(Xw.optional(t))}wrapInNullable(t){return Mh.container(Xw.nullable(t))}};var ero=class e extends gO{static LIST_UNKNOWN=Mh.container(Xw.list(Mh.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(a=>{n.add(a)})}),{typeReference:Mh.container(Xw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var vNu=class extends gO{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let f=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(f==null)return;t.schema=f}let o=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([f,u])=>{if(this.context.isReferenceObject(u)){let s=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return s.resolved?[f,s.value.value??s.value]:null}return[f,u.value??u]}).filter(f=>f!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,f]of o){let u=this.context.resolveExampleWithValue(f),s=this.context.isExampleWithSummary(f)?f.summary:c;u!=null&&(a!=null?i.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:a,example:u,exampleGenerationStrategy:n}):i.userSpecifiedExamples[s]=u)}if(Object.keys(i.userSpecifiedExamples).length===0&&a!=null){let c=$A(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n})}return i}generateOrValidateExample({schema:t,example:r,ignoreErrors:n,generateOptionalProperties:i,exampleGenerationStrategy:a}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let c=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),f=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??c[0],generateOptionalProperties:i??!1,exampleGenerationStrategy:a}),{validExample:u,errors:s}=f.convert();return n||s.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),u}};var bNu=class extends gO{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=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??gO.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:i},inlinedTypes:n};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??gO.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??gO.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t})},inlinedTypes:n};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:{}},n=this.parameter.example,i=this.parameter.examples;for(let[a,o]of Object.entries(i??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(n!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:n})}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:n}){let i=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:n}),{validExample:a,errors:o}=i.convert();return r||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var gNu=class extends UD{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var I5y="Base",$rt=class e extends gO{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}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(),n={id:r,name:this.context.casingsGenerator.generateName(r)},i=this.endpointLevelServers.map(c=>{let f=e.getServerName({server:c,context:this.context});return{id:f,name:this.context.casingsGenerator.generateName(f)}}).filter((c,f,u)=>u.findIndex(s=>s.id===c.id)===f),a=[n,...i],o=this.servers.map(c=>{let f=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:f,name:this.context.casingsGenerator.generateName(f),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description}});return{value:{defaultEnvironment:o[0]?.id,environments:mJ.multipleBaseUrls({baseUrls:a,environments:o})},defaultUrl:n.id}}let t=this.withExplodedServers(this.servers).map(r=>{let n=e.getServerName({server:r,context:this.context});return{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(pj);return{value:{defaultEnvironment:t[0]?.id,environments:mJ.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new gNu({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[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let n=Object.entries(r.variables).filter(([c,f])=>f.enum!=null&&f.enum.length>0);if(n.length===0)return[r];let i=n[0];if(i==null)return[r];let[a,o]=i;return o.enum==null?[r]:o.enum.map(c=>{let f=r.url.replace(`{${a}}`,encodeURIComponent(c)),u={};for(let[l,m]of Object.entries(r.variables??{}))l!==a&&(u[l]=m);let s={...r,url:f,variables:Object.keys(u).length>0?u:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([s])[0]})}).filter(pj)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?I5y:e.getServerExtensionName({server:this.servers[0],context:this.context})??I5y}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var gZo={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"},kiI=new Set(Object.values(gZo));var tro=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
2630
+ `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:n=[],pipe:i=!1,debuggingPort:a,channel:o,executablePath:c}=t,f=[];r?Array.isArray(r)?f.push(...this.defaultArgs(t).filter(A=>!r.includes(A))):f.push(...n):f.push(...this.defaultArgs(t)),f.some(A=>A.startsWith("--remote-debugging-"))||(i?(ky(!a,"Browser should be launched with either pipe or debugging port - not both."),f.push("--remote-debugging-pipe")):f.push(`--remote-debugging-port=${a||0}`));let u=!1,s=f.findIndex(A=>A.startsWith("--user-data-dir"));s<0&&(u=!0,f.push(`--user-data-dir=${await(0,V7y.mkdtemp)(this.getProfilePath())}`),s=f.length-1);let l=f[s].split("=",2)[1];ky(typeof l=="string","`--user-data-dir` is malformed");let m=c;return m||(ky(o||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),m=o?this.executablePath(o):this.resolveExecutablePath(t.headless??!0)),{executablePath:m,args:f,isTempUserDataDir:u,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await ERu(t)}catch(n){throw Fv(n),n}}defaultArgs(t={}){let r=L7y("--disable-features",t.args);t.args&&r.length>0&&U7y(t.args,"--disable-features");let i=["Translate","AcceptCHFrame","MediaRouter","OptimizationHints","RenderDocument",...process.env.PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES==="true"?[]:["ProcessPerSiteUpToMainFrameThreshold","IsolateSandboxedIframes"],...r].filter(A=>A!==""),a=L7y("--enable-features",t.args);t.args&&a.length>0&&U7y(t.args,"--enable-features");let o=["PdfOopif",...a].filter(A=>A!==""),c=["--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-crash-reporter","--disable-default-apps","--disable-dev-shm-usage","--disable-hang-monitor","--disable-infobars","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-search-engine-choice-screen","--disable-sync","--enable-automation","--export-tagged-pdf","--force-color-profile=srgb","--generate-pdf-document-outline","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain",`--disable-features=${i.join(",")}`,`--enable-features=${o.join(",")}`].filter(A=>A!==""),{devtools:f=!1,headless:u=!f,args:s=[],userDataDir:l,enableExtensions:m=!1}=t;return l&&c.push(`--user-data-dir=${H7y.default.resolve(l)}`),f&&c.push("--auto-open-devtools-for-tabs"),u&&c.push(u==="shell"?"--headless":"--headless=new","--hide-scrollbars","--mute-audio"),c.push(m?"--enable-unsafe-extension-debugging":"--disable-extensions"),s.every(A=>A.startsWith("-"))&&c.push("about:blank"),c.push(...s),c}executablePath(t,r=!0){return t?ARu({browser:q1.CHROME,channel:YkC(t)}):this.resolveExecutablePath(void 0,r)}};function YkC(e){switch(e){case"chrome":return E3.STABLE;case"chrome-dev":return E3.DEV;case"chrome-beta":return E3.BETA;case"chrome-canary":return E3.CANARY}}function L7y(e,t=[]){return t.filter(r=>r.startsWith(e.endsWith("=")?e:`${e}=`)).map(r=>r.split(new RegExp(`${e}=\\s*`))[1]?.trim()).filter(r=>r)}function U7y(e,t){let r=new RegExp(`^${t}=.*`),n=0;for(;n<e.length;)r.test(e[n])?e.splice(n,1):n++;return e}var G7y=$i(require("fs"),1),Mto=require("fs/promises"),J7y=$i(require("os"),1),uBf=$i(require("path"),1);hI();F8();var DRu=class e extends Ito{constructor(t){super(t,"firefox")}static getPreferences(t){return{...t,"fission.webContentIsolationStrategy":0}}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:n=[],executablePath:i,pipe:a=!1,extraPrefsFirefox:o={},debuggingPort:c=null}=t,f=[];r?Array.isArray(r)?f.push(...this.defaultArgs(t).filter(A=>!r.includes(A))):f.push(...n):f.push(...this.defaultArgs(t)),f.some(A=>A.startsWith("--remote-debugging-"))||(a&&ky(c===null,"Browser should be launched with either pipe or debugging port - not both."),f.push(`--remote-debugging-port=${c||0}`));let u,s=!0,l=f.findIndex(A=>["-profile","--profile"].includes(A));if(l!==-1){if(u=f[l+1],!u)throw new Error("Missing value for profile command line argument");s=!1}else u=await(0,Mto.mkdtemp)(this.getProfilePath()),f.push("--profile"),f.push(u);await XMf(q1.FIREFOX,{path:u,preferences:e.getPreferences(o)});let m;return this.puppeteer._isPuppeteerCore||i?(ky(i,"An `executablePath` must be specified for `puppeteer-core`"),m=i):m=this.executablePath(void 0),{isTempUserDataDir:s,userDataDir:u,args:f,executablePath:m}}async cleanUserDataDir(t,r){if(r.isTemp)try{await ERu(t)}catch(n){throw Fv(n),n}else try{let n=".puppeteer",i=["prefs.js","user.js"],a=await Promise.allSettled(i.map(async o=>{let c=uBf.default.join(t,o+n);if(G7y.default.existsSync(c)){let f=uBf.default.join(t,o);await(0,Mto.unlink)(f),await(0,Mto.rename)(c,f)}}));for(let o of a)if(o.status==="rejected")throw o.reason}catch(n){Fv(n)}}executablePath(t,r=!0){return this.resolveExecutablePath(void 0,r)}defaultArgs(t={}){let{devtools:r=!1,headless:n=!r,args:i=[],userDataDir:a=null}=t,o=[];switch(J7y.default.platform()){case"darwin":o.push("--foreground");break;case"win32":o.push("--wait-for-browser");break}return a&&(o.push("--profile"),o.push(a)),n&&o.push("--headless"),r&&o.push("--devtools"),i.every(c=>c.startsWith("-"))&&o.push("about:blank"),o.push(...i),o}};var Bto=class extends jTu{#e;#t;defaultBrowserRevision;configuration={};constructor(t){let{configuration:r,...n}=t;switch(super(n),r&&(this.configuration=r),this.configuration.defaultBrowser){case"firefox":this.defaultBrowserRevision=Leo.firefox;break;default:this.configuration.defaultBrowser="chrome",this.defaultBrowserRevision=Leo.chrome;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.trimCache=this.trimCache.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{browser:r=this.defaultBrowser}=t;switch(this.#t=r,r){case"chrome":this.defaultBrowserRevision=Leo.chrome;break;case"firefox":this.defaultBrowserRevision=Leo.firefox;break;default:throw new Error(`Unknown product: ${r}`)}return this.#e=this.#r(r),this.#e.launch(t)}#r(t){if(this.#e&&this.#e.browser===t)return this.#e;switch(t){case"chrome":return new SRu(this);case"firefox":return new DRu(this);default:throw new Error(`Unknown product: ${t}`)}}executablePath(t){return t===void 0?this.#r(this.lastLaunchedBrowser).executablePath(void 0,!1):typeof t=="string"?this.#r("chrome").executablePath(t,!1):this.#r(t.browser??this.lastLaunchedBrowser).resolveExecutablePath(t.headless,!1)}get browserVersion(){return this.configuration?.[this.lastLaunchedBrowser]?.version??this.defaultBrowserRevision}get defaultDownloadPath(){return this.configuration.cacheDirectory}get lastLaunchedBrowser(){return this.#t??this.defaultBrowser}get defaultBrowser(){return this.configuration.defaultBrowser??"chrome"}get product(){return this.lastLaunchedBrowser}defaultArgs(t={}){return this.#r(t.browser??this.lastLaunchedBrowser).defaultArgs(t)}async trimCache(){let t=tqr();if(!t)throw new Error("The current platform is not supported.");let r=this.configuration.cacheDirectory,n=await sBf({cacheDir:r}),i=[{product:"chrome",browser:q1.CHROME,currentBuildId:""},{product:"firefox",browser:q1.FIREFOX,currentBuildId:""}];for(let c of i){let f=this.configuration?.[c.product]?.version??Leo[c.product];c.currentBuildId=await yRu(c.browser,t,f)}let a=new Set(i.map(c=>`${c.browser}_${c.currentBuildId}`)),o=new Set(i.map(c=>c.browser));for(let c of n)o.has(c.browser)&&(a.has(`${c.browser}_${c.buildId}`)||await oBf({browser:c.browser,platform:t,cacheDir:r,buildId:c.buildId}))}};var CRu=require("child_process"),Y7y=$i(require("fs"),1),X7y=$i(require("os"),1),Z7y=require("path"),k7y=require("stream"),e8y=$i(oee(),1);R_t();cxe();hI();dee();N8();var XkC=function(e,t,r){for(var n=arguments.length>2,i=0;i<t.length;i++)r=n?t[i].call(e,r):t[i].call(e);return n?r:void 0},K7y=function(e,t,r,n,i,a){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var c=n.kind,f=c==="getter"?"get":c==="setter"?"set":"value",u=!t&&e?n.static?e:e.prototype:null,s=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),l,m=!1,A=r.length-1;A>=0;A--){var P={};for(var C in n)P[C]=C==="access"?{}:n[C];for(var C in n.access)P.access[C]=n.access[C];P.addInitializer=function(T){if(m)throw new TypeError("Cannot add initializers after decoration has completed");a.push(o(T||null))};var I=(0,r[A])(c==="accessor"?{get:s.get,set:s.set}:s[f],P);if(c==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(l=o(I.get))&&(s.get=l),(l=o(I.set))&&(s.set=l),(l=o(I.init))&&i.unshift(l)}else(l=o(I))&&(c==="field"?i.unshift(l):s[f]=l)}u&&Object.defineProperty(u,n.name,s),m=!0},ZkC=function(e,t,r){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})},kkC=30,$7y=30,eeI=(0,e8y.default)("puppeteer:ffmpeg"),t8y=(()=>{let e=k7y.PassThrough,t=[],r,n,i;return class extends e{static{let o=typeof Symbol=="function"&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;K7y(this,n={value:ZkC(async function(c){let f=await new Promise(u=>{this.#t.stdin.write(c,u)});f&&console.log(`ffmpeg failed to write: ${f.message}.`)},"#writeFrame")},r,{kind:"method",name:"#writeFrame",static:!1,private:!0,access:{has:c=>#o in c,get:c=>c.#o},metadata:o},null,t),K7y(this,null,i,{kind:"method",name:"stop",static:!1,private:!1,access:{has:c=>"stop"in c,get:c=>c.stop},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}#e=XkC(this,t);#t;#r=new AbortController;#n;#i;constructor(o,c,f,{ffmpegPath:u,speed:s,scale:l,crop:m,format:A,fps:P,loop:C,delay:I,quality:T,colors:z,path:U,overwrite:q}={}){super({allowHalfOpen:!1}),u??="ffmpeg",A??="webm",P??=$7y,C||=-1,I??=-1,T??=kkC,z??=256,q??=!0,this.#i=P;let{error:V}=(0,CRu.spawnSync)(u);if(V)throw V;let $=[`crop='min(${c},iw):min(${f},ih):0:0'`,`pad=${c}:${f}:0:0`];s&&$.push(`setpts=${1/s}*PTS`),m&&$.push(`crop=${m.width}:${m.height}:${m.x}:${m.y}`),l&&$.push(`scale=iw*${l}:-1:flags=lanczos`);let re=this.#a(A,P,C,I,T,z),Y=re.indexOf("-vf");Y!==-1&&$.push(re.splice(Y,2).at(-1)??""),U&&Y7y.default.mkdirSync((0,Z7y.dirname)(U),{recursive:q}),this.#t=(0,CRu.spawn)(u,[["-loglevel","error"],["-avioflags","direct"],["-fpsprobesize","0","-probesize","32","-analyzeduration","0","-fflags","nobuffer"],["-f","image2pipe","-vcodec","png","-i","pipe:0"],["-an"],["-threads","1"],["-framerate",`${P}`],["-b:v","0"],re,["-vf",$.join()],[q?"-y":"-n"],"pipe:1"].flat(),{stdio:["pipe","pipe","pipe"]}),this.#t.stdout.pipe(this),this.#t.stderr.on("data",ne=>{eeI(ne.toString("utf8"))}),this.#e=o;let{client:k}=this.#e.mainFrame();k.once(Bx.Disconnected,()=>{this.stop().catch(Fv)}),this.#n=YTy(w3(k,"Page.screencastFrame").pipe(vca(ne=>{k.send("Page.screencastFrameAck",{sessionId:ne.sessionId})}),Qrt(ne=>ne.metadata.timestamp!==void 0),R8(ne=>({buffer:Buffer.from(ne.data,"base64"),timestamp:ne.metadata.timestamp})),tqy(2,1),rqy(([{timestamp:ne,buffer:Oe},{timestamp:he}])=>FI(Array(Math.round(P*Math.max(he-ne,0))).fill(Oe))),R8(ne=>(this.#o(ne),[ne,performance.now()])),vIu(Ska(this.#r.signal,"abort"))),{defaultValue:[Buffer.from([]),performance.now()]})}#a(o,c,f,u,s,l){let m=[["-vcodec","vp9"],["-crf",`${s}`],["-deadline","realtime","-cpu-used",`${Math.min(X7y.default.cpus().length/2,8)}`]];switch(o){case"webm":return[...m,["-f","webm"]].flat();case"gif":return c=$7y===c?20:"source_fps",f===1/0&&(f=0),u!==-1&&(u/=10),[["-vf",`fps=${c},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${l}[p];[s1][p]paletteuse=dither=bayer`],["-loop",`${f}`],["-final_delay",`${u}`],["-f","gif"]].flat();case"mp4":return[...m,["-movflags","hybrid_fragmented"],["-f","mp4"]].flat()}}get#o(){return n.value}async stop(){if(this.#r.signal.aborted)return;await this.#e._stopScreencast().catch(Fv),this.#r.abort();let[o,c]=await this.#n;await Promise.all(Array(Math.max(1,Math.round(this.#i*(performance.now()-c)/1e3))).fill(o).map(this.#o.bind(this))),this.#t.stdin.end(),await new Promise(f=>{this.#t.once("close",f)})}async[(r=[IYo()],i=[IYo()],lee)](){await this.stop()}}})();var r8y=$i(require("fs"),1),n8y=$i(require("path"),1);KAi();oCe.value={fs:r8y.default,path:n8y.default,ScreenRecorder:t8y};var reI=new Bto({isPuppeteerCore:!0}),{connect:OUU,defaultArgs:AUU,executablePath:PUU,launch:wUU}=reI;var ZQy=require("os"),kQy=require("path"),e5y=$i(XQy(),1);function CTf(e){let t=process.env[e];if(t!==void 0)switch(t.toLowerCase()){case"":case"0":case"false":case"off":return!1;default:return!0}}function $nI(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}function YnI(e){if(e&&!$nI(e))throw new Error(`Unsupported browser ${e}`);switch(e){case"firefox":return"firefox";default:return"chrome"}}function XnI(e){switch(e){case"silent":return"silent";case"error":return"error";default:return"warn"}}function DTf(e,t,r={}){if(t.skipDownload)return{skipDownload:!0};let n={},i=e.replaceAll("-","_").toUpperCase();return n.version=process.env[`PUPPETEER_${i}_VERSION`]??t[e]?.version??r.version,n.downloadBaseUrl=process.env[`PUPPETEER_${i}_DOWNLOAD_BASE_URL`]??t[e]?.downloadBaseUrl??r.downloadBaseUrl,n.skipDownload=CTf(`PUPPETEER_${i}_SKIP_DOWNLOAD`)??CTf(`PUPPETEER_SKIP_${i}_DOWNLOAD`)??t[e]?.skipDownload??r.skipDownload,n}var t5y=()=>{let e=(0,e5y.cosmiconfigSync)("puppeteer",{searchStrategy:"global"}).search(),t=e?e.config:{};return t.logLevel=XnI(process.env.PUPPETEER_LOGLEVEL??t.logLevel),t.defaultBrowser=YnI(process.env.PUPPETEER_BROWSER??t.defaultBrowser),t.executablePath=process.env.PUPPETEER_EXECUTABLE_PATH??t.executablePath,t.executablePath&&(t.skipDownload=!0),t.skipDownload=CTf("PUPPETEER_SKIP_DOWNLOAD")??t.skipDownload,t.chrome=DTf("chrome",t),t["chrome-headless-shell"]=DTf("chrome-headless-shell",t),t.firefox=DTf("firefox",t,{skipDownload:!0}),t.cacheDirectory=process.env.PUPPETEER_CACHE_DIR??t.cacheDirectory??(0,kQy.join)((0,ZQy.homedir)(),".cache","puppeteer"),t.temporaryDirectory=process.env.PUPPETEER_TMP_DIR??t.temporaryDirectory,t.experiments??={},t};var ZnI=t5y(),knI=new Bto({isPuppeteerCore:!1,configuration:ZnI}),{connect:rWU,defaultArgs:nWU,executablePath:iWU,launch:r5y,trimCache:aWU}=knI;var eiI="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",tiI={"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 pZo(e,t=3,r=1e3,n=2){try{return await e()}catch(i){if(t>0)return await new Promise(a=>setTimeout(a,r)),pZo(e,t-1,r*n,n);throw i}}async function n5y(){try{return await r5y({headless:!0,args:["--ignore-certificate-errors"]})}catch{throw new Error("Could not create a Puppeteer instance")}}async function riI(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(tiI),await r.setUserAgent(eiI),await r.setJavaScriptEnabled(!0),await pZo(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let n=await pZo(()=>r.content());return await r.close(),n}catch{throw new Error("Failed to download page from Puppeteer")}}async function niI(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 ITf({url:e,browser:t}){try{let r;if(t?r=await riI(t,e):r=await pZo(()=>niI(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function i5y(e){try{let t=await pZo(()=>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 iiI=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function a5y(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,Wto.join)(process.cwd(),"fern");try{let r=await aiI(e,(0,Wto.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function aiI(e,t){let r=siI(e),n=(0,Wto.join)(t,r);if(!oiI(r))throw new Error(`${r} - file extension not supported`);if((0,YRu.existsSync)(n))return n;try{(0,YRu.mkdirSync)((0,Wto.dirname)(n),{recursive:!0})}catch{throw new Error(`${n} - failed to create directory`)}try{let i=await i5y(e);return uBy(n,i),n}catch{throw new Error(`${n}: failed to download file from source`)}}function oiI(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let n=r.toLowerCase();return!(n&&!iiI.includes(n))}function siI(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 n=r.split("?");if(n.length===0)return"image";let i=n[0];return i&&decodeURIComponent(i.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function uiI(e){let t=[];return Vv(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 o5y(e,t){let r=jka(e),n=uiI(r);if(n!=null){let i=await Promise.all(n.map(async a=>{let o=await a5y(a.properties.src);return o.success&&o.data?o.data[1]:""}));t.push(...i)}for(let i=t.length-1;i>=0;i--)t[i]||t.splice(i,1)}var s5y=28;async function u5y(e,t){e=new URL(e);let r=[];if(t){let i=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),i.push(await a.content()),await a.click(".rm-ThemeToggle"),i.push(await a.content())}catch{}await Promise.all(i.map(async a=>await o5y(a,r)))}let n=[...new Set(r).values()];if(n.length!==0){if(n.length===1&&n[0]!=null){let i=ru.of(uAe(n[0]));return{light:i,dark:i,height:s5y}}if(n[0]!=null&&n[1]!=null){let i=ru.of(uAe(n[0])),a=ru.of(uAe(n[1]));return{light:i,dark:a,height:s5y}}}}var XRu=class extends Rua{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:O$o});let n=await this.getHastForUrl(this.url),i=mTy(n)??[];if(i.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${i.length} tabs:`);for(let s of i)this.logger.debug(` - Tab: ${s.name} (${s.url})`)}for(let s of i){let l=await this.scrapeTab({name:s.name,url:s.url});if(!l)continue;let m=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(s.name),tabConfig:{slug:s.url,displayName:s.name}}),A=Ql(this.absolutePathToFernDirectory,ru.of(this.kebabCaseWithoutEmojis(s.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:A,sections:l});let P=await this.getNavigationItems({absolutePathToOutputDirectory:A,sections:l});for(let C of P)m.addItem({item:C})}let a=await n5y(),o=await u5y(this.url,a);o!=null&&r.setLogo({logo:o});let c=await $Sy(n);r.setTitle({title:c});let f=await HSy(n);if(f!=null){let s=await this.getAndCreateAssetsDirectory(),l=await fetch(f);if(l.ok){let m=Buffer.from(await l.arrayBuffer()),A=Ql(s,ru.of("favicon"));await(0,S6i.writeFile)(A,new Uint8Array(m)),r.setFavicon({favicon:GNe(this.absolutePathToFernDirectory,A)})}}let u=await ATy(n);r.setColors({colors:u}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Ql(this.absolutePathToFernDirectory,ru.of("assets"));return await(0,S6i.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let n=new URL(r,this.url),i=await this.getHastForUrl(n),a=vTy(i);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let o=bTy(a);return this.logger.debug(`Successfully scraped tab: ${t}`),o}catch(n){this.logger.error(`Failed to scrape tab ${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.error(`Stack trace: ${n.stack}`)}}async getHastForUrl(t){let r=await ITf({url:t});return jka(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let n of r){this.logger.debug(`Processing section: ${n.group}`);let i=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n});await(0,S6i.mkdir)(i,{recursive:!0}),await Promise.all(n.pages.filter(a=>a.type==="page").map(async a=>{let o=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${o.toString()}`);let c=await ITf({url:o}),f=await yTy({logger:this.logger,html:c,url:o});if(f.success&&f.data){let u=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:i,page:a.slug});await(0,S6i.writeFile)(u,f.data.mdx),f.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${f.data.images.imageURLs.length} images to download for ${o.toString()}`),await Promise.all(Object.entries(f.data.images.imageURLToFilename).map(async([s,l])=>{try{let m=await fetch(s);if(!m.ok){this.logger.warn(`Failed to download image ${s}, status: ${m.status}`);return}let A=Buffer.from(await m.arrayBuffer()),P=Ql(i,ru.of(l)),C=Wg(P);await(0,S6i.mkdir)(C,{recursive:!0}),await(0,S6i.writeFile)(P,new Uint8Array(A)),this.logger.debug(`Saved image to ${P}`)}catch(m){this.logger.warn(`Error downloading image ${s}: ${m}`)}})))}else this.logger.warn(`Failed to parse page ${o.toString()}, skipping`)})),await Promise.all(n.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:i,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let n=[];for(let i of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i}),o={section:i.group,contents:[],slug:this.kebabCaseWithoutEmojis(i.group)};for(let c of i.pages)if(c.type==="page")o.contents.push({page:c.page,path:GNe(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let f=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});o.contents.push(...f)}n.push(o)}return n}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Ql(t,ru.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Ql(t,ru.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 c5y=require("fs/promises");async function MTf({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:n,organization:i}){let a=new Nua;a.setInstance({companyName:i}),await new XRu({url:e,context:r,builder:a,absolutePathToFernDirectory:Ql(L_.of(process.cwd()),ru.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,c5y.writeFile)(Ql(L_.of(t),ru.of(kye),ru.of(QNe)),JSON.stringify({version:n,organization:i},void 0,4))}var BTf=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:n})=>{if(!e||!Cia(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let i=L_.of(fV());await MTf({readmeUrl:e,outputPath:i,taskContext:r,versionOfCli:n,organization:t})};var l5y="0.0.0";var f5y={[tw.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,X9(e)])),[tw.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"]),[tw.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"]),[tw.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"]),[tw.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"]),[tw.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","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[tw.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"]),[tw.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"]),[tw.GenerationLanguage.SWIFT]:new Set([])};var liI=["go","ruby"];function _Ce({generationLanguage:e,keywords:t,smartCasing:r}){let n={generateName:(i,a)=>{let o=l=>({unsafeName:l,safeName:fiI({name:l,keywords:diI({generationLanguage:e,keywords:t})})}),c=$A(i),f=X9(c),u=Vna(i),s=zna(c);return r&&(!hiI(s)&&(e==null||liI.includes(e))&&(c=s.map((l,m)=>{if(m>0){let A=ZRu(l);if(A!=null)return A;if(kRu(l))return l.toUpperCase()}return l}).join(""),f=X9(s.map((l,m)=>{let A=ZRu(l);return A??(kRu(l)?l.toUpperCase():m===0?X9(l):l)}).join(""))),u=i.split(" ").map(l=>l.split(/(\d+)/).map(Vna).join("")).join("_")),{originalName:i,camelCase:o(a?.casingOverrides?.camel??c),snakeCase:o(a?.casingOverrides?.snake??u),screamingSnakeCase:o(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:o(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:i,wireValue:a,opts:o})=>({name:n.generateName(i,o),wireValue:a})};return n}function fiI({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":_iI(e)?"_"+e:e}function diI({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return f5y[e]}var piI=/^[0-9]/;function _iI(e){return piI.test(e)}function hiI(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=ZRu(n)!=null||kRu(n),a=ZRu(t)!=null||kRu(t);return i&&a})}function ZRu(e){return viI.get(e.toUpperCase())}function kRu(e){return yiI.has(e.toUpperCase())}var yiI=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"]),viI=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function TTf({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:BAe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return tsa(e.auth,{single:n=>{let i=d5y({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:BAe.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:BAe.Any,schemes:n.map(i=>d5y({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function d5y({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let n=(a,o)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return yGo(c,{header:f=>q7.header({key:a,docs:o,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:Mh.primitive({v1:yw.String,v2:l0.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>p5y({key:a,casingsGenerator:r,docs:o,rawScheme:f}),tokenBearer:f=>eNu({key:a,casingsGenerator:r,docs:o,rawScheme:f}),inferredBearer(f){return eNu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:f=>eNu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return eNu({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return p5y({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function eNu({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return q7.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function p5y({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return q7.basic({key:e,docs:r,username:t.generateName(n?.username?.name??"username"),usernameEnvVar:n?.username?.env,password:t.generateName(n?.password?.name??"password"),passwordEnvVar:n?.password?.env})}function ZX(e){let t=giI(e),{value:r,done:n}=qTf(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...biI(t)]}}function*biI(e){let t;do{let{value:r}=qTf(e,"}"),n=qTf(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*giI(e){for(let t of e)yield t}function qTf(e,t){let r="",n=e.next();for(;n.done!==!0&&n.value!==t;)r+=n.value,n=e.next();return{value:r,done:n.done??!1}}function _Zo({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:jLr(n,{singleBaseUrl:()=>mJ.singleBaseUrl(miI({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>mJ.multipleBaseUrls(OiI({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,a])=>[i,jLr(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function miI({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>jLr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:_5y(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function OiI({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>jLr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:Bg(a.urls,o=>_5y(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function _5y(e){return e.endsWith("/")?e.slice(0,-1):e}function D6i(e){let t=2166136261;function r(i,a){if(typeof i=="object"&&i!=null){if(a>64){n("[MaxDepthExceeded]");return}if(Array.isArray(i)){n("[");for(let o=0;o<i.length;o++)o>0&&n(","),r(i[o],a+1);n("]")}else n("{"),Object.keys(i).sort().forEach((c,f)=>{f>0&&n(","),n(c),n(":"),r(i[c],a+1)}),n("}")}else n(String(i))}function n(i){for(let a=0;a<i.length;a++){let o=i.charCodeAt(a);t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function oVr({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 h5y({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return sVr({containerType:t});switch(t.type){case"list":{let o=x8({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:fB.literal({literal:t.literal._visit({boolean:o=>b0.boolean(o),string:o=>b0.string({original:o}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:o=>o,string:o=>o,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return sVr({containerType:t});let o=x8({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return sVr({containerType:t});let o=x8({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=x8({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=x8({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),c=x8({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?sVr({containerType:t}):{type:"success",example:fB.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:ku(t)}}function sVr({containerType:e}){switch(e.type){case"list":return{type:"success",example:fB.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:fB.literal({literal:e.literal._visit({boolean:t=>b0.boolean(t),string:t=>b0.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:fB.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:fB.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:fB.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:fB.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:ku(e)}}function v5y({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return EiI({fieldName:e,default_:AiI(t.v2),validation:PiI(t.v2)});case"BASE_64":return{type:"success",example:b0.base64(FP.BASE64),jsonExample:FP.BASE64};case"BOOLEAN":return{type:"success",example:b0.boolean(FP.BOOLEAN),jsonExample:FP.BOOLEAN};case"DATE":return{type:"success",example:b0.date(FP.DATE),jsonExample:FP.DATE};case"DATE_TIME":return{type:"success",example:b0.datetime({datetime:new Date(FP.DATE_TIME),raw:FP.DATE_TIME}),jsonExample:FP.DATE_TIME};case"DOUBLE":return SiI({fieldName:e,validation:wiI(t.v2)});case"FLOAT":return{type:"success",example:b0.float(FP.FLOAT),jsonExample:FP.FLOAT};case"INTEGER":return DiI({fieldName:e,validation:jiI(t.v2)});case"UINT_64":return{type:"success",example:b0.uint64(FP.INT64),jsonExample:FP.INT64};case"UINT":return{type:"success",example:b0.uint(FP.UINT),jsonExample:FP.UINT};case"BIG_INTEGER":return{type:"success",example:b0.bigInteger(FP.INT64.toString()),jsonExample:`${FP.INT64}`};case"LONG":return{type:"success",example:b0.long(FP.INT64),jsonExample:FP.INT64};case"UUID":return{type:"success",example:b0.uuid(FP.UUID),jsonExample:FP.UUID};default:ku(t.v1)}}function AiI(e){if(e?.type==="string")return e.default}function PiI(e){if(e?.type==="string")return e.validation}function wiI(e){if(e?.type==="double")return e.validation}function jiI(e){if(e?.type==="integer")return e.validation}function y5y(e){if(e<=FP.SAMPLE_STRINGS.length){let t=FP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return FP.SAMPLE_STRINGS[FP.SAMPLE_STRINGS.length-1]+".".repeat(e-FP.SAMPLE_STRINGS.length)}function EiI({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:b0.string({original:t}),jsonExample:t};if(r){let i=r.minLength,a=r.maxLength;if(i){let o=y5y(i);return{type:"success",example:b0.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=y5y(a);return{type:"success",example:b0.string({original:o}),jsonExample:o}}}let n=e??FP.STRING;return{type:"success",example:b0.string({original:n}),jsonExample:n}}function SiI({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:b0.double(r),jsonExample:r};if(n)return{type:"success",example:b0.double(n),jsonExample:n}}return{type:"success",example:b0.double(FP.DOUBLE),jsonExample:FP.DOUBLE}}function DiI({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:b0.integer(r),jsonExample:r};if(n)return{type:"success",example:b0.integer(n),jsonExample:n}}return{type:"success",example:b0.integer(FP.INT),jsonExample:FP.INT}}function fla({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=x8({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:f}=o;return{type:"success",example:dN.alias({value:c}),jsonExample:f}}case"enum":{let o=r.shape.values[0];return o==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dN.enum({value:o.name}),jsonExample:o.name.wireValue}}case"object":{let o={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let m=t[l.typeId];if(m==null)continue;let A=fla({fieldName:e,typeDeclaration:m,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});A!=null&&A.type==="success"&&A.example.type==="object"&&(Object.assign(o,A.jsonExample),c.push(...A.example.properties))}let f=CiI({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:u,jsonExample:s}=f;return{type:"success",example:dN.object({properties:[...c,...u.properties],extraProperties:u.extraProperties}),jsonExample:Object.assign({},o,s)}}case"undiscriminatedUnion":{let o=0;for(let c of r.shape.members){let f=x8({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(f.type==="failure"){++o;continue}let{example:u,jsonExample:s}=f;return{type:"success",example:dN.undiscriminatedUnion({index:o,singleUnionType:u}),jsonExample:s}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let s of r.shape.baseProperties){let l=x8({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});l.type==="success"&&(c[s.name.wireValue]=l.jsonExample)}let f=r.shape.baseProperties.map(s=>{let l=x8({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(l.type==="failure")throw new Error(`Failed to generate example for union base property ${s.name.wireValue}`);let{example:m}=l;return{name:s.name,value:m}}),u=r.shape.extends.flatMap(s=>{let l=t[s.typeId];if(l==null)throw new Error(`Failed to find extended type declaration with id ${s.typeId}`);let m=fla({fieldName:e,typeDeclaration:l,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(m==null||m.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${l.name.typeId}`);if(m.example.type!=="object")throw new Error(`Extended type declaration ${l.name.typeId} is not an object`);return m.example.properties});for(let s of r.shape.types){let l=s.shape._visit({noProperties:()=>({type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.noProperties()},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,...c}}),samePropertiesAsObject:m=>{let A=t[m.typeId];if(A==null)return{type:"failure",message:`Failed to find type declaration with id ${m.typeId}`};let P=fla({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:A,typeDeclarations:t,skipOptionalProperties:a});if(P==null)return{type:"failure",message:"Failed to generate example for type reference"};if(P.type==="failure")return P;let{example:C,jsonExample:I}=P;return{type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.samePropertiesAsObject({typeId:A.name.typeId,object:C.type==="object"?C:{properties:[],extraProperties:void 0}})},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,...typeof I=="object"?I:{},...c}}},singleProperty:m=>{let A=x8({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:m.type,typeDeclarations:t,skipOptionalProperties:a});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;return{type:"success",example:dN.union({discriminant:o,singleUnionType:{wireDiscriminantValue:s.discriminantValue,shape:tee.singleProperty(P)},baseProperties:f,extendProperties:u}),jsonExample:{[o.wireValue]:s.discriminantValue.wireValue,[m.name.wireValue]:C,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(l.type!=="failure")return l}}}return{type:"failure",message:"Failed to generate example for type reference"}}function CiI({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:o}){let c={},f=[];for(let u of[...r.properties??[],...r.extendedProperties??[]]){let s=x8({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:o});if(s.type==="failure"&&!oVr({typeDeclarations:n,typeReference:u.valueType}))return{type:"failure",message:`Failed to generate required property ${u.name.wireValue} b/c ${s.message}`};if(s.type==="failure")continue;let{example:l,jsonExample:m}=s;f.push({name:u.name,originalTypeDeclaration:t.name,value:l,propertyAccess:u.propertyAccess}),c[u.name.wireValue]=m}return{type:"success",example:dN.object({properties:f,extraProperties:void 0}),jsonExample:c}}function x8({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:`Exceeded max depth of ${n}`};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=fla({fieldName:e,typeDeclaration:o,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:f,jsonExample:u}=c;return{type:"success",example:{jsonExample:u,shape:nw.named({shape:f,typeName:o.name})},jsonExample:u}}case"container":{let o=h5y({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure"){let{example:u,jsonExample:s}=sVr({containerType:t.container});return{type:"success",example:{jsonExample:s,shape:nw.container(u)},jsonExample:s}}let{example:c,jsonExample:f}=o;return{type:"success",example:{jsonExample:f,shape:nw.container(c)},jsonExample:f}}case"primitive":{let{jsonExample:o,example:c}=v5y({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:nw.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:nw.unknown(o)},jsonExample:o}}}}function dla(e,t){let r=[];for(let n of e){let i=x8({fieldName:n.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function Hto(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&oVr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=x8({fieldName:n.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function tNu(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&oVr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=x8({fieldName:n.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,shape:n.allowMultiple?cse.exploded():cse.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var RTf=Mh.primitive({v1:yw.String,v2:l0.string({default:void 0,validation:void 0})});function Gto({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let o={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:K5.ok(iU.body(void 0)),docs:void 0},c=dla(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let f=dla(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;o.servicePathParameters=f.example;let u=dla(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;o.rootPathParameters=u.example;let s=tNu(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(s.type==="failure")return s;o.queryParameters=s.example;let l=Hto(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let m=Hto(r.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(m.type==="failure")return m;if(o.serviceHeaders=m.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 A={},P=[];if(t.requestBody.extends!=null)for(let C of t.requestBody.extends){let I=n[C.typeId];if(I==null)throw new Error(`Failed to find extended type declaration with id ${C.typeId}`);let T=fla({typeDeclaration:I,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});T!=null&&T.type==="success"&&Object.assign(A,T.jsonExample)}for(let C of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let I=x8({fieldName:C.name.wireValue,typeReference:C.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(I.type==="failure"&&!oVr({typeDeclarations:n,typeReference:C.valueType}))return{type:"failure",message:`Failed to generate required property ${C.name.wireValue} b/c ${I.message}`};if(I.type==="failure")continue;let{example:T,jsonExample:z}=I;P.push({name:C.name,originalTypeDeclaration:void 0,value:T}),A[C.name.wireValue]=z}o.request=RAe.inlinedRequestBody({jsonExample:A,properties:P,extraProperties:void 0});break}case"reference":{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.request=RAe.reference(P);break}default:ku(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 A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"streamParameter":{let A;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":A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1});break;default:ku(t.response.body.nonStreamResponse)}if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"streaming":{let A;switch(t.response.body.value.type){case"sse":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.sse([{data:{...P,jsonExample:C},event:""}]));break}case"json":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.stream([{...P,jsonExample:C}]));break}case"text":{if(A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.stream([{...P,jsonExample:C}]));break}default:ku(t.response.body.value)}break}case"text":{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:RTf,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=K5.ok(iU.body({...P,jsonExample:C}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:ku(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=K5.error({body:void 0,error:a.declaration.name});else{let A=x8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.response=K5.error({body:P,error:a.declaration.name})}try{return{type:"success",example:{id:D6i(o),url:IiI(t,o),...o},jsonExample:void 0}}catch(A){return{type:"failure",message:`Parse failure with exceptions ${A}`}}}function IiI(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=o});let n=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function NTf({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=dla(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(a.type==="failure")return a;i.pathParameters.push(...a.example);let o=dla(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let c=tNu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(c.type==="failure")return c;i.queryParameters=c.example;let f=Hto(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;i.headers.push(...f.example);let u=Hto(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(u.type==="failure")return u;i.headers.push(...u.example);let l=t.messages.filter(P=>P.origin==="client")[0];if(l!=null){let P=b5y({message:l,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:l.type,body:P})}let A=t.messages.filter(P=>P.origin==="server")[0];if(A!=null){let P=b5y({message:A,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:A.type,body:P})}return{type:"success",example:{...i,url:MiI(t,i)},jsonExample:void 0}}function b5y({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=x8({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return grt.reference(n.example)}function MiI(e,t){let r={};[...t.pathParameters].forEach(i=>{let a=i.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=o});let n=e.path.head+e.path.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function Jto(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function C6i(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function g5y({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let n=e.types,i={pathParameters:{},queryParameters:{},headers:{}};for(let o of t.pathParameters){let{userExample:c,autoExample:f}=Jto(o.v2Examples);c!==void 0?i.pathParameters[o.name.originalName]=c:f!==void 0&&(i.pathParameters[o.name.originalName]=f)}for(let o of t.queryParameters){let{userExample:c,autoExample:f}=Jto(o.v2Examples);if(c!==void 0)i.queryParameters[o.name.name.originalName]=c;else if(f!==void 0){if(r&&oVr({typeReference:o.valueType,typeDeclarations:n}))continue;i.queryParameters[o.name.name.originalName]=f}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let o of a){let{userExample:c,autoExample:f}=Jto(o.v2Examples);if(c!==void 0)i.headers[o.name.wireValue]=c;else if(f!==void 0){if(r&&oVr({typeReference:o.valueType,typeDeclarations:n}))continue;i.headers[o.name.wireValue]=f}}return i}function m5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:a}=g5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},f={endpoint:{method:e.method,path:BiI(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:i,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}case"inlinedRequestBody":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}case"reference":{let{userExamples:u,autoExamples:s}=C6i(e.requestBody.v2Examples);for(let[l,m]of Object.entries(u))o[l]={...f,requestBody:m};for(let[l,m]of Object.entries(s))c[l]={...f,requestBody:m};break}default:ku(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:f}}function BiI(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:a}=Jto(n.v2Examples),o=i??a,c;o==null?c=n.name.originalName:c=typeof o=="string"?o:JSON.stringify(o),t[n.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${t[n.pathParameter]}`)+n.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function rNu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,n={},i={},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:Mne.json(hZo(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let o=r.body,{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?hZo(s):s;n[u]={...a,body:Mne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?hZo(s):s;i[u]={...a,body:Mne.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?hZo(s):s;n[u]={...a,body:Mne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?hZo(s):s;i[u]={...a,body:Mne.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:f}=C6i(o.v2Examples);for(let[u,s]of Object.entries(c))n[u]={...a,body:Mne.stream([s])};for(let[u,s]of Object.entries(f))i[u]={...a,body:Mne.stream([s])}}break}case"streamParameter":break;default:ku(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:a}}function hZo(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var Kto=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},TiI=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function nNu({key:e,displayName:t,request:r,response:n,exampleStore:i,userOrAutoStore:a}){if(!i.has(e)){let o={displayName:t,request:r,response:n,codeSamples:void 0};return a[e]=o,TiI({exampleStore:i,key:e,example:o}),!0}return!1}function O5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let n={},i={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:f}=m5y({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u=Object.keys(o)[0],s=Object.values(o)[0],l=Object.keys(c)[0],m=Object.values(c)[0],A=qiI({endpoint:e,userRequestExamples:o,baseRequestExample:f,firstUserRequestName:u,firstUserRequestExample:s,firstAutoRequestName:l,firstAutoRequestExample:m,userResults:n,autoResults:i,exampleStore:a});if(RiI({endpoint:e,userRequestExamples:o,requestExamplesUsed:A,userResults:n,exampleStore:a}),Object.keys(n).length===0&&Object.keys(i).length===0){let{baseExample:P}=rNu({endpoint:e}),C=Kto(l??"base","base",void 0);nNu({key:C,displayName:l??"base",request:m??f,response:P,exampleStore:a,userOrAutoStore:i})}return{userFullExamples:n,autoFullExamples:i}}function qiI({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:n,firstUserRequestExample:i,firstAutoRequestName:a,firstAutoRequestExample:o,userResults:c,autoResults:f,exampleStore:u}){let s=e.v2Responses?.responses??[e.response],l=new Set;for(let m of s){let A=!1,{userResponseExamples:P,autoResponseExamples:C,baseExample:I}=rNu({endpoint:e,responseObject:m}),T=Object.keys(C)[0],z=Object.values(C)[0];for(let[U,q]of Object.entries(P)){let V,$;t[U]?($=t[U],l.add(U),V=Kto(U,U,m?.statusCode)):o&&a?($=o,V=Kto(a,U,m?.statusCode)):($=r,V=Kto("base",U,m?.statusCode)),nNu({key:V,displayName:U,request:$,response:q,exampleStore:u,userOrAutoStore:c})&&(A=!0)}if(!A){let U=$A(`${e.name.originalName}_example`);n&&i&&l.add(n);let q=Kto(n??a??"base",T??"base",m?.statusCode);nNu({key:q,displayName:n??a??U,request:i??o??r,response:z??I,exampleStore:u,userOrAutoStore:f})&&(A=!0)}}return l}function RiI({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=rNu({endpoint:e}),f=Object.values(a)[0],u=Object.keys(a)[0],s=Object.keys(o)[0],l=Object.values(o)[0],m=Object.entries(t).filter(([A])=>!r.has(A));for(let[A,P]of m){let C=Kto(A,u??s??"base",f?f.statusCode:l?l.statusCode:c.statusCode);nNu({key:C,displayName:A,request:P,response:f??l??c,exampleStore:i,userOrAutoStore:n})}}function yZo({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){let o=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=Gto({ir:e,service:i,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&o.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 f=e.errors[c.error.errorId];if(!f)continue;let u=Gto({ir:e,service:i,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:f}});u.type==="success"&&o.push({example:u.example})}a.autogeneratedExamples=o}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=NTf({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;i.examples=[...i.examples,o]}return e}function FTf({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let a of i.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:o,autoFullExamples:c}=O5y({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(u=>u.request!=null||u.response!=null))continue;let f=Object.values(a.v2Examples.userSpecifiedExamples).filter(u=>u!=null).flatMap(u=>u.codeSamples??[]);for(let[u,s]of Object.entries(c))c[u]={...s,codeSamples:f};for(let[u,s]of Object.entries(o))o[u]={...s,codeSamples:f}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=o}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=NTf({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;i.examples=[...i.examples,o]}return e}function P5y({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:b$({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?tee.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=b$({filteredIr:e,exampleTypeReference:r});return n!==void 0?tee.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function b$({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:nw.container(fB.list({...n,list:n.list.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:nw.container(fB.set({...n,set:n.set.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?b$({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:nw.container(fB.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?b$({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:nw.container(fB.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:nw.container(fB.map({...n,map:n.map.map(i=>{let a=b$({filteredIr:e,exampleTypeReference:i.key}),o=b$({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&o!==void 0?{key:a,value:o}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=b$({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:nw.named({...r,shape:dN.enum(n)})}),object:n=>({...t,shape:nw.named({...r,shape:dN.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:b$({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=P5y({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=b$({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:nw.named({...r,shape:dN.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function xTf({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function NiI({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function A5y({filteredIr:e,headers:t}){return t.map(r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function FiI({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=b$({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=b$({filteredIr:e,exampleTypeReference:r});return n!==void 0?RAe.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function xiI({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>K5.ok(iU.body(n!=null?b$({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>K5.ok(iU.stream(n.map(i=>b$({filteredIr:e,exampleTypeReference:i})).filter(pj))),sse:n=>K5.ok(iU.sse(n.map(({event:i,data:a})=>{let o=b$({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:i,data:o}:void 0}).filter(pj))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>K5.error({error:r,body:n!=null?b$({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function zTf({filteredIr:e,example:t}){return{...t,rootPathParameters:xTf({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:xTf({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:xTf({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:A5y({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:A5y({filteredIr:e,headers:t.endpointHeaders}),queryParameters:NiI({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?FiI({filteredIr:e,requestBody:t.request}):void 0,response:xiI({filteredIr:e,response:t.response})}}function w5y({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=b$({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dN.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dN.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:b$({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=P5y({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dN.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=b$({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dN.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function QTf(e,t){if(t==null)return e;let r=Una(e.types,c=>t.hasType(c)),n=Object.fromEntries(Object.entries(r).map(([c,f])=>{let u=[];if(f.userProvidedExamples=f.userProvidedExamples.map(s=>w5y({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),f.shape.type==="object"){for(let s of f.shape.properties)t.hasProperty(c,s.name.wireValue)&&u.push(s);return[c,{...f,shape:YE.object({...f.shape,properties:u})}]}return[c,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,f])=>{let u=f.filter(s=>t.hasWebhook(s)).map(s=>{let l=s.id;return s.payload.type==="inlinedPayload"&&l!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(m=>t.hasWebhookPayloadProperty(l,m.name.wireValue))}),s});return[c,u]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,f])=>[c,{...f}])):{},o=e.environments;if(o){switch(o.environments.type){case"singleBaseUrl":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}o.defaultEnvironment&&(t.hasEnvironmentId(o.defaultEnvironment)||(o.defaultEnvironment=void 0))}return{...e,environments:o,types:n,errors:Una(e.errors,c=>t.hasError(c)),services:Bg(Una(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(u=>({...u,example:zTf({filteredIr:t,example:u.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?zTf({filteredIr:t,example:u.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(u=>t.hasQueryParameter(f.id,u.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(u=>t.hasRequestProperty(f.id,u.name.wireValue))}}:f))})),websocketChannels:a,webhookGroups:i,serviceTypeReferenceInfo:ziI(e.serviceTypeReferenceInfo,t)}}function ziI(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}function pla(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Krt(e){return e.allParts.map(t=>t.originalName).join("/")}var pB={generateTypeId:e=>`type_${Krt(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${Krt(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${Krt(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${Krt(e)}`,generateSubpackageId:e=>`subpackage_${Krt(e)}`,generateEndpointId:(e,t)=>{let r=Krt(e.fernFilepath),n=t.name.originalName;return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${Krt(e)}`,generateWebhookId:(e,t)=>`webhooks_${Krt(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${Krt(e)}`};function $to(e){return e.type!=null}var iNu=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:n,environments:i,services:a,endpoints:o,webhooks:c,subpackages:f,queryParameters:u,requestProperties:s,webhookPayloadProperties:l,channels:m}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=o,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=f,this.requestProperties=s,this.queryParameters=u,this.channels=m}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=pB.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=pB.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=pB.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var _la=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=QiI(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let o=pB.generateTypeId(t),c={typeId:o,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[o]=c,this.typesReferencedByService[o]==null&&(this.typesReferencedByService[o]=new Set),this.properties[o]={typeId:o,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=pB.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){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=pB.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&TJ(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=pB.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,f=new Set;for(let u of[...t.headers,...r.headers])TJ(u.valueType,o,f);for(let u of[...t.pathParameters,...r.pathParameters])TJ(u.valueType,o,f);for(let u of r.queryParameters)TJ(u.valueType,o,f);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=pla(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:u}}r.requestBody!=null&&R7._visit(r.requestBody,{inlinedRequestBody:u=>{for(let s of u.extends)aNu(s,o,f);for(let s of u.properties)TJ(s.valueType,o,f);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&rU(n.request.body)){let s=pla(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:s}}},reference:({requestBodyType:u})=>{TJ(u,o,f)},fileUpload:({properties:u})=>{for(let s of u)Bne._visit(s,{file:xc,bodyProperty:({valueType:l})=>{TJ(l,o,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+s.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&fN._visit(r.response.body,{fileDownload:xc,json:u=>{TJ(u.responseBodyType,o,f)},streaming:u=>{u._visit({sse:s=>TJ(s.payload,o,f),json:s=>TJ(s.payload,o,f),text:xc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:s=>TJ(s.payload,o,f),json:s=>TJ(s.payload,o,f),text:xc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&TJ(u.nonStreamResponse.value.responseBodyType,o,f)},text:xc,bytes:xc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{c.add(pB.generateErrorId(u.error)),f.add(u.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:i,referencedTypes:o,referencedErrors:c,referencedSubpackages:f}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=pB.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let o=a.id;this.endpointsNeededForAudience.add(o),this.endpoints[o]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(i),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,n){let i=r.id;if(i==null)return;let a=new Set,o=new Set;r.payload!=null&&Cve._visit(r.payload,{inlinedPayload:c=>{for(let f of c.extends)aNu(f,a,o);for(let f of c.properties)TJ(f.valueType,a,o);if(n?.payload!=null&&typeof n.payload=="object"&&!$to(n.payload)){let f=pla(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:f}}},reference:({payloadType:c})=>{TJ(c,a,o)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),o.add(t),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:o}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t))}addChannel(t,r,n,i){if(r==null)return;let a=new Set,o=new Set;for(let c of n.messages)Dfe._visit(c.body,{reference:({bodyType:f})=>{TJ(f,a,o)},inlinedBody:f=>{for(let u of f.extends)aNu(u,a,o);for(let u of f.properties)TJ(u.valueType,a,o)},_other:()=>{}});for(let c of n.queryParameters)TJ(c.valueType,a,o);o.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:o}}markChannelForAudiences(t,r,n){r!=null&&this.hasAudience(n)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(c);for(let u of f.referencedErrors){if(r.has(u))continue;r.add(u);let s=this.getErrorNode(u);this.addReferencedTypes(t,s.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(c);this.addReferencedTypes(t,f.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(c);this.addReferencedTypes(t,f.referencedTypes)}let n={},i={},a={},o={};if(this.audiences.type==="filtered"){for(let[c,f]of Object.entries(this.properties)){if(!t.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}u.size>0&&(n[c]=u),n[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}i[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.parametersByAudience[s];l?.forEach(m=>{u.add(m)})}a[c]=u.size>0?u:void 0}for(let[c,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let u=new Set;for(let s of this.audiences.audiences){let l=f.propertiesByAudience[s];l?.forEach(m=>{u.add(m)})}o[c]=u.size>0?u:void 0}}return new iNu({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:o,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t]??=new Set;if(n.has(r))return;n.add(r);let i=this.getTypeNode(t);for(let a of i.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let o=i.descendantsByAudience[a];if(o!=null)o.forEach(c=>{t.add(c)});else{i.allDescendants.forEach(c=>{t.add(c)});break}}else i.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}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(n=>r.audiences.has(n));default:ku(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(pB.generateSubpackageId(n))}}};function QiI(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:ku(e)}}function TJ(e,t,r){Mh._visit(e,{container:n=>{LiI(n,t,r)},named:n=>{aNu(n,t,r)},primitive:xc,unknown:xc,_other:xc})}function aNu(e,t,r){t.add(pB.generateTypeId(e)),r.add(e.fernFilepath)}function LiI(e,t,r){Xw._visit(e,{list:n=>{TJ(n,t,r)},map:n=>{TJ(n.keyType,t,r),TJ(n.valueType,t,r)},optional:n=>{TJ(n,t,r)},nullable:n=>{TJ(n,t,r)},set:n=>{TJ(n,t,r)},literal:xc,_other:xc})}var UiI=[np.AvailabilityStatus.GeneralAvailability];function bPi(e){return e!==void 0&&!UiI.includes(e.status)}var LTf=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},vZo=class{errors;constructor(){this.errors=new LTf}async check({from:t,to:r}){let n=this.toInternalIr(t),i=this.toInternalIr(r),a=D6i(n),o=D6i(i);if(a===o)return{bump:"no_change",isBreaking:!1,errors:[]};let c=this.checkBreaking({from:n,to:i});return{bump:c.isBreaking?"major":"minor",isBreaking:c.isBreaking,errors:c.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}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 n=this.errors.hasErrors();return{bump:n?"major":"minor",isBreaking:n,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(bPi(i.availability))continue;let a=r[n];if(!a){this.errors.add(`Type "${n}" was removed.`);continue}if(bPi(a.availability)){this.errors.add(`Type "${n}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:i,to:a})||this.errors.add(`Type "${n}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){let a=Object.values(r).find(o=>o.name.errorId===i.name.errorId);if(!a){this.errors.add(`Error "${i.name.errorId}" with status code "${i.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:i,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[n,i]of Object.entries(t)){if(bPi(i.availability)||(i.endpoints?.every(o=>bPi(o.availability))??!1))continue;let a=r[n];if(!a){this.errors.add(`Service "${n}" was removed.`);continue}if(bPi(a.availability)){this.errors.add(`Service "${n}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:n,from:i,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:n}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:n})}checkEndpointsBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.endpoints.map(o=>[o.id,o])),a=Object.fromEntries(n.endpoints.map(o=>[o.id,o]));for(let[o,c]of Object.entries(i)){if(bPi(c.availability))continue;let f=a[o];if(!f){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(bPi(f.availability)){this.errors.add(`Endpoint "${o}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:o,from:c,to:f})}}checkEndpointBreakingChanges({id:t,from:r,to:n}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:n.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:n.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:n.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:n.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),r.requestBody!=null&&(n.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:n.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(n.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:n.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&n.pagination==null||r.pagination==null&&n.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.originalName,o])),a=Object.fromEntries(n.map(o=>[o.name.originalName,o]));for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Path parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Path parameter "${o}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(n.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Query parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Query parameter "${o}" type changed in endpoint "${t}".`),c.allowMultiple!==f.allowMultiple&&this.errors.add(`Query parameter "${o}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(n.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(i)){let f=a[o];if(!f){this.errors.add(`Header "${o}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:f.valueType})||this.errors.add(`Header "${o}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:n}){r!==n&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:n}){this.areHttpPathsCompatible({from:r,to:n})||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 n=0;n<t.parts.length;n++){let i=t.parts[n];if(i==null)return!1;let a=r.parts[n];if(a==null||i.pathParameter!==a.pathParameter||i.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:n}){switch(r.type){case"inlinedRequestBody":if(n.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:n}))return;break;case"reference":if(n.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:n}))return;break;case"fileUpload":if(n.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:n}))return;break;case"bytes":if(n.type==="bytes")return;break;default:ku(r)}this.errors.add(`Request body type changed from "${r.type}" to "${n.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let n=this.getInlinedRequestBody(t),i=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:n,to:i}),Object.entries(n).every(([a,o])=>{let c=i[a];return c?this.areTypeReferencesCompatible({from:o,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 n=this.getFileUploadRequest(t.properties),i=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:n,to:i});for(let[a,o]of Object.entries(n)){let c=i[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(o==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o!=="file"&&o!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:o,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:n}){if(r.statusCode!==n.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${n.statusCode}".`),!(r.body==null&&n.body==null)){if(r.body==null||n.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(n.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"fileDownload":if(n.body.type==="fileDownload")return;break;case"text":if(n.body.type==="text")return;break;case"bytes":if(n.body.type==="bytes")return;break;case"streaming":if(n.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"streamParameter":if(n.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:n.body.streamResponse});return}break;default:ku(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${n.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:ku(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bPi(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:ku(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 n=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),i=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(n).length!==Object.keys(i).length?!1:Object.values(n).every(a=>{let o=i[a.name.wireValue];return o?this.areNameAndWireValuesCompatible({from:a.name,to:o.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let n=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),i=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(n).map(([a,o])=>[a,o.valueType])),to:Object.fromEntries(Object.entries(i).map(([a,o])=>[a,o.valueType]))}),Object.values(n).every(a=>{let o=i[a.name.wireValue];return o?this.areObjectPropertiesCompatible({from:a,to:o}):(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 n=new Set(t.extends.map(u=>this.getKeyForDeclaration(u))),i=new Set(r.extends.map(u=>this.getKeyForDeclaration(u)));for(let u of n)if(!i.has(u))return this.errors.add(`Extended type "${u}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(u=>[u.name.wireValue,u])),o=Object.fromEntries(r.baseProperties.map(u=>[u.name.wireValue,u]));for(let u of Object.values(a)){let s=o[u.name.wireValue];if(!s)return this.errors.add(`Union type with discriminant value "${u.name.wireValue}" no longer has a property named "${u.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:u,to:s}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([u,s])=>[u,s.valueType])),to:Object.fromEntries(Object.entries(o).map(([u,s])=>[u,s.valueType]))});let c=Object.fromEntries(t.types.map(u=>[u.discriminantValue.wireValue,u])),f=Object.fromEntries(r.types.map(u=>[u.discriminantValue.wireValue,u]));return Object.values(c).every(u=>{let s=f[u.discriminantValue.wireValue];return s?this.areSingleUnionTypesCompatible({from:u.shape,to:s.shape}):(this.errors.add(`Union type for discriminant value "${u.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:ku(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((n,i)=>{let a=r.members[i];return a?this.areTypeReferencesCompatible({from:n.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${i} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||i==="file"||i==="fileArray"||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" 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:ku(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:ku(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:ku(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((n,i)=>{let a=r.allParts[i];return a==null?!1:this.areNamesCompatible({from:n,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let n of[...t.extendedProperties??[],...t.properties])r[n.name.wireValue]=n.valueType;return r}getFileUploadRequest(t){let r={};for(let n of t)switch(n.type){case"file":r[n.value.key.wireValue]="file";break;case"bodyProperty":r[n.name.wireValue]=n.valueType;break;default:ku(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>i.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function hla(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:a}=WiI(e.environments,t.environments,r),{services:o,websocketChannels:c}=HiI(e,t,i,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:n,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:o,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:ViI(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(f=>!e.rootPackage.subpackages?.includes(f))],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??[]],generationMetadata:e.generationMetadata??t.generationMetadata}}function ViI(e,t){let r=e;for(let[n,i]of Object.entries(t))r[n]==null?r[n]=i:r[n]={name:i.name,displayName:i.displayName,fernFilepath:i.fernFilepath,hasEndpointsInTree:r[n].hasEndpointsInTree||i.hasEndpointsInTree,navigationConfig:r[n].navigationConfig??i.navigationConfig,docs:r[n].docs??i.docs,service:r[n].service??i.service,subpackages:[...r[n].subpackages??[],...(i.subpackages??[]).filter(a=>!r[n]?.subpackages?.includes(a))],webhooks:r[n].webhooks??i.webhooks,websocket:r[n].websocket??i.websocket,errors:[...r[n].errors??[],...i.errors??[]],types:[...r[n].types??[],...i.types??[]]};return r}function WiI(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 n=j5y(e),i=j5y(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:mJ.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=n?t.defaultEnvironment:e.defaultEnvironment,o=e.environments,c=t.environments;if(o.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let f=n?c:o,u=n?o:c,s={},{deconflictedEnvironments2:l,changedBaseUrlIds2:m}=GiI(f,u,r);if(f.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let A="Base",P=r.generateName("Base");return f.environments.forEach(C=>{s[C.id]=A}),{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[{id:A,name:P},...l.environments.map(C=>({id:C.id,name:C.name}))],environments:f.environments.map(C=>({id:C.id,name:C.name,urls:{[A]:C.url,...Object.fromEntries(l.environments.map(I=>[I.id,I.url]))},docs:void 0}))})},changedBaseUrlIds1:n?m:s,changedBaseUrlIds2:n?s:m}}if(o.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||o.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let f=o.type==="singleBaseUrl"?o:c,u=o.type==="multipleBaseUrls"?o:c,{deconflictedEnvironments1:s,changedBaseUrlIds1:l}=JiI(f,u,r);return{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[...u.baseUrls,...s.environments.map(m=>({id:m.id,name:m.name}))],environments:u.environments.map(m=>({...m,urls:{...m.urls,...Object.fromEntries(s.environments.map(A=>[A.id,A.url]))}}))})},changedBaseUrlIds1:o.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:o.type==="singleBaseUrl"?void 0:l}}if(o.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:f,changedBaseUrlIds:u}=KiI(o,c,r);return{environments:{defaultEnvironment:a,environments:mJ.multipleBaseUrls({baseUrls:[...o.baseUrls,...f.baseUrls],environments:o.environments.flatMap(s=>f.environments.map(l=>({...s,urls:{...s.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:u}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function HiI(e,t,r,n){if(r!=null)for(let[o,c]of Object.entries(r)){for(let f of Object.values(e.services))for(let u of Object.values(f.endpoints))u.baseUrl==o&&(u.baseUrl=c),u.v2BaseUrls?.includes(o)&&(u.v2BaseUrls=u.v2BaseUrls.map(s=>s===o?c:s));for(let f of Object.values(e.websocketChannels??{}))f.baseUrl==o&&(f.baseUrl=c)}if(n!=null)for(let[o,c]of Object.entries(n)){for(let f of Object.values(t.services))for(let u of Object.values(f.endpoints))u.baseUrl==o&&(u.baseUrl=c),u.v2BaseUrls?.includes(o)&&(u.v2BaseUrls=u.v2BaseUrls.map(s=>s===o?c:s));for(let f of Object.values(t.websocketChannels??{}))f.baseUrl==o&&(f.baseUrl=c)}let i=e.services;for(let[o,c]of Object.entries(t.services))i[o]==null?i[o]=c:i[o]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...i[o].endpoints??[],...c.endpoints],pathParameters:[...i[o].pathParameters??[],...c.pathParameters??[]],headers:[...i[o].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...i[o].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:i,websocketChannels:a}}function GiI(e,t,r){let n={},i=new Set(e.environments.map(u=>u.id)),a=new Set(e.environments.map(u=>u.name)),o=new Map(e.environments.map(u=>[u.url,u.id])),c=t.environments.filter(u=>{let s=o.get(u.url);return s!=null?(n[u.id]=s,!1):!0}).map(u=>{if(i.has(u.id)||a.has(u.name)){let s=UTf(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u});return{deconflictedEnvironments2:mJ.singleBaseUrl({environments:c}),changedBaseUrlIds2:n}}function JiI(e,t,r){let n={},i=new Set(t.baseUrls.map(f=>f.id)),a=new Set(t.baseUrls.map(f=>f.name)),o=e.environments.map(f=>{if(i.has(f.id)||a.has(f.name)){let u=UTf(f.id,i);return n[f.id]=u,{...f,id:u,name:r.generateName(u)}}return f});return{deconflictedEnvironments1:mJ.singleBaseUrl({environments:o}),changedBaseUrlIds1:n}}function KiI(e,t,r){let n={},i=new Set(e.baseUrls.map(u=>u.id)),a=new Set(e.baseUrls.map(u=>u.name)),o=t.baseUrls.map(u=>{if(i.has(u.id)||a.has(u.name)){let s=UTf(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u}),c=t.environments.map(u=>({...u,urls:Object.fromEntries(Object.entries(u.urls).map(([s,l])=>[n[s]??s,l]))}));return{deconflictedEnvironments:mJ.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:n}}function j5y(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 UTf(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}var gO=class e{breadcrumbs=[];context;static STRING=np.TypeReference.primitive({v1:"STRING",v2:np.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=np.TypeReference.container(np.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var S5y=require("fs/promises");var VTf=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:n,position:i,lineStart:a}=t;this._map[r]={line:n,position:i,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,a=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:o,position:c,lineStart:f}=r;this._path.length===0?this._map["."+n]={line:o,position:c,lineStart:f}:this._fragments.push({path:this._path.join(".")+"."+n,line:o,position:c,lineStart:f})}else if(i==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,f=>{c++,!((!f.children||f.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(f,f.path):(o.children.push({...f,path:f.path.slice(a.length+1)}),o.line=f.line,o.position=f.position,o.lineStart=f.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(i==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,f=n.length;this.iterFragments(a,u=>{c.has(u.position)||(f--,c.add(u.position),this._path.length===1?this.resolveNode(u,`${a}.${f}`):(o.children.push({...u,path:f.toString()}),o.line=u.line,o.position=u.position,o.lineStart=u.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:a}=r;this._map["."]={line:n,position:i,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},E5y=VTf;var gPi;(function(e){e.WARNING="warning",e.ERROR="error"})(gPi||(gPi={}));var I6i=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new WTf({logger:t,relativePathToFile:ru.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let a=i.path?i.path.join("->"):"",o=`${i.message}|${i.level||gPi.WARNING}|${a}`;r.has(o)?n++:(r.add(o),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===gPi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gPi.WARNING&&!t))switch(r.level){case gPi.ERROR:if(this.logger.log(oE.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),i=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(oE.Debug,` - at location (${i})`)}break}}},WTf=class{logger;relativePathToFile;map=new E5y;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,S5y.readFile)(this.relativePathToFile,"utf-8");jg.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(oE.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 hee=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=_Ce({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((i,a)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||a===0&&i==="components"||a===1&&i==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(i)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=$A(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:gPi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[o]}return i==null?(n||this.errorCollector.collect({level:gPi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}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,n,i=!1,a=null,o;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),s=u[0];if(n=u[1],!s)return{resolved:!1};o=s;let l=await fetch(s);if(!l.ok)return{resolved:!1};try{let m=await l.text();try{a=JSON.parse(m),r=a}catch{a=jg.load(m),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let c=n??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let f=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of f){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,u,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,n,i));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(n.has(o))return t;n.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(n.delete(o),c.resolved)return c.value}else{let c=`${i}${o}`;if(n.has(c))return t;n.add(c);let f=r,u=o.substring(2).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~"));for(let s of u){if(typeof f!="object"||f===null)return t;f=f[s]}if(f!=null){let s=await this.resolveNestedExternalReferences(f,r,n,i);return n.delete(o),s}n.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,n,i):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let a=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([a,t.example])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.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:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return yLr.ReadOnly;if(i)return yLr.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let a=i;if(this.isReferenceObject(i)){let c=this.resolveReference({reference:i});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,n=n&&o.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new Sse.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let i=new Sse.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:Ine.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Mh.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(([n])=>n!==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 n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}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||"summary"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 n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var UD=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}};var Sse={};yf(Sse,{AudienceExtension:()=>oNu,FernAvailabilityExtension:()=>sNu,FernEnumExtension:()=>uNu,FernIgnoreExtension:()=>yla,FernOptionalExtension:()=>cNu,FernTypeExtension:()=>pNu,FernTypeNameExtension:()=>_Nu,SdkGroupNameExtension:()=>lNu,SdkMethodNameExtension:()=>fNu,ServerFromOperationNameExtension:()=>dNu});var oNu=class extends UD{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var sNu=class extends UD{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),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 Ine.InDevelopment;case"PRE_RELEASE":case"BETA":return Ine.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return Ine.GeneralAvailability;case"DEPRECATED":return Ine.Deprecated;default:return}}};var $iI=nl.object({snake:nl.string().optional(),camel:nl.string().optional(),screamingSnake:nl.string().optional(),pascal:nl.string().optional()}),YiI=nl.object({description:nl.string().optional(),name:nl.string().optional(),casing:$iI.optional()}),D5y=nl.record(YiI);var uNu=class extends UD{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=D5y.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 yla=class extends UD{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),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 cNu=class extends UD{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),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 lNu=class extends UD{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var fNu=class extends UD{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var dNu=class extends UD{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var pNu=class extends UD{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var _Nu=class extends UD{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var rqr=class extends gO{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new _la(n),this.ir={auth:{docs:void 0,requirement:np.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:np.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,generationMetadata:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new yla({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new yla({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):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,n=FTf({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let i=yZo({ir:t,exampleGeneration:r});return{...t,...i,...n}}return{...t,...n}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>n.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>i.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),a=await this.context.resolveMaybeExternalReference(n);if(a.resolved){if(n=a.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:a}){let o=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:n}),f=[...o].map(l=>this.context.casingsGenerator.generateName(l)),u=f[f.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>$A(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:f,finalpart:u,endpointGroupDisplayName:i})),this.ir.services[c.service]?.endpoints.push(t);let s=this.ir.services[c.service];s!=null&&(this.irGraph.addEndpoint(s,t),this.irGraph.markEndpointForAudience(s.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let a=i?.join(".")??r,o=this.getOrCreatePackage({group:i});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let a=$A(i?.join(".")),o=$A(r),c=this.context.namespace?`${$A(this.context.namespace)}/`:"",f=a?`channel_${c}${a}`:`channel_${c}${o}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[f]:t},f!==""?u.websocket==null&&(u.websocket=f):this.ir.rootPackage.websocket="";let s=this.context.createFernFilepath();this.irGraph.addChannel(s,f,t),n!=null&&this.irGraph.markChannelForAudiences(s,f,n)}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[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=Object.keys(i).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...i,[o]:n})}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,n])=>[r,n.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 n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:ZX(""),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(i=>$A(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let a=r[i]??"",c=`subpackage_${r.slice(0,i+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 f=this.ir.subpackages[c];n.subpackages.includes(c)||n.subpackages.push(c),n=f}return n}};var z6={};yf(z6,{AbstractConverters:()=>GTf,ExampleConverter:()=>eht,SchemaConverters:()=>HTf,ServersConverter:()=>$rt});var GTf={};yf(GTf,{AbstractMediaTypeObjectConverter:()=>vNu,AbstractParameterConverter:()=>bNu});var eht=class e extends gO{MAX_DEPTH=12;EXAMPLE_STRING=FP.STRING;EXAMPLE_NUMBER=FP.DOUBLE;EXAMPLE_BOOLEAN=FP.BOOLEAN;EXAMPLE_INTEGER=FP.INT;EXAMPLE_DATE=FP.DATE;EXAMPLE_DATE_TIME=FP.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:f=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=f}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,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,validExample:n??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 n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,validExample:n,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}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):n!=null&&(c=n);let f;return o!=null?typeof o=="boolean"?f=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:f=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):i!=null&&(f=i),c!==void 0&&f!==void 0?(t<c||t>f)&&(t=c+(f-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):f!==void 0&&t>f&&(t=f-Math.abs(f*.1)),Number(Number(t).toPrecision(3))}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,n=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)??n,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,n=this.example??t.example,a=(Array.isArray(n)?n:[n]).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()),o=a.every(c=>c?.isValid??!1)&&!r;return{isValid:o,coerced:!1,validExample:a.map(c=>c.validExample),errors:o?[]: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,n=Object.entries(t.properties??{}).map(([f,u])=>{if(typeof u!="object")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(u)&&!this.isRequiredProperty({key:f,resolvedSchema:t}))return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in u&&u.readOnly===!0&&"writeOnly"in u&&u.writeOnly===!0)return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in u&&u.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in u&&u.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(f in r)||!("nullable"in u)&&r[f]==null||"nullable"in u&&u.nullable===!0&&r[f]===void 0,l=!t.required?.includes(f);if(s&&l){if(this.example===void 0&&this.generateOptionalProperties){let m=this.maybeResolveSchemaExample(u),A=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:u,example:m,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:f,result:A.convert()}}return{key:f,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let A=r[f]??this.maybeResolveSchemaExample(u),C=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:u,example:A,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:f,result:C}}}),i=(t.allOf??[]).map((f,u)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${u}]`],context:this.context,schema:{...t,...f,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=n.every(f=>f.result.isValid)&&i.every(f=>f.isValid),o=Object.fromEntries(n.map(({key:f,result:u})=>[f,u.validExample]).filter(([f,u])=>u!==void 0));for(let f of i)if(typeof f.validExample=="object"&&f.validExample!==null){let u=f.validExample;o={...o,...Object.fromEntries(Object.entries(u).filter(([s,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let f=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},u=new Set(Object.keys(o??{}));Object.keys(r).filter(l=>!u.has(l)).forEach(l=>{let A=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:A})})}for(let{key:f,result:u}of c)u.validExample!==void 0&&o[f]===void 0&&(o[f]=u.validExample);if(Object.keys(o).length===0){let f=i.find(u=>u.validExample!==void 0&&(typeof u.validExample!="object"||u.validExample===null));f&&(o=f.validExample)}return{isValid:a,coerced:!1,validExample:o,errors:[...n.flatMap(({result:f})=>f.errors),...i.flatMap(f=>f.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((o,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:o},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(o=>o?.isValid??!1),a=r.find(o=>o.isValid)?.validExample??r[0]?.validExample??null;return{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(o=>o?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let i=this.example??this.maybeResolveSchemaExample(t),a=[],o=null;for(let u=0;u<n.length;u++){let s=n[u];if(!s)continue;let l=r==="oneOf"?{...t,...s,oneOf:void 0}:s,m=i??this.maybeResolveSchemaExample(l),P=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${u}]`],context:this.context,schema:l,example:m,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(P.isValid&&!P.coerced)return{isValid:!0,coerced:!1,validExample:P.validExample,errors:[]};a.push(P),P.isValid&&o===null&&(o=P)}let c=o!==null,f=o?.validExample??a[0]?.validExample;return{isValid:c,coerced:!1,validExample:f,errors:c?[]:a.flatMap(u=>u.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}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){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var HTf={};yf(HTf,{ArraySchemaConverter:()=>ero,EnumSchemaConverter:()=>Yto,ObjectSchemaConverter:()=>Xto,OneOfSchemaConverter:()=>Zto,PrimitiveSchemaConverter:()=>kto,SchemaConverter:()=>M6i,SchemaOrReferenceConverter:()=>pPe});function C5y(e){return ree({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Mh.primitive({v1:"BASE_64",v2:l0.base64({})});case"BOOLEAN":return Mh.primitive({v1:"BOOLEAN",v2:l0.boolean({default:void 0})});case"DATE":return Mh.primitive({v1:"DATE",v2:l0.date({})});case"DATE_TIME":return Mh.primitive({v1:"DATE_TIME",v2:l0.dateTime({})});case"FLOAT":return Mh.primitive({v1:"FLOAT",v2:l0.float({})});case"DOUBLE":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:void 0,validation:void 0})});case"UINT":return Mh.primitive({v1:"UINT",v2:l0.uint({})});case"UINT_64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({})});case"INTEGER":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:void 0,validation:void 0})});case"LONG":return Mh.primitive({v1:"LONG",v2:l0.long({default:void 0})});case"STRING":return Mh.primitive({v1:"STRING",v2:l0.string({default:void 0,validation:void 0})});case"UUID":return Mh.primitive({v1:"UUID",v2:l0.uuid({})});case"BIG_INTEGER":return Mh.primitive({v1:"BIG_INTEGER",v2:l0.bigInteger({default:void 0})});default:return}},unknown:()=>Mh.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Mh.container(Xw.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Mh.container(Xw.list(t))},optional:t=>{if(t!=null)return Mh.container(Xw.optional(t))},nullable:t=>{if(t!=null)return Mh.container(Xw.nullable(t))},set:t=>{if(t!=null)return Mh.container(Xw.set(t))},literal:t=>Mh.container(Xw.literal(t._visit({string:r=>Sfe.string(r),boolean:r=>Sfe.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var Yto=class extends gO{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let a=i.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.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 n=this.context.getAsString(this.schema.default);return{type:YE.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r})}}};var hNu=class extends gO{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}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=Mh.container(Xw.map({keyType:gO.STRING,valueType:Mh.unknown()}));return{type:YE.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new pPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Mh.container(Xw.map({keyType:gO.STRING,valueType:r.type})),i=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])i.add(a);for(let a of Object.keys(r.inlinedTypes))i.add(a);return{type:YE.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};function bZo({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let a=[],o={},c={},f=new Set;for(let[u,s]of Object.entries(e??{})){let l=[...r,"properties",u];if(typeof s!="object"){i.collect({message:`Schema property ${u} should be an object`,path:l});continue}let m=XiI(r,s,n)??n.convertBreadcrumbsToName(l),A="nullable"in s?s.nullable:!1,C=new pPe({context:n,breadcrumbs:l,schemaOrReference:s,schemaIdOverride:m,wrapAsOptional:!t.includes(u),wrapAsNullable:A}).convert();if(C!=null){a.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:C.type,docs:s.description,availability:C.availability,propertyAccess:n.getPropertyAccess(s),v2Examples:C.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...C.inlinedTypes},C.schema?.typeDeclaration.referencedTypes!=null&&C.schema.typeDeclaration.referencedTypes.forEach(I=>{f.add(I)});for(let I of C.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(o))f.add(u);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:f}}function XiI(e,t,r){return r.isReferenceObject(t)?void 0:new Sse.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var Xto=class extends gO{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:YE.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:a}=bZo({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=i,f=this.schema.required!=null&&this.schema.required.length>0,u=n,s=a;for(let[l,m]of(this.schema.allOf??[]).entries()){let A=[...this.breadcrumbs,"allOf",l.toString()],P;if(this.context.isReferenceObject(m)){let U=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:A});if(U==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(m)}`);continue}if(P=U,typeof P.additionalProperties=="boolean"&&P.additionalProperties&&(t=!0),!f||Object.keys(P.properties??{}).every(q=>!this.schema.required?.includes(q))){this.addTypeReferenceToExtends({reference:m,breadcrumbs:A,extends_:o,referencedTypes:c});continue}}else P=m;typeof P.additionalProperties=="boolean"&&P.additionalProperties&&(t=!0);let{convertedProperties:C,inlinedTypesFromProperties:I,referencedTypes:T,propertiesByAudience:z}=bZo({properties:P.properties??{},required:[...this.schema.required??[],...P.required??[]],breadcrumbs:A,context:this.context,errorCollector:this.context.errorCollector});r.push(...C),u={...u,...I},s={...s,...z},T.forEach(U=>{c.add(U)})}for(let l of Object.keys(u))c.add(l);return{type:YE.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(pj),extendedProperties:[],extraProperties:t}),propertiesByAudience:s,referencedTypes:c,inlinedTypes:u}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&n.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&i.add(o)}};var yNu=class extends UD{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Zto=class extends gO{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new yNu({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,n]of Object.entries(this.schema.discriminator?.mapping??{})){let i=this.context.resolveReference({reference:{$ref:n},breadcrumbs:this.breadcrumbs});if(i.resolved&&!Object.keys(i.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,n={};for(let[f,u]of Object.entries(this.schema.discriminator.mapping??{})){let s=new pPe({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",f]}),l=this.context.getTypeIdFromSchemaReference({$ref:u});l!=null&&r.add(l);let m=s.convert();if(m?.type!=null&&l!=null){for(let P of Object.keys(m?.inlinedTypes??{}))r.add(P);for(let P of m.schema?.typeDeclaration.referencedTypes??[])r.add(P);let A=this.context.casingsGenerator.generateNameAndWireValue({name:f,wireValue:f});t.push({docs:void 0,discriminantValue:A,availability:m.availability,displayName:f,shape:Efe.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:f})}),n={...n,...m.inlinedTypes}}}let{convertedProperties:i,referencedTypes:a,inlinedTypesFromProperties:o}=bZo({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[f,u]of(this.schema.allOf??[]).entries()){let s=[...this.breadcrumbs,"allOf",f.toString()];if(this.context.isReferenceObject(u)){let l=this.context.convertReferenceToTypeReference({reference:u,breadcrumbs:s});if(l.ok){let A=this.context.typeReferenceToDeclaredTypeName(l.reference);A!=null&&c.push(A)}let m=this.context.getTypeIdFromSchemaReference(u);m!=null&&r.add(m);continue}}for(let f of Object.keys({...n,...o}))r.add(f);return{type:YE.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...n,...o}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={},i=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let m;if(this.context.isReferenceObjectWithIdentifier(o))m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let P=this.getDiscriminatorKeyForRef(o);m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:P,displayNameOverrideSource:"discriminator_key"})}else m=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});m.ok&&t.push({type:m.reference,docs:o.description});let A=this.context.getTypeIdFromSchemaReference(o);A!=null&&r.add(A);continue}let c=this.extendSubSchema(o),f=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),u=o.title,l=new M6i({context:this.context,id:f,nameOverride:u,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(l!=null){let m=l.convertedSchema.typeDeclaration.shape;m.type==="alias"&&this.typeReferenceIsWrappedPrimitive(m.aliasOf)?t.push({type:m.aliasOf,docs:o.description}):m.type==="object"&&m.properties.length===0?t.push({type:Mh.container(Xw.map({keyType:gO.STRING,valueType:Mh.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(f,u),docs:o.description}),n={...n,...l.inlinedTypes,[f]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}return{type:YE.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}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 n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new pPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:YE.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.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 Mh.container(Xw.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,n])=>n===t.$ref)?.[0]}};var kto=class extends gO{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return Mh.container(Xw.literal(Sfe.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Mh.primitive({v1:yw.Date,v2:l0.date({})});if(this.schema.format==="date-time")return Mh.primitive({v1:yw.DateTime,v2:l0.dateTime({})})}return Mh.primitive({v1:"STRING",v2:l0.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Mh.primitive({v1:"FLOAT",v2:l0.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Mh.primitive({v1:"LONG",v2:l0.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Mh.primitive({v1:"UINT",v2:l0.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Mh.primitive({v1:"DOUBLE",v2:l0.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Mh.primitive({v1:"FLOAT",v2:l0.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Mh.primitive({v1:"INTEGER",v2:l0.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Mh.primitive({v1:"LONG",v2:l0.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Mh.primitive({v1:"UINT",v2:l0.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Mh.primitive({v1:"UINT_64",v2:l0.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Mh.primitive({v1:"INTEGER",v2:l0.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?Mh.container(Xw.literal(Sfe.boolean(t))):Mh.primitive({v1:"BOOLEAN",v2:l0.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 ZiI=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],M6i=class e extends gO{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=a,this.nameOverride=o,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 n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let f=this.tryConvertMapSchema();if(f!=null)return f;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let s=this.tryConvertUntypedSchema();if(s!=null)return s;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 Sse.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new Yto({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.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 i=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(i?.convertedSchema.typeDeclaration?.shape.type!=="object")return i}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let i of this.schema.allOf??[]){if(this.context.isReferenceObject(i))return;r=TWa(r,i,(a,o)=>{if(o===i)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new kto({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new ero({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.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 Zto({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 hNu({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 Xto({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:YE.alias({aliasOf:Mh.unknown(),resolvedType:Mh.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new Sse.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=C5y(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){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:n?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=[...ZiI,...t];return Object.keys(this.schema).every(i=>r.includes(i))}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 n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let a=this.context.resolveExample(i),o=this.generateOrValidateExample({example:a});r[`${this.id}_example_${n}`]=o}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let n=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:i,errors:a}=n.convert();return r||a.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),i}};var pPe=class extends gO{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=a,this.wrapAsNullable=o}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),n=new M6i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),i=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=n.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:i}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:i}}}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 Mh.container(Xw.optional(t))}wrapInNullable(t){return Mh.container(Xw.nullable(t))}};var ero=class e extends gO{static LIST_UNKNOWN=Mh.container(Xw.list(Mh.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(a=>{n.add(a)})}),{typeReference:Mh.container(Xw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var vNu=class extends gO{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let f=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(f==null)return;t.schema=f}let o=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([f,u])=>{if(this.context.isReferenceObject(u)){let s=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return s.resolved?[f,s.value.value??s.value]:null}return[f,u.value??u]}).filter(f=>f!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new pPe({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,f]of o){let u=this.context.resolveExampleWithValue(f),s=this.context.isExampleWithSummary(f)?f.summary:c;u!=null&&(a!=null?i.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:a,example:u,exampleGenerationStrategy:n}):i.userSpecifiedExamples[s]=u)}if(Object.keys(i.userSpecifiedExamples).length===0&&a!=null){let c=$A(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n})}return i}generateOrValidateExample({schema:t,example:r,ignoreErrors:n,generateOptionalProperties:i,exampleGenerationStrategy:a}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let c=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),f=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??c[0],generateOptionalProperties:i??!1,exampleGenerationStrategy:a}),{validExample:u,errors:s}=f.convert();return n||s.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),u}};var bNu=class extends gO{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=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??gO.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:i},inlinedTypes:n};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??gO.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??gO.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t})},inlinedTypes:n};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:{}},n=this.parameter.example,i=this.parameter.examples;for(let[a,o]of Object.entries(i??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(n!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:n})}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:n}){let i=new eht({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:n}),{validExample:a,errors:o}=i.convert();return r||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var gNu=class extends UD{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var I5y="Base",$rt=class e extends gO{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}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(),n={id:r,name:this.context.casingsGenerator.generateName(r)},i=this.endpointLevelServers.map(c=>{let f=e.getServerName({server:c,context:this.context});return{id:f,name:this.context.casingsGenerator.generateName(f)}}).filter((c,f,u)=>u.findIndex(s=>s.id===c.id)===f),a=[n,...i],o=this.servers.map(c=>{let f=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:f,name:this.context.casingsGenerator.generateName(f),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description}});return{value:{defaultEnvironment:o[0]?.id,environments:mJ.multipleBaseUrls({baseUrls:a,environments:o})},defaultUrl:n.id}}let t=this.withExplodedServers(this.servers).map(r=>{let n=e.getServerName({server:r,context:this.context});return{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(pj);return{value:{defaultEnvironment:t[0]?.id,environments:mJ.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new gNu({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[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let n=Object.entries(r.variables).filter(([c,f])=>f.enum!=null&&f.enum.length>0);if(n.length===0)return[r];let i=n[0];if(i==null)return[r];let[a,o]=i;return o.enum==null?[r]:o.enum.map(c=>{let f=r.url.replace(`{${a}}`,encodeURIComponent(c)),u={};for(let[l,m]of Object.entries(r.variables??{}))l!==a&&(u[l]=m);let s={...r,url:f,variables:Object.keys(u).length>0?u:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([s])[0]})}).filter(pj)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?I5y:e.getServerExtensionName({server:this.servers[0],context:this.context})??I5y}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var gZo={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"},kiI=new Set(Object.values(gZo));var tro=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
2631
2631
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(oE.Trace,...t)}debug(...t){this.write(oE.Debug,...t)}info(...t){this.write(oE.Info,...t)}warn(...t){this.write(oE.Warn,...t)}error(...t){this.write(oE.Error,...t)}log(t,...r){this.write(t,...r)}};function uVr(e){if(e?.deprecated)return{status:Ine.Deprecated,message:"DEPRECATED"}}var nqr={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}},mNu={MESSAGE:4,ENUM:5,SERVICE:6};var ONu=class extends gO{enum;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,enum:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.enum=n,this.sourceCodeInfoPath=i}convert(){let t=this.enum.value.map((r,n)=>{let i=r.name;return{name:{name:this.context.casingsGenerator.generateName(i),wireValue:i},docs:this.context.getCommentForPath([...this.sourceCodeInfoPath,nqr.ENUM.VALUE,n]),availability:void 0}});return{type:YE.enum({default:void 0,values:t})}}};function M5y(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var B5y=new Set([_C.DOUBLE,_C.FLOAT,_C.INT64,_C.UINT64,_C.INT32,_C.FIXED64,_C.FIXED32,_C.BOOL,_C.STRING,_C.BYTES,_C.UINT32,_C.SFIXED32,_C.SFIXED64,_C.SINT32,_C.SINT64]);var ANu=class e extends gO{static LIST_UNKNOWN=Mh.container(Xw.list(Mh.unknown()));field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.field=n,this.sourceCodeInfoPath=i}convert(){if(this.field.label===3){let r=new B6i({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:fWa.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let n=new Set;return{typeReference:Mh.container(Xw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var PNu=class extends gO{field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.field=n,this.sourceCodeInfoPath=i}convert(){switch(this.field.type){case _C.STRING:return Mh.primitive({v1:yw.String,v2:l0.string({default:void 0,validation:void 0})});case _C.DOUBLE:return Mh.primitive({v1:yw.Double,v2:l0.double({default:void 0,validation:void 0})});case _C.FLOAT:return Mh.primitive({v1:yw.Float,v2:l0.float({})});case _C.INT32:return Mh.primitive({v1:yw.Integer,v2:l0.integer({default:void 0,validation:void 0})});case _C.INT64:return Mh.primitive({v1:yw.Long,v2:l0.long({default:void 0})});case _C.UINT32:return Mh.primitive({v1:yw.Uint,v2:l0.uint({default:void 0})});case _C.UINT64:return Mh.primitive({v1:yw.Uint64,v2:l0.uint64({default:void 0})});case _C.BOOL:return Mh.primitive({v1:yw.Boolean,v2:l0.boolean({default:void 0})});default:return Mh.unknown()}}};var B6i=class extends gO{field;wrapAsOptional;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:n,wrapAsOptional:i,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.field=n,this.wrapAsOptional=i??!0,this.sourceCodeInfoPath=a}convert(){if(this.field.label===3){let n=new ANu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(n!=null)return{type:this.wrapAsOptional?this.wrapInOptional(n.typeReference):n.typeReference,inlinedTypes:n.inlinedTypes,availability:uVr(this.field.options)}}if(B5y.has(this.field.type)){let n=new PNu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(n!=null)return{type:this.wrapAsOptional?this.wrapInOptional(n):n,inlinedTypes:{},availability:uVr(this.field.options)}}if((this.field.type===_C.MESSAGE||this.field.type===_C.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:{},availability:uVr(this.field.options)}}}wrapInOptional(t){return Mh.container(Xw.optional(t))}};function T5y({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:n}){let i=[],a={},o=new Set,c={};for(let[f,u]of e.entries()){let l=new B6i({context:r,breadcrumbs:[...t,"fields",u.name],field:u,sourceCodeInfoPath:[...n,nqr.MESSAGE.FIELD,f]}).convert();if(l!=null){let m={name:r.casingsGenerator.generateNameAndWireValue({name:u.name,wireValue:u.name}),valueType:l.type,docs:r.getCommentForPath([...n,nqr.MESSAGE.FIELD,f]),availability:l.availability,propertyAccess:void 0,v2Examples:void 0};if(Object.hasOwn(u,"oneofIndex")&&u.oneofIndex!=null){c[u.oneofIndex]==null&&(c[u.oneofIndex]=[]),c[u.oneofIndex].push(u);continue}i.push(m)}}return{convertedFields:i,referencedTypes:o,propertiesByAudience:a,oneOfFields:c}}var wNu=class extends gO{oneOfFields;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,oneOfFields:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.oneOfFields=n,this.sourceCodeInfoPath=i}convert(){let t=[];for(let r of this.oneOfFields){let i=new B6i({context:this.context,breadcrumbs:this.breadcrumbs,field:r,wrapAsOptional:!1,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();i!=null&&t.push({type:i.type,docs:void 0})}return{type:YE.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{},availability:uVr(this.getProtoAvailabilityOptions())}}getProtoAvailabilityOptions(){return{deprecated:this.oneOfFields.every(t=>t.options?.deprecated)}}};var jNu=class extends gO{message;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,message:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.message=n,this.sourceCodeInfoPath=i}convert(){let t={},r=new Set,{convertedFields:n,referencedTypes:i,propertiesByAudience:a,oneOfFields:o}=T5y({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let c of i)r.add(c);for(let[c,f]of this.message.nestedType.entries()){let s=new T6i({context:this.context,breadcrumbs:this.breadcrumbs,schema:f,sourceCodeInfoPath:[...this.sourceCodeInfoPath,nqr.MESSAGE.NESTED_TYPE,c],schemaIndex:c}).convert();if(s!=null){for(let l of s.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(s.inlinedTypes).map(([l,m])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(m,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(f.name)]:this.context.updateTypeId(s.convertedSchema,this.prependDelimitedParentMessageName(f.name))}}}for(let[c,f]of this.message.enumType.entries()){let s=new T6i({context:this.context,breadcrumbs:this.breadcrumbs,schema:f,sourceCodeInfoPath:[...this.sourceCodeInfoPath,nqr.MESSAGE.ENUM_TYPE,c],schemaIndex:c}).convert();if(s!=null){for(let l of s.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(s.inlinedTypes).map(([l,m])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(m,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(f.name)]:this.context.updateTypeId(s.convertedSchema,this.prependDelimitedParentMessageName(f.name))}}}for(let[c,f]of this.message.oneofDecl.entries()){let s=new wNu({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:o[c]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,nqr.MESSAGE.ONEOF_DECL,c]}).convert();if(s!=null){for(let A of s.referencedTypes)r.add(A);let l={typeDeclaration:this.createTypeDeclaration({shape:s.type,referencedTypes:s.referencedTypes,typeName:this.prependParentMessageName(M5y(f.name))}),audiences:[],propertiesByAudience:{}},m=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(l.typeDeclaration.name.typeId)});m.ok===!0&&(n.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:f.name,wireValue:f.name}),valueType:m.reference,docs:void 0,availability:s.availability,propertyAccess:void 0,v2Examples:void 0}),t={...t,[l.typeDeclaration.name.typeId]:l})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:YE.object({properties:n,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),availability:uVr(this.message.options)}),audiences:[],propertiesByAudience:a},inlinedTypes:t}}createTypeDeclaration({shape:t,referencedTypes:r,typeName:n,docs:i,availability:a}){return{name:this.convertDeclaredTypeName(n),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:a,docs:i,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 T6i=class extends gO{schema;audiences;sourceCodeInfoPath;schemaIndex;constructor({context:t,breadcrumbs:r,schema:n,sourceCodeInfoPath:i,schemaIndex:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.sourceCodeInfoPath=i,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 ONu({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),availability:uVr(this.schema.options)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new jNu({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:n,availability:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:i,docs:n,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 rro=class extends hee{comments;codeGeneratorRequest;constructor({comments:t,codeGeneratorRequest:r,...n}){super(n),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(n=>n.name!==this.spec.name))if(t.startsWith(r.package)){for(let n of r.messageType)if(`${r.package}.${n.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:n,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:Mh.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(i=>i!==""),n=this.spec.package.split(".").filter(i=>i!=="");for(;r.length>0&&n.length>0;){if(r[0]!==n[0])return t;r.shift(),n.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 n=this.comments[r];for(let i=1;i<t.length;i++){let a=t[i];if(a===void 0||!n)return;n=n[a]}return n?._comment}};function JTf(){return{4:{},5:{},6:{}}}function q5y(e){let t=JTf();return e.package?.startsWith("google.protobuf")||e.sourceCodeInfo?.location.forEach(r=>{let n=r.path;if(!n||n.length===0)return;let i=n[0];if(!(i in t))return;let a=r.leadingComments||r.trailingComments||"";if(!a)return;let o=t[i];for(let c=1;c<n.length;c++){let f=n[c];f!=null&&(f in o||(o[f]={}),o=o[f])}o._comment=a.trim()}),t}var mZo=class e extends gO{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:n,type:i,depth:a=0,seenMessages:o=new Set}){super({context:r,breadcrumbs:t}),this.message=n,this.type=i,this.depth=a,this.seenMessages=o}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(n){return{isValid:!1,coerced:!1,validExample:{},errors:[`Failed to convert message ${t}: ${n}`]}}}getFullyQualifiedMessageName(t){let r=this.context.spec.package||"",n=t.name||"";return r?`${r}.${n}`:n}convertMessage(t){let r=new Map,n=new Map,i=new Map;this.message.oneofDecl&&this.message.oneofDecl.forEach((s,l)=>{s.name&&i.set(l,s.name)});for(let s of this.message.field)Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null&&(n.has(s.oneofIndex)||n.set(s.oneofIndex,s));for(let s of this.message.field){let l=s.name??"";if(!(!l||Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null&&n.get(s.oneofIndex)!==s))try{let A=this.convertField({field:s,seenMessages:t,fieldName:l});r.set(l,{field:s,result:A})}catch(A){r.set(l,{field:s,result:{isValid:!1,coerced:!1,validExample:null,errors:[`Error converting field ${l}: ${A}`]}})}}let a=Array.from(r.values()),o=a.every(({result:s})=>s.isValid),c=a.flatMap(({result:s})=>s.errors),f={},u=new Map;for(let[s,{field:l,result:m}]of r.entries()){if(!m.isValid||m.validExample===null||m.validExample===void 0)continue;if(Object.hasOwn(l,"oneofIndex")&&l.oneofIndex!=null&&i.has(l.oneofIndex)){let P=i.get(l.oneofIndex)??void 0;P!=null&&u.set(P,{fieldName:s,value:m.validExample})}else f[s]=m.validExample}for(let[s,{fieldName:l,value:m}]of u.entries())f[s]={[l]:m};return{isValid:o,coerced:!1,validExample:f,errors:c}}convertField({field:t,seenMessages:r,fieldName:n}){return t.label===fWa.REPEATED?this.convertRepeatedField({field:t,seenMessages:r,fieldName:n}):this.convertSingleField({field:t,seenMessages:r,fieldName:n})}convertRepeatedField({field:t,seenMessages:r,fieldName:n}){let i=this.convertSingleField({field:t,seenMessages:r,fieldName:n});return{isValid:i.isValid,coerced:!1,validExample:i.isValid?[i.validExample]:[],errors:i.errors}}convertSingleField({field:t,seenMessages:r,fieldName:n}){switch(t.type){case _C.DOUBLE:case _C.FLOAT:case _C.INT64:case _C.UINT64:case _C.INT32:case _C.FIXED64:case _C.FIXED32:case _C.UINT32:case _C.SFIXED32:case _C.SFIXED64:case _C.SINT32:case _C.SINT64:return this.convertNumber();case _C.BOOL:return this.convertBoolean();case _C.STRING:return this.convertString(this.EXAMPLE_STRING);case _C.BYTES:return this.convertBytes();case _C.ENUM:return this.convertEnum(t);case _C.MESSAGE:return this.convertMessage_Field(t,r,n);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??"",n=this.context.maybeRemoveLeadingPeriod(r),i=this.findEnumType(n);return i?i.value.length===0?{isValid:!0,coerced:!1,validExample:0,errors:[]}:{isValid:!0,coerced:!1,validExample:i.value[0]?.number??0,errors:[]}:{isValid:!1,coerced:!1,validExample:0,errors:[`Enum type ${t.typeName} not found`]}}convertMessage_Field(t,r,n){let i=t.typeName;if(!i)return{isValid:!1,coerced:!1,validExample:null,errors:[`Missing type name for message field ${n}`]};let a=this.context.maybeRemoveLeadingPeriod(i),o,c;if(this.context.getCodeGeneratorRequest())for(let u of this.context.getCodeGeneratorRequest().protoFile){let s=this.context.resolveTypeIdToProtoFile(a);if(s.ok){o=s.message,s.protoFileName!==this.context.spec.name?c=new rro({...this.context,comments:JTf(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:u,logger:new tro}):c=this.context;break}}return!o||!c?{isValid:!0,coerced:!1,validExample:null,errors:[`Could not find message type ${a}`]}:new e({context:c,breadcrumbs:[...this.breadcrumbs,n],message:o,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 n of this.context.getCodeGeneratorRequest().protoFile)if(r=this.findEnumInFile(t,n),r!=null)break}return r}findEnumInFile(t,r){let n=r.package||"";for(let i of r.enumType)if((n?`${n}.${i.name}`:i.name||"")===t||i.name===t)return i;for(let i of r.messageType){let a=this.findEnumInMessage(t,i,n);if(a!=null)return a}}findEnumInMessage(t,r,n){let i=n?`${n}.${r.name}`:r.name||"";for(let a of r.enumType)if(`${i}.${a.name}`===t||a.name===t)return a;for(let a of r.nestedType){let o=this.findEnumInMessage(t,a,i);if(o!=null)return o}}};var ENu=class extends gO{operation;serviceName;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,operation:n,serviceName:i,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.operation=n,this.serviceName=i,this.sourceCodeInfoPath=a}convert(){let t=this.context.spec.package,r=this.convertRequestBody(),n=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:n?.responseBody,v2Responses:void 0,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:nU.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,security:void 0,availability:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:!1,basePath:void 0,fullPath:{head:this.operation.name,parts:[]},allPathParameters:[],pagination:void 0,transport:void 0,source:TAe.proto({methodType:this.getGrpcMethodType()}),audiences:[],retries:void 0}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?lTr.BidirectionalStream:this.operation.clientStreaming?lTr.ClientStream:this.operation.serverStreaming?lTr.ServerStream:lTr.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:R7.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:fN.json(wfe.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var SNu=class extends gO{service;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,service:n,sourceCodeInfoPath:i}){super({context:t,breadcrumbs:r}),this.service=n,this.sourceCodeInfoPath=i}convert(){let t=[];for(let[r,n]of this.service.method.entries()){let a=new ENu({context:this.context,breadcrumbs:this.breadcrumbs,operation:n,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,nqr.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 R5y(){return{displayName:void 0,request:{endpoint:{method:_Lr.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:np.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var DNu=class extends rqr{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}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 i=new T6i({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[mNu.ENUM,t],schemaIndex:t}).convert();i!=null&&this.addTypesToIr({...N5y(i.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:i.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let i=new T6i({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[mNu.MESSAGE,t],schemaIndex:t}).convert();i!=null&&this.addTypesToIr({...N5y(i.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:i.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let i=new SNu({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[mNu.SERVICE,t]}).convert();if(i!=null)for(let a of i.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:i.serviceName,endpointGroupDisplayName:i.serviceDisplayName})}}generateExamplesForServices(){for(let[t,r]of Object.entries(this.ir.services))for(let[n,i]of Object.entries(r.endpoints)){let a=R5y(),o=this.constructRequestBodyExample(i),c=this.constructResponseBodyExample(i);o!=null&&a.request!=null&&(a.request.requestBody=o),c!=null&&a.response!=null&&(a.response.body=Mne.json(c)),i.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{[n]:a}}}}constructRequestBodyExample(t){let r=t.requestBody.requestBodyType.typeId,n=this.context.resolveTypeIdToProtoFile(r);if(n.ok)return new mZo({context:this.context,breadcrumbs:this.breadcrumbs,message:n.message,type:"request"}).convert().validExample}constructResponseBodyExample(t){let r=(t.response?.body).value.responseBodyType.typeId,n=this.context.resolveTypeIdToProtoFile(r);if(n.ok)return new mZo({context:this.context,breadcrumbs:this.breadcrumbs,message:n.message,type:"response"}).convert().validExample}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:a}){let o=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:n}),f=[...o].map(l=>this.context.casingsGenerator.generateName(l)),u=f[f.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>$A(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:f,finalpart:u,endpointGroupDisplayName:i})),this.ir.services[c.service]?.endpoints.push(t);let s=this.ir.services[c.service];s!=null&&(this.irGraph.addEndpoint(s,t),this.irGraph.markEndpointForAudience(s.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 n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let a=r[i]??"",c=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:a,...this.createPackage({name:a})});let f=this.ir.subpackages[c];n.subpackages.includes(c)||n.subpackages.push(c),n=f}return n}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 N5y(e,t){return Object.fromEntries(Object.entries(e).map(([r,n])=>[t(r),n]))}function F5y({req:e,options:t}){let r,n=_Ce({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let c=new DNu({context:new rro({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new I6i({logger:{log:(f,...u)=>{}},relativeFilepathToSpec:void 0}),logger:new tro,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:q5y(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();c!=null&&(r=r===void 0?c:hla(r,c,n))}let i=V0.IntermediateRepresentation.json(r,{allowUnrecognizedEnumValues:!0,skipValidation:!0});return i.ok?{name:"ir.json",content:JSON.stringify(i.value,null,2)}:{name:"ir.json",content:JSON.stringify(i.errors,null,2)}}function x5y(e){return{}}var KTf=eaI({name:"protoc-gen-fern",version:`v${String(l5y)}`,run:F5y});function eaI({name:e,version:t,run:r}){return{name:e,version:t,run(n){let i=x5y(n.parameter),a=r({req:n,options:i});return taI([a],Yk_,Xk_)}}}function taI(e,t,r){return H5o(Kks,{supportedFeatures:W5.parse(Z5o.PROTO3_OPTIONAL|Z5o.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var L5y=$i(require("net"),1),U5y=$i(require("os"),1),CNu=class extends Error{constructor(t){super(`${t} is locked`)}},nro={old:new Set,young:new Set},raI=1e3*15;var OZo,naI=()=>{let e=U5y.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},z5y=e=>new Promise((t,r)=>{let n=L5y.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),Q5y=async(e,t)=>{if(e.host||e.port===0)return z5y(e);for(let r of t)try{await z5y({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},iaI=function*(e){e&&(yield*e),yield 0};async function iro(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of i){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(i)}OZo===void 0&&(OZo=setTimeout(()=>{OZo=void 0,nro.old=nro.young,nro.young=new Set},raI),OZo.unref&&OZo.unref());let n=naI();for(let i of iaI(t))try{if(r.has(i))continue;let a=await Q5y({...e,port:i},n);for(;nro.old.has(a)||nro.young.has(a);){if(i!==0)throw new CNu(i);a=await Q5y({...e,port:i},n)}return nro.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof CNu))throw a}throw new Error("No available ports found")}wLy();var T9y=$i(B9y(),1),{applyExtends:hoI,cjsPlatformShim:yoI,Parser:voI,processArgv:boI,Yargs:kNu}=T9y.default;kNu.applyExtends=(e,t,r)=>hoI(e,t,r,yoI);kNu.hideBin=boI.hideBin;kNu.Parser=voI;var q9y=kNu;var R9y=require("fs/promises");var N9y=require("path"),F9y=$i(CDe(),1);async function x9y({url:e,logger:t}){try{let r=await goI({url:e,logger:t}),n=await F9y.default.dir(),i=(0,N9y.join)(n.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",n.path),t.debug("filePath",i),await(0,R9y.writeFile)(i,r),{status:"success",filePath:i}}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 goI({url:e,logger:t}){let r=await VX.get(e),n=r.headers["content-type"]??"";return n.includes("json")||e.endsWith(".json")?typeof r.data=="string"?r.data:JSON.stringify(r.data,null,2):n.includes("yaml")||e.endsWith(".yml")||e.endsWith(".yaml")?typeof r.data=="string"?r.data:iGa(r.data):(t.warn(`Unrecognized Content-Type "${n}" from endpoint ${e}. Please ensure you're pointing to a URL that returns JSON or YAML and not HTML (e.g. Swagger UI webpage)`),iGa(r.data))}var TZo=$i($Mr(),1);function Wqf(e,t){if(e=TZo.default.parse(e),t=TZo.default.parse(t),!(TZo.default.compareBuild(e,t)>=0))return TZo.default.diff(e,t)||"build"}var moI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,OoI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,AoI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,PoI=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,woI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,joI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function Cla(e){let t=e.match(woI);if(t!=null){let[c,f,u,s,l]=t,m=qJ(f),A=qJ(u),P=qJ(s),C=qJ(l);if(m==null||A==null||P==null||C==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:m,minor:A,patch:P,index:C}}let r=e.match(joI);if(r!=null){let[c,f,u,s,l]=r,m=qJ(f),A=qJ(u),P=qJ(s),C=qJ(l);if(m==null||A==null||P==null||C==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:m,minor:A,patch:P,index:C}}let n=e.match(moI);if(n!=null){let[c,f,u,s,l]=n,m=qJ(f),A=qJ(u),P=qJ(s),C=qJ(l);if(m==null||A==null||P==null||C==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:m,minor:A,patch:P,commitIndex:C}}let i=e.match(AoI);if(i!=null){let[c,f,u,s,l]=i,m=qJ(f),A=qJ(u),P=qJ(s),C=qJ(l);if(m==null||A==null||P==null||C==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:m,minor:A,patch:P,releaseCandidateIndex:C}}let a=e.match(OoI);if(a!=null){let[c,f,u,s,l,m]=a,A=qJ(f),P=qJ(u),C=qJ(s),I=qJ(l),T=qJ(m);if(A==null||P==null||C==null||I==null||T==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:A,minor:P,patch:C,releaseCandidateIndex:I,commitIndex:T}}let o=e.match(PoI);if(o!=null){let[c,f,u,s]=o,l=qJ(f),m=qJ(u),A=qJ(s);if(l==null||m==null||A==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:l,minor:m,patch:A}}throw new Error("Failed to parse version: "+e)}function qJ(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function gxe(e,t){if(e===t)return!1;let r=Cla(e),n=Cla(t);if(r.major!==n.major||r.minor!==n.minor||r.patch!==n.patch)return Wqf(z9y(r),z9y(n))==null;if(r.type==="post-release-commit")return n.type!=="post-release-commit"||r.commitIndex>n.commitIndex;if(r.type==="release")return n.type!=="post-release-commit";if(r.type==="rc"){switch(n.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}return r.releaseCandidateIndex!==n.releaseCandidateIndex&&r.releaseCandidateIndex>n.releaseCandidateIndex}if(r.type==="post-rc-commit"){switch(n.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}if(n.type==="post-rc-commit")return r.releaseCandidateIndex!==n.releaseCandidateIndex?r.releaseCandidateIndex>n.releaseCandidateIndex:r.commitIndex>n.commitIndex}if(r.type==="beta"){switch(n.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1;case"alpha":return!0}return r.index>n.index}if(r.type==="alpha"){switch(n.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1}return r.index>n.index}return!gxe(t,e)}function z9y(e){return`${e.major}.${e.minor}.${e.patch}`}var _Pe=e=>e.name==="up",tnt=e=>e.name==="down",Q9y=e=>e.name==="space",pro=e=>e.name==="backspace",F6i=e=>e.name==="tab",eFu=e=>"1234567890".includes(e.name),Yne=e=>e.name==="enter"||e.name==="return";var tFu=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},rFu=class extends Error{name="CancelPromptError";message="Prompt was canceled"},qZo=class extends Error{name="ExitPromptError"},nFu=class extends Error{name="HookError"},fVr=class extends Error{name="ValidationError"};var W9y=require("async_hooks");var iFu=require("async_hooks");var L9y=new iFu.AsyncLocalStorage;function EoI(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function U9y(e,t){let r=EoI(e);return L9y.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return t(n)})}function Ila(){let e=L9y.getStore();if(!e)throw new nFu("[Inquirer] Hook functions can only be called from within a prompt");return e}function Hqf(){return Ila().rl}function Gqf(e){let t=(...r)=>{let n=Ila(),i=!1,a=n.handleChange;n.handleChange=()=>{i=!0};let o=e(...r);return i&&a(),n.handleChange=a,o};return iFu.AsyncResource.bind(t)}function _ro(e){let t=Ila(),{index:r}=t,n={get(){return t.hooks[r]},set(a){t.hooks[r]=a},initialized:r in t.hooks},i=e(n);return t.index++,i}function V9y(){Ila().handleChange()}var Mla={queue(e){let t=Ila(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(Hqf());if(n!=null&&typeof n!="function")throw new fVr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=Ila();Gqf(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Ila();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function aD(e){return _ro(t=>{let r=W9y.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),V9y())});if(t.initialized)return[t.get(),r];let n=typeof e=="function"?e():e;return t.set(n),[n,r]})}function rnt(e,t){_ro(r=>{let n=r.get();(!Array.isArray(n)||t.some((a,o)=>!Object.is(a,n[o])))&&Mla.queue(e),r.set(t)})}var oht=$i(hse(),1);var H9y={prefix:{idle:oht.default.blue("?"),done:oht.default.green(Nne.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>oht.default.yellow(e))},style:{answer:oht.default.cyan,message:oht.default.bold,error:e=>oht.default.red(`> ${e}`),defaultAnswer:e=>oht.default.dim(`(${e})`),help:oht.default.dim,highlight:oht.default.cyan,key:e=>oht.default.cyan(oht.default.bold(`<${e}>`))}};function G9y(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 J9y(...e){let t={};for(let r of e)for(let[n,i]of Object.entries(r)){let a=t[n];t[n]=G9y(a)&&G9y(i)?J9y(a,i):i}return t}function g$(...e){let t=[H9y,...e.filter(r=>r!=null)];return J9y(...t)}function bee({status:e="idle",theme:t}){let[r,n]=aD(!1),[i,a]=aD(0),{prefix:o,spinner:c}=g$(t);return rnt(()=>{if(e==="loading"){let u,s=-1,l=setTimeout(()=>{n(!0),u=setInterval(()=>{s=s+1,a(s%c.frames.length)},c.interval)},300);return()=>{clearTimeout(l),clearInterval(u)}}else n(!1)},[e]),r?c.frames[i]:typeof o=="string"?o:o[e==="loading"?"idle":e]??o.idle}function mxe(e,t){return _ro(r=>{let n=r.get();if(!n||n.dependencies.length!==t.length||n.dependencies.some((i,a)=>i!==t[a])){let i=e();return r.set({value:i,dependencies:t}),i}return n.value})}function sht(e){return aD({current:e})[0]}function gee(e){let t=sht(e);t.current=e,rnt(r=>{let n=!1,i=Gqf((a,o)=>{n||t.current(o,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var K9y=$i(Abf(),1),$9y=$i(Ibf(),1);function RZo(e,t){return e.split(`
2632
2632
  `).flatMap(r=>(0,$9y.default)(r,t,{trim:!1,hard:!0}).split(`
2633
2633
  `).map(n=>n.trimEnd())).join(`
@@ -2669,12 +2669,12 @@ ${q}${z}${V}${hro}`});function fFu({message:e,error:t,logger:r,logLevel:n=oE.Err
2669
2669
  Run ${Mf.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
2670
2670
  Run ${Mf.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),IZa(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function ORf({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!qUy(e))return;let i=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,f)=>c.generatorName.localeCompare(f.generatorName)||c.currentVersion.localeCompare(f.currentVersion));for(let c of o)i+=`
2671
2671
  ${await vsI(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Mf.dim(c.currentVersion)+Mf.reset(" \u2192 ")+Mf.green(c.latestVersion);return i+=`
2672
- `,n?IZa(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function vsI(e){let r=await new TUy.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 bsI({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,u,s,l)=>{c.versions[u]==null&&(c.versions[u]={});let m=e3i(s.name,l),A=await sTr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[u][s.name]={previousVersion:s.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,u,s)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=e3i(u.name,s),m=await sTr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:s});m!=null&&(o.versions[c][f][u.name]={previousVersion:u.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await vTr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(i!=null&&f.groupName!==i))for(let u of f.generators)n!=null&&u.name!==n||await r(a.workspaceName,f.groupName,u,o)}})}))}function FUy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let f=gxe(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function hFu({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await bsI({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[f,u]of Object.entries(c.versions))o.push(...FUy(u,f,t.logger));else o.push(...FUy(c.versions,void 0,t.logger))}return o}var VZo=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var gro=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var ARf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),xUy=typeof globalThis.AbortController=="function",zUy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",QUy=typeof globalThis.ReadableStream=="function",LUy=typeof globalThis.FormData=="function",yFu=["get","post","put","patch","head","delete"],gsI=()=>{};gsI();var UUy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},vFu=2147483647,VUy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,bFu=Symbol("stop"),WUy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},HUy={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 msI=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=VUy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.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},GUy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},JUy=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(GUy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},KUy=(e,t,r)=>{if(!e.body)return e;let n=msI(r??e.body);return new Request(e,{duplex:"half",body:GUy(e.body,n,t)})};var mro=e=>e!==null&&typeof e=="object";var WZo=(...e)=>{for(let t of e)if((!mro(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return jRf({},...e)},PRf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function gFu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:jRf(e[r]??[],t[r]??[])}var wRf=(e={},t={})=>({beforeRequest:gFu(e,t,"beforeRequest"),beforeRetry:gFu(e,t,"beforeRetry"),afterResponse:gFu(e,t,"afterResponse"),beforeError:gFu(e,t,"beforeError")}),jRf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(mro(i)){for(let[a,o]of Object.entries(i))mro(o)&&a in t&&(o=jRf(t[a],o)),t={...t,[a]:o};mro(i.hooks)&&(n=wRf(n,i.hooks),t.hooks=n),mro(i.headers)&&(r=PRf(r,i.headers),t.headers=r)}return t};var YUy=e=>yFu.includes(e)?e.toUpperCase():e,OsI=["get","put","head","delete","options","trace"],AsI=[408,413,429,500,502,503,504],PsI=[413,429,503],$Uy={limit:2,methods:OsI,statusCodes:AsI,afterStatusCodes:PsI,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},XUy=(e={})=>{if(typeof e=="number")return{...$Uy,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{...$Uy,...e}};async function ERf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new gro(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function SRf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var ZUy=(e,t)=>{let r={};for(let n in t)!(n in HUy)&&!(n in WUy)&&!(n in e)&&(r[n]=t[n]);return r},kUy=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 HZo=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>vFu)throw new RangeError(`The \`timeout\` option cannot be greater than ${vFu}`);await Promise.resolve();let c=await n._fetch();for(let f of n._options.hooks.afterResponse){let u=await f(n.request,n._options,n._decorateResponse(c.clone()));u instanceof globalThis.Response&&(c=u)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let f=new VZo(c,n.request,n._options);for(let u of n._options.hooks.beforeError)f=await u(f);throw f}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!QUy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return JUy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),n.request.bodyUsed||f.push(n.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(UUy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||f);let u=await o;if(c==="json"){if(u.status===204)return"";let s=await u.text();return s===""?"":r.parseJson?r.parseJson(s):JSON.parse(s)}return u[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:PRf(this._input.headers,r.headers),hooks:wRf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:YUy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:XUy(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(xUy&&zUy){let n=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=n?AbortSignal.any([n,this.abortController.signal]):this.abortController.signal}if(ARf&&(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),kUy(this._options.searchParams)){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(LUy&&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(!ARf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=KUy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof gro)throw t;if(t instanceof VZo){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),vFu);if(this._retryCount<1)throw r;await SRf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===bFu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=ZUy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):ERf(this._originalRequest,t,this.abortController,this._options)}};var DRf=e=>{let t=(r,n)=>HZo.create(r,WZo(e,n));for(let r of yFu)t[r]=(n,i)=>HZo.create(n,WZo(e,i,{method:r}));return t.create=r=>DRf(WZo(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),DRf(WZo(e,r))),t.stop=bFu,t},wsI=DRf(),eVy=wsI;var PVy=$i(AVy(),1);function TRf(e){let t=(0,PVy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var vWy=$i(yWy(),1),bWy=$i($Mr(),1),GRf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},JRf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function KRf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??TRf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,vWy.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let u;try{u=await eVy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new GRf(e):l}if(t.allVersions)return u;let s=new JRf(e,r);if(u["dist-tags"][r]){let{time:l}=u;u=u.versions[u["dist-tags"][r]],u.time=l}else if(r){let l=!!u.versions[r];if(n&&!l)for(let[A,P]of Object.entries(u.versions))P.deprecated&&delete u.versions[A];if(!l){let A=Object.keys(u.versions);if(r=bWy.default.maxSatisfying(A,r),!r)throw s}let{time:m}=u;if(u=u.versions[r],u.time=m,!u)throw s}return u}async function XZo(e,t){let{version:r}=await KRf(e.toLowerCase(),t);return r}async function Q6i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:XZo(e.packageName,{version:t?"prerelease":"latest"})}var gWy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],MFu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new _Fu(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.107.7"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Mf.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new gne}failWithoutThrowing(t,r){this.didSucceed=!1,fFu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mZa()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await RUy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2672
+ `,n?IZa(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function vsI(e){let r=await new TUy.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 bsI({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,u,s,l)=>{c.versions[u]==null&&(c.versions[u]={});let m=e3i(s.name,l),A=await sTr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[u][s.name]={previousVersion:s.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,u,s)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=e3i(u.name,s),m=await sTr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:s});m!=null&&(o.versions[c][f][u.name]={previousVersion:u.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function NUy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await vTr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(i!=null&&f.groupName!==i))for(let u of f.generators)n!=null&&u.name!==n||await r(a.workspaceName,f.groupName,u,o)}})}))}function FUy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let f=gxe(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function hFu({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await bsI({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[f,u]of Object.entries(c.versions))o.push(...FUy(u,f,t.logger));else o.push(...FUy(c.versions,void 0,t.logger))}return o}var VZo=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var gro=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var ARf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),xUy=typeof globalThis.AbortController=="function",zUy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",QUy=typeof globalThis.ReadableStream=="function",LUy=typeof globalThis.FormData=="function",yFu=["get","post","put","patch","head","delete"],gsI=()=>{};gsI();var UUy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},vFu=2147483647,VUy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,bFu=Symbol("stop"),WUy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},HUy={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 msI=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=VUy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.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},GUy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},JUy=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(GUy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},KUy=(e,t,r)=>{if(!e.body)return e;let n=msI(r??e.body);return new Request(e,{duplex:"half",body:GUy(e.body,n,t)})};var mro=e=>e!==null&&typeof e=="object";var WZo=(...e)=>{for(let t of e)if((!mro(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return jRf({},...e)},PRf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function gFu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:jRf(e[r]??[],t[r]??[])}var wRf=(e={},t={})=>({beforeRequest:gFu(e,t,"beforeRequest"),beforeRetry:gFu(e,t,"beforeRetry"),afterResponse:gFu(e,t,"afterResponse"),beforeError:gFu(e,t,"beforeError")}),jRf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(mro(i)){for(let[a,o]of Object.entries(i))mro(o)&&a in t&&(o=jRf(t[a],o)),t={...t,[a]:o};mro(i.hooks)&&(n=wRf(n,i.hooks),t.hooks=n),mro(i.headers)&&(r=PRf(r,i.headers),t.headers=r)}return t};var YUy=e=>yFu.includes(e)?e.toUpperCase():e,OsI=["get","put","head","delete","options","trace"],AsI=[408,413,429,500,502,503,504],PsI=[413,429,503],$Uy={limit:2,methods:OsI,statusCodes:AsI,afterStatusCodes:PsI,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},XUy=(e={})=>{if(typeof e=="number")return{...$Uy,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{...$Uy,...e}};async function ERf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new gro(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function SRf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var ZUy=(e,t)=>{let r={};for(let n in t)!(n in HUy)&&!(n in WUy)&&!(n in e)&&(r[n]=t[n]);return r},kUy=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 HZo=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>vFu)throw new RangeError(`The \`timeout\` option cannot be greater than ${vFu}`);await Promise.resolve();let c=await n._fetch();for(let f of n._options.hooks.afterResponse){let u=await f(n.request,n._options,n._decorateResponse(c.clone()));u instanceof globalThis.Response&&(c=u)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let f=new VZo(c,n.request,n._options);for(let u of n._options.hooks.beforeError)f=await u(f);throw f}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!QUy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return JUy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),n.request.bodyUsed||f.push(n.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(UUy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||f);let u=await o;if(c==="json"){if(u.status===204)return"";let s=await u.text();return s===""?"":r.parseJson?r.parseJson(s):JSON.parse(s)}return u[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:PRf(this._input.headers,r.headers),hooks:wRf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:YUy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:XUy(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(xUy&&zUy){let n=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=n?AbortSignal.any([n,this.abortController.signal]):this.abortController.signal}if(ARf&&(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),kUy(this._options.searchParams)){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(LUy&&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(!ARf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=KUy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof gro)throw t;if(t instanceof VZo){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),vFu);if(this._retryCount<1)throw r;await SRf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===bFu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=ZUy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):ERf(this._originalRequest,t,this.abortController,this._options)}};var DRf=e=>{let t=(r,n)=>HZo.create(r,WZo(e,n));for(let r of yFu)t[r]=(n,i)=>HZo.create(n,WZo(e,i,{method:r}));return t.create=r=>DRf(WZo(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),DRf(WZo(e,r))),t.stop=bFu,t},wsI=DRf(),eVy=wsI;var PVy=$i(AVy(),1);function TRf(e){let t=(0,PVy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var vWy=$i(yWy(),1),bWy=$i($Mr(),1),GRf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},JRf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function KRf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??TRf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,vWy.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let u;try{u=await eVy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new GRf(e):l}if(t.allVersions)return u;let s=new JRf(e,r);if(u["dist-tags"][r]){let{time:l}=u;u=u.versions[u["dist-tags"][r]],u.time=l}else if(r){let l=!!u.versions[r];if(n&&!l)for(let[A,P]of Object.entries(u.versions))P.deprecated&&delete u.versions[A];if(!l){let A=Object.keys(u.versions);if(r=bWy.default.maxSatisfying(A,r),!r)throw s}let{time:m}=u;if(u=u.versions[r],u.time=m,!u)throw s}return u}async function XZo(e,t){let{version:r}=await KRf(e.toLowerCase(),t);return r}async function Q6i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:XZo(e.packageName,{version:t?"prerelease":"latest"})}var gWy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],MFu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new _Fu(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.107.8"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Mf.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new gne}failWithoutThrowing(t,r){this.didSucceed=!1,fFu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mZa()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await RUy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2673
2673
  `)||(r+=`
2674
2674
  `),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=cJl(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new FZo(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw a.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,a),new gne}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await mZa()).sendEvent(t)}logger=q2r((t,...r)=>this.log(t,...r));stderr=q2r((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=mWy(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?mWy(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=gWy[this.numTasks++%gWy.length],o=Mf.hex(a)(i);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===dV.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 n=t.filter(i=>gxi.indexOf(i.level)>=gxi.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===oE.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 Q6i({cliEnvironment:this.environment,includePreReleases:t}),n=gxe(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await hFu({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await lRf({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Mf.yellow("?"),style:{answer:i=>Mf.cyan(i),message:i=>Mf.bold(i),highlight:i=>Mf.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
2675
2675
  Cancelled by user.`),new gne):n}}async getInput(t){return await oRf({message:t.message,default:t.default})}};function mWy(e){return`[${e}]:`}var lqr=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:n,absoluteFilePath:i,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=n,this.absoluteFilePath=i,this.changelog=a}};var int=class extends lqr{definition;sources;type="fern";constructor({definition:t,sources:r,...n}){super(n),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var lht={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0,groupEnvironmentsByHost:!1};function ZZo({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??lht.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??lht.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??lht.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??lht.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??lht.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??lht.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??lht.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??lht.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??lht.respectForwardCompatibleEnums,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??lht.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??lht.coerceOptionalSchemasToNullable,groupEnvironmentsByHost:t?.groupEnvironmentsByHost??e?.groupEnvironmentsByHost??lht.groupEnvironmentsByHost}}var vPe={openapi:e=>({...e,type:"openapi",_visit:function(t){return vPe._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return vPe._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 Sro={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Sro._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var nde={basic:e=>({...e,type:"basic",_visit:function(t){return nde._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return nde._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return nde._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return nde._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return nde._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 TS={primitive:e=>({value:e,type:"primitive",_visit:function(t){return TS._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return TS._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return TS._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return TS._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return TS._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return TS._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return TS._visit(this,t)}}),null:e=>({...e,type:"null",_visit:function(t){return TS._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return TS._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"null":return t.null(e);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var zO={int:e=>({value:e,type:"int",_visit:function(t){return zO._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return zO._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return zO._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return zO._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return zO._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return zO._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return zO._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return zO._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return zO._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return zO._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return zO._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 L6i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return L6i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return L6i._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 U6i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return U6i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return U6i._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 BFu={};yf(BFu,{Availability:()=>ide,CustomCodeSample:()=>dVr,EndpointExample:()=>fht,EndpointResponseExample:()=>dht,HttpMethod:()=>ode,LiteralSchemaValue:()=>IV,MultipartRequestPropertyEncoding:()=>XRf,MultipartSchema:()=>pVr,OneOfSchema:()=>_Vr,Pagination:()=>ant,PrimitiveSchemaValue:()=>Rq,Request:()=>fqr,Response:()=>Yve,RetriesConfiguration:()=>kZo,Schema:()=>p1,SupportedSdkLanguage:()=>ade,WebhookHttpMethod:()=>YRf,WebsocketMessageOrigin:()=>$Rf});var $Rf={Client:"client",Server:"server",_visit:(e,t)=>{switch(e){case $Rf.Client:return t.client();case $Rf.Server:return t.server();default:return t._other()}}};var YRf={Get:"GET",Post:"POST",_visit:(e,t)=>{switch(e){case YRf.Get:return t.get();case YRf.Post:return t.post();default:return t._other()}}};var ide={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case ide.GenerallyAvailable:return t.generallyAvailable();case ide.Beta:return t.beta();case ide.Deprecated:return t.deprecated();default:return t._other()}}};var kZo={disabled:e=>({value:e,type:"disabled",_visit:function(t){return kZo._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"disabled":return t.disabled(e.value);default:return t._other(e)}}};var ant={cursor:e=>({...e,type:"cursor",_visit:function(t){return ant._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return ant._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return ant._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 dVr={language:e=>({...e,type:"language",_visit:function(t){return dVr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return dVr._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 ade={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 ade.Curl:return t.curl();case ade.Python:return t.python();case ade.Javascript:return t.javascript();case ade.Typescript:return t.typescript();case ade.Go:return t.go();case ade.Ruby:return t.ruby();case ade.Csharp:return t.csharp();case ade.Java:return t.java();case ade.Js:return t.js();case ade.Node:return t.node();case ade.Ts:return t.ts();case ade.Nodets:return t.nodets();case ade.Golang:return t.golang();case ade.Dotnet:return t.dotnet();case ade.Jvm:return t.jvm();default:return t._other()}}};var fht={unknown:e=>({value:e,type:"unknown",_visit:function(t){return fht._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return fht._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 dht={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return dht._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return dht._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 ode={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case ode.Get:return t.get();case ode.Post:return t.post();case ode.Put:return t.put();case ode.Patch:return t.patch();case ode.Delete:return t.delete();case ode.Head:return t.head();case ode.Options:return t.options();case ode.Trace:return t.trace();default:return t._other()}}};var fqr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return fqr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return fqr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return fqr._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return fqr._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 XRf={Json:"json",Form:"form",_visit:(e,t)=>{switch(e){case XRf.Json:return t.json();case XRf.Form:return t.form();default:return t._other()}}};var pVr={file:e=>({...e,type:"file",_visit:function(t){return pVr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return pVr._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 Yve={file:e=>({...e,type:"file",_visit:function(t){return Yve._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Yve._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Yve._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return Yve._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return Yve._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return Yve._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return Yve._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 p1={primitive:e=>({...e,type:"primitive",_visit:function(t){return p1._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return p1._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return p1._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return p1._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return p1._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return p1._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return p1._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return p1._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return p1._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return p1._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return p1._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 Rq={int:e=>({...e,type:"int",_visit:function(t){return Rq._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Rq._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Rq._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Rq._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Rq._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Rq._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Rq._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Rq._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Rq._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Rq._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Rq._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 IV={boolean:e=>({value:e,type:"boolean",_visit:function(t){return IV._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return IV._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 _Vr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return _Vr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return _Vr._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 hCe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return hCe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return hCe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return hCe._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return hCe._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 VL={file:e=>({...e,type:"file",_visit:function(t){return VL._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return VL._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return VL._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return VL._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return VL._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return VL._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return VL._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 Bh={primitive:e=>({...e,type:"primitive",_visit:function(t){return Bh._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Bh._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Bh._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Bh._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Bh._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Bh._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Bh._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Bh._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Bh._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Bh._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Bh._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 ont={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return ont._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return ont._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 tm={int:e=>({...e,type:"int",_visit:function(t){return tm._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tm._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return tm._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return tm._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return tm._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return tm._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tm._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return tm._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return tm._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return tm._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tm._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 Gj={};yf(Gj,{AllOfPropertyConflict:()=>kro,ArraySchema:()=>$xu,ArraySchemaWithExample:()=>E3u,Availability:()=>UFu,Base64WithExample:()=>O3u,BasicSecurityScheme:()=>WFu,BearerSecurityScheme:()=>HFu,BooleanSchema:()=>Vxu,BooleanWithExample:()=>A3u,BytesResponse:()=>Vro,CasingOverrides:()=>KFu,CommonProperty:()=>n3u,CommonPropertyWithExample:()=>R3u,CursorPagination:()=>Exu,CustomCodeSample:()=>wxu,CustomCodeSampleLanguage:()=>Oxu,CustomCodeSampleSdk:()=>Pxu,CustomPagination:()=>Dxu,DateWithExample:()=>m3u,DatetimeWithExample:()=>g3u,DiscriminatedOneOfSchema:()=>t3u,DiscriminatedOneOfSchemaWithExample:()=>T3u,DoubleSchema:()=>Lxu,DoubleWithExample:()=>v3u,Encoding:()=>LFu,Endpoint:()=>Cxu,EndpointExample:()=>Jro,EndpointResponseExample:()=>mxu,EndpointSdkName:()=>vVr,EndpointSecurity:()=>Rro,EndpointWithExample:()=>YWy,EnumSchema:()=>Bro,EnumSchemaWithExample:()=>w3u,EnumValue:()=>H6i,ErrorExample:()=>hxu,FernExample:()=>vxu,FileResponse:()=>Lro,FileSchema:()=>sxu,FloatWithExample:()=>y3u,FormUrlEncodedRequest:()=>dxu,FullEndpointExample:()=>jxu,FullExample:()=>jQ,FullObjectExample:()=>rxu,FullOneOfExample:()=>ixu,GlobalHeader:()=>Hxu,Header:()=>J6i,HeaderExample:()=>Gro,HeaderSecurityScheme:()=>GFu,HeaderWithExample:()=>Y6i,HttpEndpointServer:()=>Wro,HttpError:()=>yxu,HttpErrorWithExample:()=>f3u,HttpMethod:()=>Nro,IdempotencyHeader:()=>Gxu,Int64WithExample:()=>p3u,IntSchema:()=>zxu,IntWithExample:()=>d3u,JsonRequest:()=>fxu,JsonRequestWithExample:()=>s3u,JsonResponse:()=>Uro,JsonResponseWithExample:()=>rno,KeyValuePair:()=>nxu,LiteralExample:()=>exu,LiteralSchema:()=>Zro,LiteralSchemaValue:()=>Jxu,LongSchema:()=>Qxu,MapSchema:()=>Yxu,MapSchemaWithExample:()=>S3u,MultipartRequest:()=>Qro,MultipartRequestProperty:()=>lxu,MultipartRequestPropertyEncoding:()=>cxu,MultipartSchema:()=>uxu,NamedFullExample:()=>_ht,Namespace:()=>$Fu,NamespaceId:()=>kFu,NullExample:()=>txu,NullableSchema:()=>Zxu,NullableSchemaWithExample:()=>C3u,OauthSecurityScheme:()=>XFu,ObjectProperty:()=>e3u,ObjectPropertyConflictInfo:()=>eno,ObjectPropertyWithExample:()=>B3u,ObjectSchema:()=>Kxu,ObjectSchemaWithExample:()=>I3u,OctetStreamRequest:()=>zro,OffsetPagination:()=>Sxu,OneOfSchema:()=>kxu,OneOfSchemaWithExample:()=>M3u,OpenApiIntermediateRepresentation:()=>KWy,OpenApiSource:()=>FFu,OptionalSchema:()=>Xxu,OptionalSchemaWithExample:()=>D3u,Pagination:()=>Kro,ParseFormUrlEncodedRequest:()=>u3u,ParseMultipartRequest:()=>o3u,ParseOctetStreamRequest:()=>a3u,PathParameter:()=>Fro,PathParameterExample:()=>bxu,PathParameterWithExample:()=>i3u,PrimitiveExample:()=>qro,PrimitiveSchema:()=>$6i,PrimitiveSchemaValue:()=>Wxu,PrimitiveSchemaValueWithExample:()=>P3u,PrimitiveSchemaWithExample:()=>nno,PropertyKey:()=>Tro,ProtobufEncoding:()=>QFu,ProtobufSource:()=>xFu,QueryParameter:()=>xro,QueryParameterExample:()=>Hro,QueryParameterWithExample:()=>tno,QuerySecurityScheme:()=>JFu,ReferencedSchema:()=>bVr,Request:()=>pxu,RequestWithExample:()=>c3u,Response:()=>_xu,ResponseWithExample:()=>l3u,RetriesConfiguration:()=>$ro,Schema:()=>QI,SchemaId:()=>yCe,SchemaWithExample:()=>V4,Schemas:()=>xxu,SdkGroup:()=>YFu,SdkGroupInfo:()=>axu,SdkGroupName:()=>G6i,SecurityScheme:()=>ZFu,SecuritySchemeId:()=>Mro,Server:()=>nko,Source:()=>zFu,StatusCode:()=>hVr,StreamingResponseExample:()=>gxu,StringSchema:()=>Uxu,StringSchemaWithExample:()=>b3u,SupportedSdkLanguage:()=>Axu,Tag:()=>VFu,TagId:()=>vCe,Tags:()=>oxu,TextResponse:()=>K6i,Uint64WithExample:()=>h3u,UintWithExample:()=>_3u,UnDiscriminatedOneOfSchema:()=>r3u,UnDiscriminatedOneOfSchemaWithExample:()=>q3u,UnknownSchemaWithExample:()=>j3u,Webhook:()=>Ixu,WebhookExampleCall:()=>Xro,WebhookHttpMethod:()=>Yro,WebhookWithExample:()=>XWy,WebsocketChannel:()=>Fxu,WebsocketHandshake:()=>Mxu,WebsocketHandshakeWithExample:()=>$Wy,WebsocketMessageExample:()=>Rxu,WebsocketMessageOrigin:()=>Bxu,WebsocketMessageSchema:()=>Txu,WebsocketServer:()=>qxu,WebsocketSessionExample:()=>Nxu,WithAvailability:()=>iw,WithDescription:()=>Ov,WithEncoding:()=>Oxe,WithInline:()=>U4,WithName:()=>PD,WithNamespace:()=>qS,WithSdkGroupName:()=>FM,WithSdkMethodName:()=>yVr,WithSource:()=>AP,WithStatusCode:()=>pht,WithTitle:()=>NM,commons:()=>rNf,example:()=>nNf,finalIr:()=>iNf,parseIr:()=>aNf});var rNf={};yf(rNf,{BasicSecurityScheme:()=>WFu,BearerSecurityScheme:()=>HFu,Encoding:()=>LFu,HeaderSecurityScheme:()=>GFu,Namespace:()=>$Fu,NamespaceId:()=>kFu,OauthSecurityScheme:()=>XFu,OpenApiSource:()=>FFu,ProtobufEncoding:()=>QFu,ProtobufSource:()=>xFu,QuerySecurityScheme:()=>JFu,SchemaId:()=>yCe,SdkGroup:()=>YFu,SdkGroupName:()=>G6i,SecurityScheme:()=>ZFu,SecuritySchemeId:()=>Mro,Server:()=>nko,Source:()=>zFu,StatusCode:()=>hVr,Tag:()=>VFu,TagId:()=>vCe,WithAvailability:()=>iw,WithDescription:()=>Ov,WithEncoding:()=>Oxe,WithInline:()=>U4,WithName:()=>PD,WithNamespace:()=>qS,WithSdkGroupName:()=>FM,WithSdkMethodName:()=>yVr,WithSource:()=>AP,WithStatusCode:()=>pht,WithTitle:()=>NM});var Wr={};yf(Wr,{JsonError:()=>Dro,ParseError:()=>Cro,any:()=>RWy,bigint:()=>AWy,boolean:()=>NWy,booleanLiteral:()=>qWy,date:()=>PWy,discriminant:()=>HWy,enum_:()=>qFu,getObjectLikeUtils:()=>dqr,getObjectUtils:()=>Vla,getSchemaUtils:()=>wQ,isProperty:()=>W6i,lazy:()=>wWy,lazyObject:()=>MWy,list:()=>NFu,number:()=>FWy,object:()=>RFu,objectWithoutOptionalProperties:()=>IWy,optional:()=>ZRf,property:()=>EWy,record:()=>LWy,set:()=>UWy,string:()=>xWy,stringLiteral:()=>TWy,transform:()=>kRf,undiscriminatedUnion:()=>WWy,union:()=>JWy,unknown:()=>zWy,withParsedProperties:()=>tNf});var Nq={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 G7(e,t){return`Expected ${t}. Received ${IuI(e)}.`}function IuI(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 sde(e){return{...e,json:OWy(e.json),parse:OWy(e.parse)}}function OWy(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
2676
2676
  `)),{ok:!0,value:t}):n}}function TFu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var Dro=class e extends Error{errors;constructor(t){super(t.map(TFu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Cro=class e extends Error{errors;constructor(t){super(t.map(TFu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function wQ(e){return{optional:()=>ZRf(e),transform:t=>kRf(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Cro(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new Dro(n.errors)}}}function ZRf(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Nq.OPTIONAL};return{...t,...wQ(t)}}function kRf(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...wQ(r)}}function AWy(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:G7(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:G7(t,"bigint")}]},getType:()=>Nq.BIGINT};return{...sde(e),...wQ(e)}}var MuI=/^([+-]?\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 PWy(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:G7(t,"string")}]}:MuI.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:G7(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:G7(t,"Date object")}]},getType:()=>Nq.DATE};return{...sde(e),...wQ(e)}}function bPe(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...sde(r),...wQ(r)}}}function qFu(e){let t=new Set(e);return bPe(Nq.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:G7(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:G7(n,"enum")}]}:{ok:!0,value:n})()}function wWy(e){let t=eNf(e);return{...t,...wQ(t)}}function eNf(e){return{parse:(t,r)=>Iro(e).parse(t,r),json:(t,r)=>Iro(e).json(t,r),getType:()=>Iro(e).getType()}}function Iro(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function eko(e){return Object.entries(e)}function tko(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function V6i(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 rko(e){return Object.keys(e)}function jWy(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function dqr(e){return{withParsedProperties:t=>tNf(e,t)}}function tNf(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[f,u])=>({...c,[f]:typeof u=="function"?u(a.value):u}),{});return{ok:!0,value:{...a.value,...o}}},json:(n,i)=>{if(!V6i(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:G7(n,"object")}]};let a=new Set(Object.keys(t)),o=tko(n,Object.keys(n).filter(c=>!a.has(c)));return e.json(o,i)},getType:()=>e.getType()};return{...r,...wQ(r),...dqr(r)}}function EWy(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function W6i(e){return e.isProperty}function RFu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>W6i(n)?n.rawKey:r),_getParsedProperties:()=>rko(e),parse:(r,n)=>{let i={},a=[];for(let[o,c]of eko(e)){let f=W6i(c)?c.rawKey:o,u=W6i(c)?c.valueSchema:c,s={rawKey:f,parsedKey:o,valueSchema:u};i[f]=s,CWy(u)&&a.push(f)}return SWy({value:r,requiredKeys:a,getProperty:o=>{let c=i[o];if(c!=null)return{transformedKey:c.parsedKey,transform:f=>c.valueSchema.parse(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,o]of eko(e)){let c=W6i(o)?o.valueSchema:o;CWy(c)&&i.push(a)}return SWy({value:r,requiredKeys:i,getProperty:a=>{let o=e[a];if(o!=null)return W6i(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>Nq.OBJECT};return{...sde(t),...wQ(t),...dqr(t),...Vla(t)}}function SWy({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!V6i(e))return{ok:!1,errors:[{path:a,message:G7(e,"object")}]};let o=new Set(t),c=[],f={};for(let[u,s]of Object.entries(e)){let l=r(u);if(l!=null){o.delete(u);let m=l.transform(s);m.ok?f[l.transformedKey]=m.value:(f[u]=s,c.push(...m.errors))}else switch(n){case"fail":c.push({path:[...a,u],message:`Unexpected key "${u}"`});break;case"strip":break;case"passthrough":f[u]=s;break}}return c.push(...t.filter(u=>o.has(u)).map(u=>({path:a,message:`Missing required key "${u}"`}))),c.length===0||i?{ok:!0,value:f}:{ok:!1,errors:c}}function Vla(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>DWy({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>DWy({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>Nq.OBJECT};return{...r,...wQ(r),...dqr(r),...Vla(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,n)=>{let i=e.parse(r,{...n,unrecognizedObjectKeys:"passthrough"});return i.ok?{ok:!0,value:{...r,...i.value}}:i},json:(r,n)=>{let i=e.json(r,{...n,unrecognizedObjectKeys:"passthrough"});return i.ok?{ok:!0,value:{...r,...i.value}}:i},getType:()=>Nq.OBJECT};return{...t,...wQ(t),...dqr(t),...Vla(t)}}}}function DWy({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,o]=jWy(rko(t),u=>i.has(u)),c=r(tko(t,o)),f=n(tko(t,a));return c.ok&&f.ok?{ok:!0,value:{...c.value,...f.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...f.ok?[]:f.errors]}}function CWy(e){return!BuI(e)}function BuI(e){switch(e.getType()){case Nq.ANY:case Nq.UNKNOWN:case Nq.OPTIONAL:return!0;default:return!1}}function IWy(e){return RFu(e)}function MWy(e){let t={...eNf(e),_getRawProperties:()=>Iro(e)._getRawProperties(),_getParsedProperties:()=>Iro(e)._getParsedProperties()};return{...t,...wQ(t),...dqr(t),...Vla(t)}}function NFu(e){let t={parse:(r,n)=>BWy(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>BWy(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Nq.LIST};return{...sde(t),...wQ(t)}}function BWy(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:G7(e,"list"),path:[]}]}}function TWy(e){return bPe(Nq.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:G7(r,`"${e}"`)}]})()}function qWy(e){return bPe(Nq.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:G7(r,`${e.toString()}`)}]})()}var RWy=bPe(Nq.ANY,e=>({ok:!0,value:e}));var NWy=bPe(Nq.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:G7(e,"boolean")}]});var FWy=bPe(Nq.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:G7(e,"number")}]});var xWy=bPe(Nq.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:G7(e,"string")}]});var zWy=bPe(Nq.UNKNOWN,e=>({ok:!0,value:e}));function LWy(e,t){let r={parse:(n,i)=>QWy({value:n,isKeyNumeric:e.getType()===Nq.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>QWy({value:n,isKeyNumeric:e.getType()===Nq.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Nq.RECORD};return{...sde(r),...wQ(r)}}function QWy({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return V6i(e)?eko(e).reduce((a,[o,c])=>{if(c==null)return a;let f=a,u=o;if(t){let A=o.length>0?Number(o):NaN;isNaN(A)||(u=A)}let s=r(u),l=n(c,u);if(f.ok&&s.ok&&l.ok)return{ok:!0,value:{...f.value,[s.value]:l.value}};let m=[];return f.ok||m.push(...f.errors),s.ok||m.push(...s.errors),l.ok||m.push(...l.errors),{ok:!1,errors:m}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:G7(e,"object")}]}}function UWy(e){let t=NFu(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:G7(n,"Set")}]},getType:()=>Nq.SET};return{...sde(r),...wQ(r)}}function WWy(e){let t={parse:(r,n)=>VWy((i,a)=>i.parse(r,a),e,n),json:(r,n)=>VWy((i,a)=>i.json(r,a),e,n),getType:()=>Nq.UNDISCRIMINATED_UNION};return{...sde(t),...wQ(t)}}function VWy(e,t,r){let n=[];for(let[i,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)n.push({path:c.path,message:`[Variant ${i}] ${c.message}`})}return{ok:!1,errors:n}}function HWy(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function JWy(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=qFu(rko(t)),a={parse:(o,c)=>GWy({value:o,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:f=>i.parse(f,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,u)=>u.parse(f,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>GWy({value:o,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:f=>i.json(f,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,u)=>u.json(f,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>Nq.UNION};return{...sde(a),...wQ(a),...dqr(a)}}function GWy({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!V6i(e))return{ok:!1,errors:[{path:c,message:G7(e,"object")}]};let{[t]:f,...u}=e;if(f==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let s=n(f);if(!s.ok)return{ok:!1,errors:s.errors};let l=i(s.value);if(l==null)return a?{ok:!0,value:{[r]:s.value,...u}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let m=o(u,l);return m.ok?{ok:!0,value:{[r]:f,...m.value}}:m}var NM=Wr.objectWithoutOptionalProperties({title:Wr.string().optional()});var FFu=Wr.objectWithoutOptionalProperties({file:Wr.string()});var xFu=Wr.objectWithoutOptionalProperties({file:Wr.string()});var zFu=Wr.union("type",{openapi:FFu,protobuf:xFu}).transform({transform:e=>{switch(e.type){case"openapi":return vPe.openapi(e);case"protobuf":return vPe.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var AP=Wr.objectWithoutOptionalProperties({source:zFu.optional()});var QFu=Wr.objectWithoutOptionalProperties({typeName:Wr.string()});var LFu=Wr.union("type",{protobuf:QFu}).transform({transform:e=>{switch(e.type){case"protobuf":return Sro.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oxe=Wr.objectWithoutOptionalProperties({encoding:LFu.optional()});var Ov=Wr.objectWithoutOptionalProperties({description:Wr.string().optional()});var UFu=Wr.enum_(["GenerallyAvailable","Beta","Deprecated"]);var iw=Wr.objectWithoutOptionalProperties({availability:UFu.optional()});var hVr=Wr.number();var pht=Wr.objectWithoutOptionalProperties({statusCode:hVr.optional()});var PD=Wr.objectWithoutOptionalProperties({nameOverride:Wr.string().optional(),generatedName:Wr.string()});var U4=Wr.objectWithoutOptionalProperties({inline:Wr.boolean().optional()});var yCe=Wr.string();var vCe=Wr.string();var VFu=Wr.objectWithoutOptionalProperties({id:vCe}).extend(Ov);var Mro=Wr.string();var WFu=Wr.objectWithoutOptionalProperties({usernameVariableName:Wr.string().optional(),usernameEnvVar:Wr.string().optional(),passwordVariableName:Wr.string().optional(),passwordEnvVar:Wr.string().optional()});var HFu=Wr.objectWithoutOptionalProperties({tokenVariableName:Wr.string().optional(),tokenEnvVar:Wr.string().optional()});var GFu=Wr.objectWithoutOptionalProperties({headerName:Wr.string(),prefix:Wr.string().optional(),headerVariableName:Wr.string().optional(),headerEnvVar:Wr.string().optional()});var JFu=Wr.objectWithoutOptionalProperties({queryParameterName:Wr.string()});var KFu=Wr.objectWithoutOptionalProperties({snake:Wr.string().optional(),camel:Wr.string().optional(),screamingSnake:Wr.string().optional(),pascal:Wr.string().optional()});var H6i=Wr.objectWithoutOptionalProperties({nameOverride:Wr.string().optional(),generatedName:Wr.string(),value:Wr.string(),casing:KFu.optional()}).extend(Ov).extend(iw);var $Fu=Wr.objectWithoutOptionalProperties({type:Wr.stringLiteral("namespace"),name:Wr.string()});var YFu=Wr.undiscriminatedUnion([Wr.string(),$Fu]);var G6i=Wr.list(YFu);var FM=Wr.objectWithoutOptionalProperties({groupName:G6i.optional()});var qS=Wr.objectWithoutOptionalProperties({namespace:Wr.string().optional()});var Bro=Wr.objectWithoutOptionalProperties({default:H6i.optional(),values:Wr.list(H6i)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(AP).extend(NM).extend(U4);var XFu=Wr.objectWithoutOptionalProperties({scopesEnum:Bro.optional()});var ZFu=Wr.union("type",{basic:WFu,bearer:HFu,header:GFu,query:JFu,oauth:XFu}).transform({transform:e=>{switch(e.type){case"basic":return nde.basic(e);case"bearer":return nde.bearer(e);case"header":return nde.header(e);case"query":return nde.query(e);case"oauth":return nde.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var nko=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),url:Wr.string(),audiences:Wr.list(Wr.string()).optional()}).extend(Ov);var kFu=Wr.string();var yVr=Wr.objectWithoutOptionalProperties({sdkMethodName:Wr.string().optional()});var nNf={};yf(nNf,{FullExample:()=>jQ,FullObjectExample:()=>rxu,FullOneOfExample:()=>ixu,KeyValuePair:()=>nxu,LiteralExample:()=>exu,NullExample:()=>txu,PrimitiveExample:()=>qro,PropertyKey:()=>Tro});var Tro=Wr.string();var qro=Wr.union("type",{int:Wr.object({value:Wr.number()}),int64:Wr.object({value:Wr.number()}),uint:Wr.object({value:Wr.number()}),uint64:Wr.object({value:Wr.number()}),float:Wr.object({value:Wr.number()}),double:Wr.object({value:Wr.number()}),string:Wr.object({value:Wr.string()}),datetime:Wr.object({value:Wr.string()}),date:Wr.object({value:Wr.string()}),base64:Wr.object({value:Wr.string()}),boolean:Wr.object({value:Wr.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return zO.int(e.value);case"int64":return zO.int64(e.value);case"uint":return zO.uint(e.value);case"uint64":return zO.uint64(e.value);case"float":return zO.float(e.value);case"double":return zO.double(e.value);case"string":return zO.string(e.value);case"datetime":return zO.datetime(e.value);case"date":return zO.date(e.value);case"base64":return zO.base64(e.value);case"boolean":return zO.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var exu=Wr.union("type",{boolean:Wr.object({value:Wr.boolean()}),string:Wr.object({value:Wr.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return L6i.boolean(e.value);case"string":return L6i.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var txu=Wr.objectWithoutOptionalProperties({});var jQ=Wr.union("type",{primitive:Wr.object({value:qro}),object:Wr.lazyObject(()=>rxu),array:Wr.object({value:Wr.list(Wr.lazy(()=>jQ))}),map:Wr.object({value:Wr.list(Wr.lazyObject(()=>nxu))}),enum:Wr.object({value:Wr.string()}),literal:Wr.object({value:exu}),oneOf:Wr.object({value:Wr.lazy(()=>ixu)}),null:txu,unknown:Wr.object({value:Wr.lazy(()=>jQ)})}).transform({transform:e=>{switch(e.type){case"primitive":return TS.primitive(e.value);case"object":return TS.object(e);case"array":return TS.array(e.value);case"map":return TS.map(e.value);case"enum":return TS.enum(e.value);case"literal":return TS.literal(e.value);case"oneOf":return TS.oneOf(e.value);case"null":return TS.null(e);case"unknown":return TS.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var rxu=Wr.objectWithoutOptionalProperties({properties:Wr.record(Tro,Wr.lazy(()=>jQ))});var nxu=Wr.objectWithoutOptionalProperties({key:qro,value:Wr.lazy(()=>jQ)});var ixu=Wr.union("type",{discriminated:Wr.object({value:Wr.record(Tro,Wr.lazy(()=>jQ))}),undiscriminated:Wr.object({value:Wr.lazy(()=>jQ)})}).transform({transform:e=>{switch(e.type){case"discriminated":return U6i.discriminated(e.value);case"undiscriminated":return U6i.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var iNf={};yf(iNf,{AllOfPropertyConflict:()=>kro,ArraySchema:()=>$xu,Availability:()=>UFu,BooleanSchema:()=>Vxu,BytesResponse:()=>Vro,CasingOverrides:()=>KFu,CommonProperty:()=>n3u,CursorPagination:()=>Exu,CustomCodeSample:()=>wxu,CustomCodeSampleLanguage:()=>Oxu,CustomCodeSampleSdk:()=>Pxu,CustomPagination:()=>Dxu,DiscriminatedOneOfSchema:()=>t3u,DoubleSchema:()=>Lxu,Endpoint:()=>Cxu,EndpointExample:()=>Jro,EndpointResponseExample:()=>mxu,EndpointSdkName:()=>vVr,EndpointSecurity:()=>Rro,EnumSchema:()=>Bro,EnumValue:()=>H6i,ErrorExample:()=>hxu,FernExample:()=>vxu,FileResponse:()=>Lro,FileSchema:()=>sxu,FormUrlEncodedRequest:()=>dxu,FullEndpointExample:()=>jxu,GlobalHeader:()=>Hxu,Header:()=>J6i,HeaderExample:()=>Gro,HttpEndpointServer:()=>Wro,HttpError:()=>yxu,HttpMethod:()=>Nro,IdempotencyHeader:()=>Gxu,IntSchema:()=>zxu,JsonRequest:()=>fxu,JsonResponse:()=>Uro,LiteralSchema:()=>Zro,LiteralSchemaValue:()=>Jxu,LongSchema:()=>Qxu,MapSchema:()=>Yxu,MultipartRequest:()=>Qro,MultipartRequestProperty:()=>lxu,MultipartRequestPropertyEncoding:()=>cxu,MultipartSchema:()=>uxu,NullableSchema:()=>Zxu,ObjectProperty:()=>e3u,ObjectPropertyConflictInfo:()=>eno,ObjectSchema:()=>Kxu,OctetStreamRequest:()=>zro,OffsetPagination:()=>Sxu,OneOfSchema:()=>kxu,OpenApiIntermediateRepresentation:()=>KWy,OptionalSchema:()=>Xxu,Pagination:()=>Kro,PathParameter:()=>Fro,PathParameterExample:()=>bxu,PrimitiveSchema:()=>$6i,PrimitiveSchemaValue:()=>Wxu,QueryParameter:()=>xro,QueryParameterExample:()=>Hro,ReferencedSchema:()=>bVr,Request:()=>pxu,Response:()=>_xu,RetriesConfiguration:()=>$ro,Schema:()=>QI,Schemas:()=>xxu,SdkGroupInfo:()=>axu,StreamingResponseExample:()=>gxu,StringSchema:()=>Uxu,SupportedSdkLanguage:()=>Axu,Tags:()=>oxu,TextResponse:()=>K6i,UnDiscriminatedOneOfSchema:()=>r3u,Webhook:()=>Ixu,WebhookExampleCall:()=>Xro,WebhookHttpMethod:()=>Yro,WebsocketChannel:()=>Fxu,WebsocketHandshake:()=>Mxu,WebsocketMessageExample:()=>Rxu,WebsocketMessageOrigin:()=>Bxu,WebsocketMessageSchema:()=>Txu,WebsocketServer:()=>qxu,WebsocketSessionExample:()=>Nxu});var axu=Wr.objectWithoutOptionalProperties({summary:Wr.string().optional(),description:Wr.string().optional()});var oxu=Wr.objectWithoutOptionalProperties({tagsById:Wr.record(vCe,VFu),orderedTagIds:Wr.list(vCe).optional()});var Rro=Wr.list(Wr.record(Mro,Wr.list(Wr.string())));var Nro=Wr.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var Fro=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>QI),variableReference:Wr.string().optional(),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var xro=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>QI),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var J6i=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>QI),env:Wr.string().optional(),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var vVr=Wr.objectWithoutOptionalProperties({groupName:G6i,methodName:Wr.string()});var zro=Wr.objectWithoutOptionalProperties({contentType:Wr.string().optional()}).extend(Ov).extend(AP);var sxu=Wr.objectWithoutOptionalProperties({isOptional:Wr.boolean(),isArray:Wr.boolean()}).extend(Ov);var uxu=Wr.union("type",{file:sxu,json:Wr.object({value:Wr.lazy(()=>QI)})}).transform({transform:e=>{switch(e.type){case"file":return pVr.file(e);case"json":return pVr.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var cxu=Wr.enum_(["json","form"]);var lxu=Wr.objectWithoutOptionalProperties({key:Wr.string(),schema:uxu,contentType:Wr.string().optional(),exploded:Wr.boolean().optional(),encoding:cxu.optional()}).extend(Ov);var Qro=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),properties:Wr.list(lxu)}).extend(Ov).extend(AP);var fxu=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>QI),contentType:Wr.string().optional(),additionalProperties:Wr.boolean()}).extend(Ov).extend(AP);var dxu=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>QI),contentType:Wr.string().optional(),additionalProperties:Wr.boolean()}).extend(Ov).extend(AP);var pxu=Wr.union("type",{octetStream:zro,multipart:Qro,json:fxu,formUrlEncoded:dxu}).transform({transform:e=>{switch(e.type){case"octetStream":return fqr.octetStream(e);case"multipart":return fqr.multipart(e);case"json":return fqr.json(e);case"formUrlEncoded":return fqr.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var Lro=Wr.objectWithoutOptionalProperties({}).extend(Ov).extend(AP).extend(pht);var Uro=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>QI),responseProperty:Wr.string().optional()}).extend(Ov).extend(AP).extend(pht);var K6i=Wr.objectWithoutOptionalProperties({}).extend(Ov).extend(AP).extend(pht);var Vro=Wr.objectWithoutOptionalProperties({}).extend(Ov).extend(AP).extend(pht);var _xu=Wr.union("type",{file:Lro,json:Uro,text:K6i,bytes:Vro,streamingSse:Uro,streamingText:K6i,streamingJson:Uro}).transform({transform:e=>{switch(e.type){case"file":return Yve.file(e);case"json":return Yve.json(e);case"text":return Yve.text(e);case"bytes":return Yve.bytes(e);case"streamingSse":return Yve.streamingSse(e);case"streamingText":return Yve.streamingText(e);case"streamingJson":return Yve.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var hxu=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),description:Wr.string().optional(),example:Wr.lazy(()=>jQ)});var yxu=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>QI).optional(),examples:Wr.list(hxu).optional()}).extend(Ov).extend(PD).extend(AP);var Wro=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),url:Wr.string().optional(),audiences:Wr.list(Wr.string()).optional()});var vxu=Wr.unknown();var bxu=Wr.objectWithoutOptionalProperties({name:Wr.string(),parameterNameOverride:Wr.string().optional(),value:Wr.lazy(()=>jQ)});var Hro=Wr.objectWithoutOptionalProperties({name:Wr.string(),value:Wr.lazy(()=>jQ)});var Gro=Wr.objectWithoutOptionalProperties({name:Wr.string(),value:Wr.lazy(()=>jQ)});var gxu=Wr.objectWithoutOptionalProperties({sse:Wr.boolean(),events:Wr.list(Wr.lazy(()=>jQ))});var mxu=Wr.union("type",{withStreaming:gxu,withoutStreaming:Wr.object({value:Wr.lazy(()=>jQ)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return dht.withStreaming(e);case"withoutStreaming":return dht.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Oxu=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),language:Wr.string(),code:Wr.string(),install:Wr.string().optional()}).extend(Ov);var Axu=Wr.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var Pxu=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),sdk:Axu,code:Wr.string()}).extend(Ov);var wxu=Wr.union("type",{language:Oxu,sdk:Pxu}).transform({transform:e=>{switch(e.type){case"language":return dVr.language(e);case"sdk":return dVr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var jxu=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),pathParameters:Wr.list(bxu).optional(),queryParameters:Wr.list(Hro).optional(),headers:Wr.list(Gro).optional(),request:Wr.lazy(()=>jQ).optional(),response:mxu.optional(),codeSamples:Wr.list(wxu)}).extend(Ov);var Jro=Wr.union("type",{unknown:Wr.object({value:vxu}),full:jxu}).transform({transform:e=>{switch(e.type){case"unknown":return fht.unknown(e.value);case"full":return fht.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Exu=Wr.objectWithoutOptionalProperties({cursor:Wr.string(),nextCursor:Wr.property("next_cursor",Wr.string()),results:Wr.string()});var Sxu=Wr.objectWithoutOptionalProperties({offset:Wr.string(),results:Wr.string(),step:Wr.string().optional(),hasNextPage:Wr.string().optional()});var Dxu=Wr.objectWithoutOptionalProperties({results:Wr.string()});var Kro=Wr.union("type",{cursor:Exu,offset:Sxu,custom:Dxu}).transform({transform:e=>{switch(e.type){case"cursor":return ant.cursor(e);case"offset":return ant.offset(e);case"custom":return ant.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var $ro=Wr.union("type",{disabled:Wr.object({value:Wr.boolean().optional()})}).transform({transform:e=>{switch(e.type){case"disabled":return kZo.disabled(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Cxu=Wr.objectWithoutOptionalProperties({authed:Wr.boolean(),security:Rro,internal:Wr.boolean().optional(),idempotent:Wr.boolean().optional(),method:Nro,audiences:Wr.list(Wr.string()),path:Wr.string(),summary:Wr.string().optional(),operationId:Wr.string().optional(),tags:Wr.list(vCe),pathParameters:Wr.list(Fro),queryParameters:Wr.list(xro),headers:Wr.list(J6i),sdkName:vVr.optional(),generatedRequestName:Wr.string(),requestNameOverride:Wr.string().optional(),request:pxu.optional(),response:_xu.optional(),errors:Wr.record(hVr,yxu),servers:Wr.list(Wro),examples:Wr.list(Jro),pagination:Kro.optional(),retries:$ro.optional()}).extend(Ov).extend(iw).extend(AP).extend(qS);var Yro=Wr.enum_(["GET","POST"]);var Xro=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),payload:Wr.lazy(()=>jQ)}).extend(Ov);var Ixu=Wr.objectWithoutOptionalProperties({audiences:Wr.list(Wr.string()),sdkName:vVr.optional(),method:Yro,summary:Wr.string().optional(),operationId:Wr.string(),tags:Wr.list(vCe),headers:Wr.list(J6i),generatedPayloadName:Wr.string(),payload:Wr.lazy(()=>QI),examples:Wr.list(Xro)}).extend(Ov).extend(AP).extend(qS);var Mxu=Wr.objectWithoutOptionalProperties({queryParameters:Wr.list(xro),headers:Wr.list(J6i),pathParameters:Wr.list(Fro)});var Bxu=Wr.enum_(["client","server"]);var Txu=Wr.objectWithoutOptionalProperties({name:Wr.string(),origin:Bxu,body:Wr.lazy(()=>QI)});var qxu=Wr.objectWithoutOptionalProperties({name:Wr.string(),url:Wr.string()});var Rxu=Wr.objectWithoutOptionalProperties({messageType:Wr.string(),payload:Wr.lazy(()=>jQ)}).extend(Ov);var Nxu=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),queryParameters:Wr.list(Hro).optional(),headers:Wr.list(Gro).optional(),messages:Wr.list(Rxu)}).extend(Ov);var Fxu=Wr.objectWithoutOptionalProperties({audiences:Wr.list(Wr.string()),path:Wr.string(),groupName:G6i,summary:Wr.string().optional(),handshake:Mxu,messages:Wr.list(Txu),servers:Wr.list(qxu),examples:Wr.list(Nxu)}).extend(Ov).extend(AP);var xxu=Wr.objectWithoutOptionalProperties({rootSchemas:Wr.record(yCe,Wr.lazy(()=>QI)),namespacedSchemas:Wr.record(kFu,Wr.record(yCe,Wr.lazy(()=>QI)))});var zxu=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),minimum:Wr.number().optional(),maximum:Wr.number().optional(),exclusiveMinimum:Wr.boolean().optional(),exclusiveMaximum:Wr.boolean().optional(),multipleOf:Wr.number().optional()});var Qxu=Wr.objectWithoutOptionalProperties({default:Wr.number().optional()});var Lxu=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),minimum:Wr.number().optional(),maximum:Wr.number().optional(),exclusiveMinimum:Wr.boolean().optional(),exclusiveMaximum:Wr.boolean().optional(),multipleOf:Wr.number().optional()});var Uxu=Wr.objectWithoutOptionalProperties({default:Wr.string().optional(),pattern:Wr.string().optional(),format:Wr.string().optional(),minLength:Wr.number().optional(),maxLength:Wr.number().optional()});var Vxu=Wr.objectWithoutOptionalProperties({default:Wr.boolean().optional()});var Wxu=Wr.union("type",{int:zxu,int64:Qxu,uint:Wr.object({}),uint64:Wr.object({}),float:Wr.object({}),double:Lxu,string:Uxu,datetime:Wr.object({}),date:Wr.object({}),base64:Wr.object({}),boolean:Vxu}).transform({transform:e=>{switch(e.type){case"int":return Rq.int(e);case"int64":return Rq.int64(e);case"uint":return Rq.uint();case"uint64":return Rq.uint64();case"float":return Rq.float();case"double":return Rq.double(e);case"string":return Rq.string(e);case"datetime":return Rq.datetime();case"date":return Rq.date();case"base64":return Rq.base64();case"boolean":return Rq.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var $6i=Wr.objectWithoutOptionalProperties({schema:Wxu}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM);var Hxu=Wr.objectWithoutOptionalProperties({header:Wr.string(),name:Wr.string().optional(),optional:Wr.boolean().optional(),env:Wr.string().optional(),schema:Wr.lazy(()=>QI).optional()});var Gxu=Wr.objectWithoutOptionalProperties({header:Wr.string(),name:Wr.string().optional(),env:Wr.string().optional(),schema:Wr.lazy(()=>QI).optional()});var KWy=Wr.objectWithoutOptionalProperties({apiVersion:Wr.unknown().optional(),title:Wr.string().optional(),description:Wr.string().optional(),basePath:Wr.string().optional(),servers:Wr.list(nko),websocketServers:Wr.list(nko),groups:Wr.record(Wr.string(),axu),tags:oxu,hasEndpointsMarkedInternal:Wr.boolean(),endpoints:Wr.list(Cxu),webhooks:Wr.list(Ixu),channels:Wr.record(Wr.string(),Fxu),groupedSchemas:xxu,variables:Wr.record(Wr.string(),$6i),nonRequestReferencedSchemas:Wr.set(yCe),securitySchemes:Wr.record(Mro,ZFu),globalHeaders:Wr.list(Hxu).optional(),idempotencyHeaders:Wr.list(Gxu).optional()});var bVr=Wr.objectWithoutOptionalProperties({schema:yCe}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(AP).extend(NM);var Jxu=Wr.union("type",{boolean:Wr.object({value:Wr.boolean()}),string:Wr.object({value:Wr.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return IV.boolean(e.value);case"string":return IV.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Zro=Wr.objectWithoutOptionalProperties({value:Jxu}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM);var QI=Wr.union("type",{primitive:$6i,object:Wr.lazyObject(()=>Kxu),array:Wr.lazyObject(()=>$xu),map:Wr.lazyObject(()=>Yxu),optional:Wr.lazyObject(()=>Xxu),enum:Bro,reference:bVr,literal:Zro,oneOf:Wr.object({value:Wr.lazy(()=>kxu)}),nullable:Wr.lazyObject(()=>Zxu),unknown:PD}).transform({transform:e=>{switch(e.type){case"primitive":return p1.primitive(e);case"object":return p1.object(e);case"array":return p1.array(e);case"map":return p1.map(e);case"optional":return p1.optional(e);case"enum":return p1.enum(e);case"reference":return p1.reference(e);case"literal":return p1.literal(e);case"oneOf":return p1.oneOf(e.value);case"nullable":return p1.nullable(e);case"unknown":return p1.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var kro=Wr.objectWithoutOptionalProperties({propertyKey:Wr.string(),allOfSchemaIds:Wr.list(yCe),conflictingTypeSignatures:Wr.boolean()});var Kxu=Wr.objectWithoutOptionalProperties({allOf:Wr.list(bVr),properties:Wr.list(Wr.lazyObject(()=>e3u)),allOfPropertyConflicts:Wr.list(kro),additionalProperties:Wr.boolean()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(AP).extend(NM).extend(U4);var eno=Wr.objectWithoutOptionalProperties({differentSchema:Wr.boolean()});var e3u=Wr.objectWithoutOptionalProperties({key:Wr.string(),schema:Wr.lazy(()=>QI),readonly:Wr.boolean().optional(),writeonly:Wr.boolean().optional(),conflict:Wr.record(yCe,eno),generatedName:Wr.string(),nameOverride:Wr.string().optional(),audiences:Wr.list(Wr.string())}).extend(iw);var $xu=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>QI)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var Yxu=Wr.objectWithoutOptionalProperties({key:$6i,value:Wr.lazy(()=>QI)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(NM).extend(U4);var Xxu=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>QI)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var Zxu=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>QI)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var kxu=Wr.union("type",{discriminated:Wr.lazyObject(()=>t3u),undiscriminated:Wr.lazyObject(()=>r3u)}).transform({transform:e=>{switch(e.type){case"discriminated":return _Vr.discriminated(e);case"undiscriminated":return _Vr.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var t3u=Wr.objectWithoutOptionalProperties({discriminantProperty:Wr.string(),commonProperties:Wr.list(Wr.lazyObject(()=>n3u)),schemas:Wr.record(Wr.string(),Wr.lazy(()=>QI))}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(AP).extend(NM).extend(U4);var n3u=Wr.objectWithoutOptionalProperties({key:Wr.string(),schema:Wr.lazy(()=>QI)});var r3u=Wr.objectWithoutOptionalProperties({schemas:Wr.list(Wr.lazy(()=>QI))}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(AP).extend(NM).extend(U4);var aNf={};yf(aNf,{ArraySchemaWithExample:()=>E3u,Base64WithExample:()=>O3u,BooleanWithExample:()=>A3u,CommonPropertyWithExample:()=>R3u,DateWithExample:()=>m3u,DatetimeWithExample:()=>g3u,DiscriminatedOneOfSchemaWithExample:()=>T3u,DoubleWithExample:()=>v3u,EndpointWithExample:()=>YWy,EnumSchemaWithExample:()=>w3u,FloatWithExample:()=>y3u,HeaderWithExample:()=>Y6i,HttpErrorWithExample:()=>f3u,Int64WithExample:()=>p3u,IntWithExample:()=>d3u,JsonRequestWithExample:()=>s3u,JsonResponseWithExample:()=>rno,MapSchemaWithExample:()=>S3u,NamedFullExample:()=>_ht,NullableSchemaWithExample:()=>C3u,ObjectPropertyWithExample:()=>B3u,ObjectSchemaWithExample:()=>I3u,OneOfSchemaWithExample:()=>M3u,OptionalSchemaWithExample:()=>D3u,ParseFormUrlEncodedRequest:()=>u3u,ParseMultipartRequest:()=>o3u,ParseOctetStreamRequest:()=>a3u,PathParameterWithExample:()=>i3u,PrimitiveSchemaValueWithExample:()=>P3u,PrimitiveSchemaWithExample:()=>nno,QueryParameterWithExample:()=>tno,RequestWithExample:()=>c3u,ResponseWithExample:()=>l3u,SchemaWithExample:()=>V4,StringSchemaWithExample:()=>b3u,Uint64WithExample:()=>h3u,UintWithExample:()=>_3u,UnDiscriminatedOneOfSchemaWithExample:()=>q3u,UnknownSchemaWithExample:()=>j3u,WebhookWithExample:()=>XWy,WebsocketHandshakeWithExample:()=>$Wy});var _ht=Wr.objectWithoutOptionalProperties({name:Wr.string().optional(),value:Wr.unknown()}).extend(Ov);var tno=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>V4),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var Y6i=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>V4),env:Wr.string().optional(),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var $Wy=Wr.objectWithoutOptionalProperties({queryParameters:Wr.list(tno),headers:Wr.list(Y6i)});var i3u=Wr.objectWithoutOptionalProperties({name:Wr.string(),schema:Wr.lazy(()=>V4),variableReference:Wr.string().optional(),parameterNameOverride:Wr.string().optional()}).extend(Ov).extend(iw).extend(AP);var a3u=Wr.objectWithoutOptionalProperties({}).extend(zro).extend(yVr);var o3u=Wr.objectWithoutOptionalProperties({}).extend(Qro).extend(yVr);var s3u=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>V4),contentType:Wr.string().optional(),fullExamples:Wr.list(_ht).optional(),additionalProperties:Wr.boolean()}).extend(Ov).extend(AP).extend(yVr);var u3u=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>V4),contentType:Wr.string().optional(),fullExamples:Wr.list(_ht).optional(),additionalProperties:Wr.boolean()}).extend(Ov).extend(AP).extend(yVr);var c3u=Wr.union("type",{octetStream:a3u,multipart:o3u,json:s3u,formUrlEncoded:u3u}).transform({transform:e=>{switch(e.type){case"octetStream":return hCe.octetStream(e);case"multipart":return hCe.multipart(e);case"json":return hCe.json(e);case"formUrlEncoded":return hCe.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var rno=Wr.objectWithoutOptionalProperties({schema:Wr.lazy(()=>V4),responseProperty:Wr.string().optional(),fullExamples:Wr.list(_ht).optional()}).extend(Ov).extend(AP).extend(pht);var l3u=Wr.union("type",{file:Lro,json:rno,text:K6i,bytes:Vro,streamingSse:rno,streamingText:K6i,streamingJson:rno}).transform({transform:e=>{switch(e.type){case"file":return VL.file(e);case"json":return VL.json(e);case"text":return VL.text(e);case"bytes":return VL.bytes(e);case"streamingSse":return VL.streamingSse(e);case"streamingText":return VL.streamingText(e);case"streamingJson":return VL.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var f3u=Wr.objectWithoutOptionalProperties({statusCode:hVr,schema:Wr.lazy(()=>V4),fullExamples:Wr.list(_ht).optional()}).extend(Ov).extend(PD).extend(AP);var YWy=Wr.objectWithoutOptionalProperties({authed:Wr.boolean(),security:Rro,internal:Wr.boolean().optional(),idempotent:Wr.boolean().optional(),method:Nro,audiences:Wr.list(Wr.string()),path:Wr.string(),summary:Wr.string().optional(),operationId:Wr.string().optional(),tags:Wr.list(vCe),pathParameters:Wr.list(i3u),queryParameters:Wr.list(tno),headers:Wr.list(Y6i),sdkName:vVr.optional(),generatedRequestName:Wr.string(),requestNameOverride:Wr.string().optional(),request:c3u.optional(),response:l3u.optional(),errors:Wr.record(hVr,f3u),servers:Wr.list(Wro),examples:Wr.list(Jro),pagination:Kro.optional(),retries:$ro.optional()}).extend(Ov).extend(iw).extend(AP).extend(qS);var XWy=Wr.objectWithoutOptionalProperties({audiences:Wr.list(Wr.string()),sdkName:vVr.optional(),method:Yro,summary:Wr.string().optional(),operationId:Wr.string(),tags:Wr.list(vCe),headers:Wr.list(Y6i),generatedPayloadName:Wr.string(),payload:Wr.lazy(()=>V4),examples:Wr.list(Xro)}).extend(Ov).extend(AP).extend(qS);var d3u=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),minimum:Wr.number().optional(),maximum:Wr.number().optional(),exclusiveMinimum:Wr.boolean().optional(),exclusiveMaximum:Wr.boolean().optional(),multipleOf:Wr.number().optional(),example:Wr.number().optional()});var p3u=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),example:Wr.number().optional()});var _3u=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),example:Wr.number().optional()});var h3u=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),example:Wr.number().optional()});var y3u=Wr.objectWithoutOptionalProperties({example:Wr.number().optional()});var v3u=Wr.objectWithoutOptionalProperties({default:Wr.number().optional(),minimum:Wr.number().optional(),maximum:Wr.number().optional(),exclusiveMinimum:Wr.boolean().optional(),exclusiveMaximum:Wr.boolean().optional(),multipleOf:Wr.number().optional(),example:Wr.number().optional()});var b3u=Wr.objectWithoutOptionalProperties({default:Wr.string().optional(),pattern:Wr.string().optional(),format:Wr.string().optional(),minLength:Wr.number().optional(),maxLength:Wr.number().optional(),example:Wr.string().optional()});var g3u=Wr.objectWithoutOptionalProperties({example:Wr.string().optional()});var m3u=Wr.objectWithoutOptionalProperties({example:Wr.string().optional()});var O3u=Wr.objectWithoutOptionalProperties({example:Wr.string().optional()});var A3u=Wr.objectWithoutOptionalProperties({default:Wr.boolean().optional(),example:Wr.boolean().optional()});var P3u=Wr.union("type",{int:d3u,int64:p3u,uint:_3u,uint64:h3u,float:y3u,double:v3u,string:b3u,datetime:g3u,date:m3u,base64:O3u,boolean:A3u}).transform({transform:e=>{switch(e.type){case"int":return tm.int(e);case"int64":return tm.int64(e);case"uint":return tm.uint(e);case"uint64":return tm.uint64(e);case"float":return tm.float(e);case"double":return tm.double(e);case"string":return tm.string(e);case"datetime":return tm.datetime(e);case"date":return tm.date(e);case"base64":return tm.base64(e);case"boolean":return tm.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var nno=Wr.objectWithoutOptionalProperties({schema:P3u}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM);var w3u=Wr.objectWithoutOptionalProperties({default:H6i.optional(),values:Wr.list(H6i),example:Wr.string().optional()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(AP).extend(NM).extend(U4);var j3u=Wr.objectWithoutOptionalProperties({example:Wr.unknown()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM);var V4=Wr.union("type",{primitive:nno,object:Wr.lazyObject(()=>I3u),array:Wr.lazyObject(()=>E3u),map:Wr.lazyObject(()=>S3u),optional:Wr.lazyObject(()=>D3u),enum:w3u,reference:bVr,literal:Zro,oneOf:Wr.object({value:Wr.lazy(()=>M3u)}),nullable:Wr.lazyObject(()=>C3u),unknown:j3u}).transform({transform:e=>{switch(e.type){case"primitive":return Bh.primitive(e);case"object":return Bh.object(e);case"array":return Bh.array(e);case"map":return Bh.map(e);case"optional":return Bh.optional(e);case"enum":return Bh.enum(e);case"reference":return Bh.reference(e);case"literal":return Bh.literal(e);case"oneOf":return Bh.oneOf(e.value);case"nullable":return Bh.nullable(e);case"unknown":return Bh.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var E3u=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>V4),example:Wr.list(Wr.unknown()).optional()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var S3u=Wr.objectWithoutOptionalProperties({key:nno,value:Wr.lazy(()=>V4),example:Wr.unknown().optional()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(NM).extend(U4);var D3u=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>V4)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var C3u=Wr.objectWithoutOptionalProperties({value:Wr.lazy(()=>V4)}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(NM).extend(U4);var I3u=Wr.objectWithoutOptionalProperties({allOf:Wr.list(bVr),properties:Wr.list(Wr.lazyObject(()=>B3u)),allOfPropertyConflicts:Wr.list(kro),fullExamples:Wr.list(_ht).optional(),additionalProperties:Wr.boolean()}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(AP).extend(NM).extend(U4);var B3u=Wr.objectWithoutOptionalProperties({key:Wr.string(),schema:Wr.lazy(()=>V4),readonly:Wr.boolean().optional(),writeonly:Wr.boolean().optional(),audiences:Wr.list(Wr.string()),conflict:Wr.record(yCe,eno),nameOverride:Wr.string().optional(),generatedName:Wr.string()}).extend(iw);var M3u=Wr.union("type",{discriminated:Wr.lazyObject(()=>T3u),undiscriminated:Wr.lazyObject(()=>q3u)}).transform({transform:e=>{switch(e.type){case"discriminated":return ont.discriminated(e);case"undiscriminated":return ont.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var T3u=Wr.objectWithoutOptionalProperties({discriminantProperty:Wr.string(),commonProperties:Wr.list(Wr.lazyObject(()=>R3u)),schemas:Wr.record(Wr.string(),Wr.lazy(()=>V4))}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(AP).extend(NM).extend(U4);var R3u=Wr.objectWithoutOptionalProperties({key:Wr.string(),schema:Wr.lazy(()=>V4)});var q3u=Wr.objectWithoutOptionalProperties({schemas:Wr.list(Wr.lazy(()=>V4))}).extend(FM).extend(qS).extend(PD).extend(Ov).extend(iw).extend(Oxe).extend(AP).extend(NM).extend(U4);var ZWy=/^(\d+)/,ino=/^[a-zA-Z][a-zA-Z0-9_]*$/,kWy={"<":"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 X6i(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],n=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let o=Math.floor(e/10),c=e%10;return c===0?n[o]:`${n[o]}_${t[c]}`}if(e<1e3){let o=Math.floor(e/100),c=e%100;return c===0?`${t[o]}_hundred`:`${t[o]}_hundred_${X6i(c)}`}let i=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[i]}_thousand`:`${t[i]}_thousand_${X6i(a)}`}function iko(e){let t=e.match(ZWy);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let a=X6i(i);return n.length>0?`${a}_${n}`:a}}}function ano(e){let t=iko(e),r=kWy[e];return t!=null?X9($A(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":X9($A(e)))}function Axe(e,t){return e.type==="primitive"&&t.type==="primitive"?eHy(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?TuI(e.values,t.values):e.type==="array"&&t.type==="array"?Axe(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"?Axe(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?quI(e.value,t.value):e.type==="object"&&t.type==="object"?RuI(e,t):e.type==="map"&&t.type==="map"?eHy(e.key.schema,t.key.schema)&&Axe(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function eHy(e,t){return e.type===t.type}function TuI(e,t){let r=new Set(...e.map(i=>i.value)),n=new Set(...t.map(i=>i.value));return tse(r,n)}function quI(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,n])=>{let i=t.schemas[r];return i==null?!1:Axe(n,i)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,n)=>{let i=t.schemas[n];return i==null?!1:Axe(r,i)}):!1}function RuI(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(n=>[n.key,n.schema]));return Object.entries(t.properties).every(([n,i])=>{let a=r[n];return a==null?!1:Axe(a,i.schema)})}function RJ(e){switch(e){case ide.Deprecated:return"deprecated";case ide.Beta:return"pre-release";case ide.GenerallyAvailable:return"generally-available";default:return}}function NuI(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function tHy(e){let t=e?NuI(e):void 0;if(t==null||t.length===0)return nia;let r=[];for(let[n,i]of t.entries())if(typeof i=="string")r.push($A(i));else if(typeof i=="object")switch(i.type){case"namespace":{n<t.length-1?r.push($A(i.name)):r.push(i.name,nia);break}default:ku(i.type)}else ku(i);return r.join("/")}function Z6i(e){return Sw.of(`${tHy(e)}.yml`)}function oNf({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?nia:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,tHy(r))}function rHy({sdkName:e,namespaceOverride:t}){return Sw.of(`${oNf({sdkName:e,namespaceOverride:t})}.yml`)}function nHy({location:e,namespaceOverride:t}){return t!=null?RX(Sw.of(t),e):e}function N3u(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:ku(e.type)}}function ono(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:ku(e)}}function W4(e){return typeof e=="string"?e:e.type}function sno(e){if(typeof e!="string")return e.docs}function ako(e){if(typeof e!="string")return e.default}function sNf(e){if(typeof e!="string")return e.validation}function aHy(e){let t=W4(e);return t.startsWith("nullable<")||t.startsWith("optional<nullable<")?e:typeof e=="string"?iHy(e):{...e,type:iHy(e.type)}}function iHy(e){return e.startsWith("nullable<")||e.startsWith("optional<nullable<")?e:e.startsWith("optional<")?e.replace("optional<","optional<nullable<")+">":`nullable<${e}>`}function Wla(e){return W4(e).startsWith("optional<")?e:typeof e=="string"?oHy(e):{...e,type:oHy(e.type)}}function oHy(e){return e.startsWith("optional<")?e:`optional<${e}>`}var FuI=-2147483648,xuI=2147483647,zuI=-17976931348623157e292,QuI=17976931348623157e292;function vC({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i,declarationDepth:a}){switch(n.shouldMarkSchemaAsReferenced()&&n.markSchemaAsReferenced(e,i),e.type){case"primitive":return F3u(e);case"array":return lNf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"map":return fNf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"reference":return cNf({schema:e,fileContainingReference:t,context:n,namespace:i});case"unknown":return pNf();case"optional":return x3u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"nullable":return dNf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"enum":return $uI({schema:e,fileContainingReference:t,context:n,declarationFile:r,declarationDepth:a});case"literal":return e.value,_Nf(e);case"object":return YuI({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"oneOf":return XuI({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});default:ku(e)}}function F3u(e){switch(e.schema.type){case"string":return VuI({description:e.description,schema:e.schema});case"int":return WuI({description:e.description,schema:e.schema});case"float":return HuI({description:e.description,schema:e.schema});case"double":return GuI({description:e.description,schema:e.schema});case"boolean":return LuI({description:e.description,schema:e.schema});case"int64":return UuI({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:RJ(e.availability)}:{}}}function LuI({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function UuI({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function VuI({description:e,schema:t}){let r="string",n=JuI(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function WuI({description:e,schema:t}){let r="integer",n=sHy(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function HuI({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function GuI({description:e,schema:t}){let r="double",n=sHy(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function JuI(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,a=KuI(t);if(!(a==null&&r==null&&n==null&&i==null))return{format:a,pattern:r,minLength:n,maxLength:i}}function KuI(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 sHy(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:a,exclusiveMaximum:o}=e;if(r=uNf(r,t),n=uNf(n,t),i=uNf(i,t),!(r==null&&n==null&&a==null&&o==null&&i==null))return{min:r,max:n,exclusiveMin:a,exclusiveMax:o,multipleOf:i}}function uNf(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[FuI,xuI]:[zuI,QuI];return e<r||e>n?void 0:e}function cNf({schema:e,fileContainingReference:t,context:r,namespace:n}){let i=r.getSchema(e.schema,n);if(i==null)return"unknown";let a=ZuI(i)??e.schema,o=ono(i),c=kuI(i),u=z3u({context:r,fileContainingReference:t,declarationFile:Z6i(o),type:a});return i.type==="nullable"&&(u=r.wrapReferencesToNullableInOptional?`optional<${u}>`:`nullable<${u}>`),i.type==="optional"&&!u.startsWith("optional<")&&(u=`optional<${u}>`),e.description==null&&c==null?u:{type:u,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:RJ(e.availability)}:{}}}function lNf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=vC({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=`list<${W4(o)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:RJ(e.availability)}:{},type:c}}function fNf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=F3u(e.key),c=vC({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),f=e.encoding!=null?N3u(e.encoding):void 0,u=`map<${W4(o)}, ${W4(c)}>`;if(e.description==null&&f==null&&e.title==null)return u;let s={type:u};return e.description!=null&&(s.docs=e.description),e.encoding!=null&&(s.encoding=f),e.availability!=null&&(s.availability=RJ(e.availability)),s}function dNf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){if(!n.respectNullableSchemas)return x3u({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});let o=vC({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=W4(o),f=sno(o),u=ako(o),s=sNf(o),l=aHy(c);if(n.wrapReferencesToNullableInOptional&&(l=Wla(l)),e.availability==null&&e.description==null&&f==null&&u==null&&s==null&&e.title==null)return l;let m=typeof l=="string"?{type:l}:l;return(e.description!=null||f!=null)&&(m.docs=e.description??f),u!=null&&(m.default=u),s!=null&&(m.validation=s),e.availability!=null&&(m.availability=RJ(e.availability)),m}function x3u({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=vC({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=W4(o),f=sno(o),u=ako(o),s=sNf(o),l=Wla(c);if(e.availability==null&&e.description==null&&f==null&&u==null&&s==null&&e.title==null)return l;let m=typeof l=="string"?{type:l}:l;return(e.description!=null||f!=null)&&(m.docs=e.description??f),u!=null&&(m.default=u),s!=null&&(m.validation=s),e.availability!=null&&(m.availability=RJ(e.availability)),m}function pNf(){return"unknown"}function _Nf(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:ku(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:RJ(e.availability)}:{}}}function $uI({schema:e,fileContainingReference:t,declarationFile:r,context:n,declarationDepth:i}){let a=oko(e,i),o=e.nameOverride??e.generatedName;n.builder.addType(r,{name:o,schema:a.schema});let c=z3u({type:o,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return c;let f={type:c};return e.description!=null&&(f.docs=e.description),e.default!=null&&(f.default=e.default.value),e.availability!=null&&(f.availability=RJ(e.availability)),f}function YuI({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=hNf({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:o.schema});let f=z3u({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:RJ(e.availability)}:{}}}function XuI({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=yNf({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:o.schema});let f=z3u({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?f:{...e.title!=null?{"display-name":e.title}:{},type:f,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:RJ(e.availability)}:{}}}function z3u({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function ZuI(e){return p1._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 kuI(e){return p1._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:()=>{}})}var Cse;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(Cse||(Cse={}));function wPi(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:ku(e)}}function cHy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a;switch(e.type){case"primitive":a=rcI(e);break;case"array":a=ecI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"map":a=tcI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"reference":a=ncI({schema:e,context:t,declarationFile:r,namespace:n});break;case"unknown":a=acI(e.nameOverride,e.generatedName);break;case"optional":a=fHy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"nullable":a=icI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"enum":a=oko(e,i);break;case"literal":a=ocI(e,e.nameOverride,e.generatedName);break;case"object":a=hNf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"oneOf":a=yNf({schema:e.value,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;default:ku(e)}return a}function hNf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a=t.isInState(Cse.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),o=!1,c={},f=new Set;for(let A of e.properties){if(A.readonly&&(o=!0),a&&A.readonly)continue;if(Object.keys(A.conflict).length>0){if(Object.entries(A.conflict).every(([q,V])=>!V.differentSchema))continue;Object.entries(A.conflict).forEach(([q])=>{vNf({property:A.key,schemaId:q,context:t,namespace:n}).forEach($=>{f.add($)})})}let P=vC({schema:A.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1}),C=A.audiences,I=A.nameOverride,T=RJ(A.availability),z=lcI(A);c[A.key]=ccI({typeReference:P,audiences:C,name:I,availability:T,propertyAccess:z})}let u=new Set;for(let A of e.allOfPropertyConflicts)A.allOfSchemaIds.forEach(P=>f.add(P)),A.conflictingTypeSignatures&&u.add(A.propertyKey);let s=[];for(let A of e.allOf){let P=dHy({schema:A.schema,context:t,namespace:n});if(P==null||f.has(A.schema)||f.has(P))continue;let C=vC({schema:p1.reference(A),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1});s.push(W4(C))}for(let A of f){let P=bNf(t,A,n);for(let C of P.properties)c[C.key]==null&&(u.has(C.key)&&(c[C.key]="unknown"),c[C.key]=vC({schema:C.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1}));for(let C of P.allOf){if(f.has(C.schema))continue;let I=vC({schema:p1.reference(C),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1});s.push(W4(I))}}let l={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(c).map(([A,P])=>ucI(A)?[A,typeof P=="string"?{type:P,name:`_${A}`}:{...P,name:`_${A}`}]:[A,P]))};s.length>0&&(l.extends=s),e.additionalProperties&&(l["extra-properties"]=!0),e.availability!=null&&(l.availability=RJ(e.availability)),e.source!=null&&(l.source=wPi(e.source)),l.inline=gNf(e,i);let m=e.nameOverride??e.generatedName;return{name:o&&t.respectReadonlySchemas&&!a?`${m}Read`:m,schema:l}}function vNf({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return vNf({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:a,allOf:o}=bNf(r,t,n),c=a.some(u=>u.key===e),f=[...o.flatMap(u=>vNf({property:e,context:r,schemaId:u.schema,namespace:n}))];if(c||f.length>0)return[t,...f]}return[]}function lHy(e,t,r){return t.type==="object"?{properties:t.properties,allOf:t.allOf}:t.type==="reference"?bNf(e,t.schema,r):t.type==="nullable"?lHy(e,t.value,r):{properties:[],allOf:[]}}function bNf(e,t,r){let n=e.getSchema(t,r);return n==null?{properties:[],allOf:[]}:lHy(e,n,r)}function ecI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:lNf({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function tcI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:fNf({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function rcI(e){let t=F3u(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function uHy(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function oko(e,t){let r={enum:e.values.map(a=>{let o=a.nameOverride??a.generatedName,c=a.value;if(o===c&&a.description==null&&(a.casing==null||uHy(a.casing)))return o;let f={value:a.value};if(o!==c&&(f.name=o),a.description!=null&&(f.docs=a.description),a.casing!=null&&!uHy(a.casing)){let u={},s=!1;a.casing.camel!=null&&(u.camel=a.casing.camel,s=!0),a.casing.screamingSnake!=null&&(u["screaming-snake"]=a.casing.screamingSnake,s=!0),a.casing.snake!=null&&(u.snake=a.casing.snake,s=!0),a.casing.pascal!=null&&(u.pascal=a.casing.pascal,s=!0),s&&(f.casing=u)}return f})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=gNf(e,t);let n=new Set,i={...r,enum:[],source:e.source!=null?wPi(e.source):void 0};for(let a of r.enum){let o=typeof a=="string"?a:a.name??a.value;n.has(o.toLowerCase())||(i.enum.push(a),n.add(o.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:i}}function ncI({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:cNf({schema:e,context:t,fileContainingReference:r,namespace:n})}}function icI({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:dNf({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}:fHy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i})}function fHy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:x3u({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}}function acI(e,t){return{name:e??t,schema:pNf()}}function ocI(e,t,r){return{name:t??r,schema:_Nf(e)}}function yNf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a=e.encoding!=null?N3u(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let u of e.commonProperties)c[u.key]=vC({schema:u.schema,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1});let f={};for(let[u,s]of Object.entries(e.schemas))f[u]=vC({schema:s,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?RJ(e.availability):void 0,union:f,encoding:a,source:e.source!=null?wPi(e.source):void 0}}}let o=[];for(let c of e.schemas)o.push(vC({schema:c,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:o,encoding:a,source:e.source!=null?wPi(e.source):void 0,inline:gNf(e,i)}}}var scI=/^[0-9]/;function ucI(e){return scI.test(e)}function dHy({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?dHy({context:t,schema:n.schema,namespace:r}):e}function ccI({typeReference:e,audiences:t,name:r,availability:n,propertyAccess:i}){return t.length===0&&r==null&&n==null&&i==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{},...i!=null?{access:i}:{}}}function gNf(e,t){return e.inline===!0||t>0?!0:void 0}function lcI(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return FX.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return FX.ObjectPropertyAccess.WriteOnly}}function pHy(e){let t=e.replace(/^x-|^X-/,"");return $A(t)}function _Hy(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??pHy(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(Sw.of("__package__.yml"),{name:"OauthScope",schema:oko(n.scopesEnum,0).schema})}}function gVr({header:e,context:t,fileContainingReference:r,namespace:n}){let i=vC({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),a=W4(i),o=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:$A(o);if(e.description==null&&e.name===c&&e.env==null&&e.availability==null)return a;let f={type:a};return c!==e.name&&(f.name=c),e.description!=null&&(f.docs=e.description),e.env!=null&&(f.env=e.env),e.availability!=null&&(f.availability=RJ(e.availability)),f}function Q3u({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=vC({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return W4(i);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:W4(i)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=RJ(e.availability)),a}function U3u({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=mNf({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let a=W4(i.value),o=ako(i.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let c={type:a};return o!=null&&(c.default=o),i.allowMultiple&&(c["allow-multiple"]=!0),e.description!=null&&(c.docs=e.description),e.parameterNameOverride!=null&&(c.name=e.parameterNameOverride),e.availability!=null&&(c.availability=RJ(e.availability)),fcI(i.value)&&i.value.validation!==void 0&&(c.validation=i.value.validation),c.default==null&&c["allow-multiple"]==null&&c.docs==null&&c.name==null&&c.availability==null&&c.validation==null?a:c}function mNf({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:vC({schema:p1.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:Sw.of(mF),fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undiscriminated"){let a=[],o=!1;for(let[c,f]of Object.entries(i.value.schemas))f.type==="primitive"&&f.schema.type==="string"&&(o=!0),f.type==="literal"&&f.value.type==="string"&&(ino.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:ano(f.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),o&&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(i.value.schemas.length===2){let[c,f]=i.value.schemas;if(c!=null&&f!=null&&L3u({array:c,primitive:f}))return{value:vC({schema:p1.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:f,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(c!=null&&f!=null&&L3u({array:c,primitive:f}))return{value:vC({schema:p1.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:n,declarationDepth:0}),allowMultiple:!0}}for(let[c,f]of Object.entries(i.value.schemas))return mNf({schema:f,context:t,fileContainingReference:r,namespace:n})}else if(t.objectQueryParameters)return{value:vC({schema:e,context:t,fileContainingReference:r,declarationFile:Sw.of(mF),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){let i=e.type==="optional"?p1.optional:p1.nullable;if(e.value.type==="reference"){let a=t.getSchema(e.value.schema,n);if(a==null)return;if(a.type==="array")return{value:vC({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a.value,description:e.description??a.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:Sw.of(mF),namespace:n,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:vC({schema:e,context:t,fileContainingReference:r,declarationFile:Sw.of(mF),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:vC({schema:i({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:n,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let a=[],o=!1;for(let[c,f]of Object.entries(e.value.value.schemas))f.type==="primitive"&&f.schema.type==="string"&&(o=!0),f.type==="literal"&&f.value.type==="string"&&(ino.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:ano(f.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),o&&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[c,f]=e.value.value.schemas;if(c!=null&&f!=null&&L3u({array:c,primitive:f}))return{value:vC({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:f,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(c!=null&&f!=null&&L3u({array:f,primitive:c}))return{value:vC({schema:i({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:n,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:vC({schema:e,context:t,fileContainingReference:r,declarationFile:Sw.of(mF),namespace:n,declarationDepth:0}),allowMultiple:!1};for(let[c,f]of Object.entries(e.value.value.schemas))return mNf({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:f,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return t.objectQueryParameters?{value:vC({schema:e,context:t,fileContainingReference:r,declarationFile:Sw.of(mF),namespace:n,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:vC({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:vC({schema:p1.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:n,declarationDepth:0}),allowMultiple:!0}:{value:vC({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}function L3u({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function fcI(e){return typeof e=="object"&&e!==null&&"type"in e}function hHy({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"]=dcI(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=pcI({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=k6i(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function dcI(e){let t={};return e.forEach(r=>{let n=k6i(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function pcI({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=k6i(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function k6i(e){switch(e.type){case"primitive":return yHy(e.value);case"object":return vHy(e.properties);case"array":return _cI(e.value);case"map":return hcI(e.value);case"oneOf":return ycI(e.value);case"enum":return e.value;case"literal":return vcI(e.value);case"unknown":return k6i(e.value);case"null":return null;default:ku(e)}}function yHy(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:ku(e)}}function vHy(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,k6i(r)]))}function _cI(e){return e.map(t=>k6i(t))}function hcI(e){return Object.fromEntries(e.map(t=>[yHy(t.key),k6i(t.value)]))}function ycI(e){return e.type==="discriminated"?vHy(e.value):k6i(e.value)}function vcI(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:ku(e)}}function sko(e){try{let r=new URL(e).pathname.split("/").filter(n=>n.length>0);if(r.length>0)return r[r.length-1]}catch{}}function V3u(e){try{return new URL(e).protocol.replace(":","")}catch{return}}function W3u(e,t,r=!1){let n=sko(t);return r&&n!=null?n:e!=null&&n!=null?`${e}_${n}`:n??e??"websocket"}function jPi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function H3u(e,t){return t??(e?.groupName!=null?jPi(e.groupName):void 0)}function bHy({channel:e,context:t,declarationFile:r}){let n=e.servers[0],i=n!=null?t.groupEnvironmentsByHost?t.getUrlId(n.url)??W3u(n.name,n.url,!0):n.name:void 0;t.logger.debug(`[buildChannel] Channel path="${e.path}", server name="${n?.name}", server url="${n?.url}", resolved urlId="${i}" (from collision map: ${t.getUrlId(n?.url??"")!=null})`);let a={path:e.path,url:i,auth:!1};e.audiences!=null&&e.audiences.length>0&&(a.audiences=e.audiences),e.summary!=null&&(a["display-name"]=e.summary),e.description!=null&&(a.docs=e.description);let o=jPi(e.groupName),c={};if(e.handshake.pathParameters.length>0)for(let s of e.handshake.pathParameters)c[s.name]=Q3u({pathParameter:s,context:t,fileContainingReference:r,namespace:o});Object.keys(c).length>0&&(a["path-parameters"]=c);let f={};if(e.handshake.queryParameters.length>0)for(let s of e.handshake.queryParameters){let l=U3u({queryParameter:s,context:t,fileContainingReference:r,namespace:o});l!=null&&(f[s.name]=l)}Object.keys(f).length>0&&(a["query-parameters"]=f);let u={};if(e.handshake.headers.length>0)for(let s of e.handshake.headers){let l=gVr({header:s,context:t,fileContainingReference:r,namespace:o});u[s.name]=l}Object.keys(u).length>0&&(a.headers=u),t.builder.addChannel(r,{channel:a});for(let s of e.messages)t.builder.addChannelMessage(r,{messageId:s.name,message:{origin:s.origin,body:vC({schema:s.body,context:t,fileContainingReference:r,namespace:o,declarationDepth:0})}});for(let s of e.examples){let l=hHy({context:t,websocketExample:s});t.builder.addChannelExample(r,{example:l})}}function ONf(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}var hht="Base",OHy="Default";function gHy(e){try{return new URL(e).hostname}catch{return}}function mHy(e){return e??OHy}function bcI(e,t){let r=new Map;for(let n of e){if(ONf(n)||!("url"in n)||!n.url)continue;let i=gHy(n.url)??n.url;r.has(i)||r.set(i,{environmentName:mHy(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.httpServers.push({name:n.name,url:n.url,audiences:n.audiences})}for(let n of t){let i=gHy(n.url)??n.url;r.has(i)||r.set(i,{environmentName:mHy(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.websocketServers.push(n)}return r}function Hla(e){return Object.entries(e).reduce((t,[r,n])=>(Ort(n)?Object.entries(n.urls).forEach(([i,a])=>{t[i]=a}):t[r]=typeof n=="string"?n:n.url,t),{})}function AHy(e){if(e.environmentOverrides!=null){for(let[T,z]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:T,schema:z});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=[],n=e.ir.servers.some(T=>ONf(T)),i=e.ir.servers;for(let T of i)if(ONf(T)){let z={urls:{}};for(let[U,q]of Object.entries(T.urls))z.urls[U]=q.url;T.name&&(t[T.name]=z)}else if("url"in T&&T.url){let z=T.audiences?{url:T.url,audiences:T.audiences}:T.url;if(T.name==null){r.push(z);continue}t[T.name]=z}let a={},o={},c=[];for(let T of e.ir.endpoints)for(let z of T.servers){if(z.url==null&&z.name!=null){a[z.name]||(a[z.name]=[]);continue}if(z.url==null)continue;let U=z.audiences?{url:z.url,audiences:z.audiences}:z.url;if(z.name==null){c.push(U);continue}a[z.name]||(a[z.name]=[]),a[z.name]?.push({url:z.url,audiences:z.audiences}),o[z.name]=U}let f={},u=[];for(let T of e.ir.websocketServers){e.logger.debug(`[buildEnvironments] Processing WebSocket server: name="${T.name}", url="${T.url}"`);let z=T.audiences?{url:T.url,audiences:T.audiences}:T.url;if(T.name==null){u.push(z);continue}f[T.name]=z}let s=Object.keys(t).length,l=s>0,m=Object.keys(o).length>0,A=Object.keys(a).some(T=>a[T]?.length===0),P=Object.keys(f).length>0;if(e.groupEnvironmentsByHost&&P&&(l||e.ir.servers.length>0)){let T=Object.entries(f).map(([U,q])=>({name:U,url:typeof q=="string"?q:q.url,audiences:typeof q=="string"?void 0:q.audiences})),z=bcI(i,T);if(z.size>0){let U=!0;for(let[q,V]of z.entries()){let $={},re=[...V.httpServers.map(k=>({...k,isHttp:!0})),...V.websocketServers.map(k=>({...k,isHttp:!1}))],Y=new Map;for(let k of re){let ne=sko(k.url),Oe=V3u(k.url);ne&&Oe&&(Y.has(ne)||Y.set(ne,new Set),Y.get(ne)?.add(Oe))}if(V.httpServers.length>0){let k=V.httpServers[0];k!=null&&($[hht]=k.url,e.setUrlId(k.url,hht));for(let ne=1;ne<V.httpServers.length;ne++){let Oe=V.httpServers[ne];if(Oe!=null){let he=sko(Oe.url),me=V3u(Oe.url),ve=he?Y.get(he):void 0,Ce=ve&&ve.size>1,Se=Ce&&me!=="https"?`${he}_${me}`:he||`Http${ne+1}`;e.logger.debug(`[buildEnvironments] HTTP server: url="${Oe.url}", pathSegment="${he}", protocol="${me}", hasCollision=${Ce}, urlId="${Se}"`),$[Se]=Oe.url,e.setUrlId(Oe.url,Se)}}}for(let k of V.websocketServers){let ne=sko(k.url),Oe=V3u(k.url),he=ne?Y.get(ne):void 0,me=he&&he.size>1,ve=me?`${ne}_${Oe}`:W3u(k.name,k.url,!0);e.logger.debug(`[buildEnvironments] WebSocket server: name="${k.name}", url="${k.url}", pathSegment="${ne}", protocol="${Oe}", hasCollision=${me}, urlId="${ve}"`),$[ve]=k.url,e.setUrlId(k.url,ve)}if(Object.keys($).length>1)e.builder.addEnvironment({name:V.environmentName,schema:{urls:$}});else if(Object.keys($).length===1){let k=Object.values($)[0];k!=null&&e.builder.addEnvironment({name:V.environmentName,schema:k})}U&&(e.builder.setDefaultEnvironment(V.environmentName),Object.keys($).length>1&&e.builder.setDefaultUrl(hht),U=!1)}return}}if(!l&&!m&&P&&e.ir.servers.length===0){for(let[T,z]of Object.entries(f))e.builder.addEnvironment({name:T,schema:z});e.builder.setDefaultEnvironment(Object.keys(f)[0]),e.builder.setDefaultUrl(hht);return}if(c.length>0&&e.logger.debug(`Skipping endpoint level servers ${c.map(T=>typeof T=="string"?T:T.url).join(", ")} because x-fern-server-name was not provided.`),!l){let T=e.ir.servers[0]?.url,z=e.ir.servers[0]?.audiences;if(T!=null){let U=z?{url:T,audiences:z}:T;t[OHy]=U}}let C=Object.values(t).map(T=>typeof T=="string"?T:Ort(T)?Object.values(T.urls)[0]:T.url),I=r.filter(T=>{let z=typeof T=="string"?T:T.url;return!C.includes(z)});if(I.length>0&&e.logger.debug(`Skipping top level servers ${I.map(T=>typeof T=="string"?T:T.url).join(", ")} because x-fern-server-name was not provided.`),n){let T=!0;for(let[z,U]of Object.entries(t))if(e.builder.addEnvironment({name:z,schema:U}),T){if(e.builder.setDefaultEnvironment(z),Ort(U)){let q=Object.keys(U.urls)[0];q&&e.builder.setDefaultUrl(q)}T=!1}return}if(!m&&!A){let T=!0;for(let[z,U]of Object.entries(t))if(T){if(P){let q=typeof U=="string"?U:Ort(U)?Object.values(U.urls)[0]:U.url;e.builder.addEnvironment({name:z,schema:{urls:{[hht]:q??"",...Hla(f)}}})}else e.builder.addEnvironment({name:z,schema:U});e.builder.setDefaultEnvironment(z),T=!1}else if(P){let q=typeof U=="string"?U:Ort(U)?Object.values(U.urls)[0]:U.url;e.builder.addEnvironment({name:z,schema:{urls:{[hht]:q??"",...Hla(f)}}})}else e.builder.addEnvironment({name:z,schema:U});P&&e.builder.setDefaultUrl(hht)}else if(s===1){let T=Object.keys(t)[0],z=Object.values(t)[0],U=typeof z=="string"?z:Ort(z)?Object.values(z.urls)[0]:z.url;e.builder.addEnvironment({name:T,schema:{urls:{[hht]:U??"",...Hla(o),...Hla(f)}}}),e.builder.setDefaultEnvironment(T),e.builder.setDefaultUrl(hht)}else{let T=new Map;for(let z of e.ir.endpoints)for(let U of z.servers)if(U.url!=null&&U.name!=null){T.has(U.name)||T.set(U.name,new Map);let q=U.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",V=T.get(U.name);V&&V.set(q,U.url)}if(T.size>0){let z=!0;for(let[U,q]of Object.entries(t)){let V=typeof q=="string"?q:Ort(q)?Object.values(q.urls)[0]:q.url;if(!V)continue;let $=V.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",re={[hht]:V};for(let[Y,k]of T.entries()){let ne=k.get($)||k.get("production")||k.values().next().value;ne&&(re[Y]=ne)}P&&Object.assign(re,Hla(f)),Object.keys(re).length>1?e.builder.addEnvironment({name:U,schema:{urls:re}}):e.builder.addEnvironment({name:U,schema:V}),z&&(e.builder.setDefaultEnvironment(U),z=!1)}T.size>0&&e.builder.setDefaultUrl(hht)}else{let z=!0;for(let[U,q]of Object.entries(t)){if(P||Object.keys(o).length>0){let V=typeof q=="string"?q:Ort(q)?Object.values(q.urls)[0]:q.url;e.builder.addEnvironment({name:U,schema:{urls:{[hht]:V??"",...Hla(o),...Hla(f)}}})}else e.builder.addEnvironment({name:U,schema:q});z&&(e.builder.setDefaultEnvironment(U),z=!1)}}}}var ANf=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},gcI=.75,mcI=new Set("authorization");function PHy(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let i="optional<string>";if(n.name==null&&n.env==null&&typeof n.schema=="string")i=n.schema;else if(n!=null){let a=n.schema?ono(n.schema):void 0,o=a!=null?jPi(a):void 0,c=Sw.of("api.yml");i={name:n.name,env:n.env,type:n.schema!=null?W4(vC({schema:n.schema,context:e,fileContainingReference:o?RX(Sw.of($A(o)),c):c,namespace:o,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:i})}if(e.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let a of i.headers){if(mcI.has(a.name.toLowerCase()))continue;let o=r[a.name];if(o==null){let c=t[a.name],f=gVr({header:{...a,schema:c?.schema??a.schema,name:c?.name??a.name},fileContainingReference:Sw.of(Qk),context:e,namespace:void 0});o=new ANf(f),r[a.name]=o}o.increment()}let n=e.ir.endpoints.length*gcI;for(let[i,a]of Object.entries(r)){let o=t[i],c=a.count===e.ir.endpoints.length,f=a.count>=n;o==null&&(c?e.builder.addGlobalHeader({name:i,schema:a.schema}):f&&e.builder.addGlobalHeader({name:i,schema:Wla(a.schema)}))}}}function wHy(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?ono(t.schema):void 0,n=r!=null?jPi(r):void 0,i=gVr({header:{...t,schema:t.schema??p1.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:Rq.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:Sw.of(Qk),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:Wla(i)})}}function gPe(e){switch(e.type){case"primitive":return EHy(e.value);case"object":return SHy(e.properties);case"array":return DHy(e.value);case"map":return AcI(e.value);case"oneOf":return PcI(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return wcI(e.value);case"unknown":return gPe(e.value);case"null":return null;default:ku(e)}}function jHy(e){switch(e.type){case"withStreaming":return e.sse?{stream:OcI(e.events)}:{stream:DHy(e.events)};case"withoutStreaming":return{body:gPe(e.value)};default:ku(e)}}function EHy(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:ku(e)}}function SHy(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,gPe(r)]))}function OcI(e){return e.map(t=>({event:"",data:gPe(t)}))}function DHy(e){return e.map(t=>gPe(t))}function AcI(e){return Object.fromEntries(e.map(t=>[EHy(t.key),gPe(t.value)]))}function PcI(e){return e.type==="discriminated"?SHy(e.value):gPe(e.value)}function wcI(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:ku(e)}}function CHy({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"]=jcI(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=EcI(e.queryParameters));let n=e.headers!=null&&e.headers.length>0,i=t.builder.getGlobalHeaders(),a=Object.keys(i).length>0,o=new Set(e.headers?.map(c=>c.name)??[]);if(n||a){let c=[];if(e.headers!=null)for(let f of e.headers)f.name!==t.builder.getAuthHeaderName()&&c.push(f);for(let[f,u]of Object.entries(i))if(!o.has(f))if(u!=null&&typeof u=="object"&&u.type!=null){let s=ree({type:u.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:xc}});s!=null&&c.push({name:f,value:TS.literal(L6i.string(s))})}else c.push({name:f,value:TS.primitive(zO.string(f))});r.headers=ScI({context:t,namedFullExamples:c})}return e.request!=null&&(r.request=gPe(e.request)),e.response!=null&&(r.response=jHy(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(pj)),r}function jcI(e){let t={};return e.forEach(r=>{let n=gPe(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function EcI(e){let t={};return e.forEach(r=>{let n=gPe(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function ScI({context:e,namedFullExamples:t}){let r={};return t.forEach(n=>{let i=gPe(n.value);i!=null&&(r[n.name]=i)}),r}function IHy(e){return ode._visit(e,{get:()=>FX.HttpMethodSchema.Get,post:()=>FX.HttpMethodSchema.Post,put:()=>FX.HttpMethodSchema.Put,patch:()=>FX.HttpMethodSchema.Patch,delete:()=>FX.HttpMethodSchema.Delete,head:()=>FX.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 MHy(e){return e==="POST"||e==="PUT"||e==="PATCH"}function BHy({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:n}=r.ir,i=[],a=new Set,o=e.path,c=H3u(e.sdkName,e.namespace),f={};for(let I of e.pathParameters)I.parameterNameOverride&&(o=o.replace(I.name,I.parameterNameOverride)),f[I.parameterNameOverride??I.name]=Q3u({pathParameter:I,context:r,fileContainingReference:t,namespace:c}),a.add(I.name);let u={};for(let I of e.queryParameters){let T=U3u({queryParameter:I,context:r,fileContainingReference:t,namespace:c});T!=null&&(u[I.name]=T,a.add(I.name))}let s;if(e.pagination!=null)switch(e.pagination.type){case"cursor":s={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":s={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":s={type:"custom",results:e.pagination.results};break;default:ku(e.pagination)}let l={path:o,method:IHy(e.method),auth:Object.keys(e.security).length>0?e.security:void 0,docs:e.description??void 0,pagination:s,source:e.source!=null?wPi(e.source):void 0};!McI({context:r,request:e.request})&&Object.keys(f).length>0&&(l["path-parameters"]=f),e.summary!=null&&(l["display-name"]=e.summary);let m={},A=r.builder.getGlobalHeaderNames(),P=r.builder.getAuthHeaderName();P!=null&&A.add(P);let C=e.headers.filter(I=>!A.has(I.name));for(let I of C){let T=gVr({header:I,context:r,fileContainingReference:t,namespace:c});m[I.name]=T,a.add(typeof T=="string"?I.name:T.name??I.name)}if(e.request!=null){r.setInState(Cse.Request);let I=IcI({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(f).length>0?f:void 0,queryParameters:Object.keys(u).length>0?u:void 0,nonRequestReferencedSchemas:Array.from(n),headers:Object.keys(m).length>0?m:void 0,usedNames:a,namespace:c});l.request=I.value,i=[...i,...I.schemaIdsToExclude??[]],r.unsetInState(Cse.Request)}else{let I=r.inlinePathParameters&&Object.keys(f).length>0,T=Object.keys(u).length>0,z=Object.keys(m).length>0,U={};(I||T||z)&&(U.name=e.requestNameOverride??e.generatedRequestName),I&&(U["path-parameters"]=f),T&&(U["query-parameters"]=u),z&&(U.headers=m),Object.keys(U).length>0&&(l.request=U)}if(e.response!=null&&e.response._visit({json:I=>{let T=vC({schema:I.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l.response={docs:I.description??void 0,type:W4(T)},I.statusCode!=null&&(l.response["status-code"]=I.statusCode),I.responseProperty!=null&&(l.response.property=I.responseProperty)},streamingJson:I=>{let T=vC({schema:I.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:I.description??void 0,type:W4(T),format:"json"}},streamingSse:I=>{let T=vC({schema:I.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:I.description??void 0,type:W4(T),format:"sse"}},file:I=>{l.response={docs:I.description??void 0,type:"file","status-code":I.statusCode}},bytes:I=>{l.response={docs:I.description??void 0,type:"bytes","status-code":I.statusCode}},streamingText:I=>{l["response-stream"]={docs:I.description??void 0,type:"text"}},text:I=>{l.response={docs:I.description??void 0,type:"text","status-code":I.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let I=r.getDefaultServerName(),T=e.servers[0];T==null?I!=null&&(l.url=I):l.url=T.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=RJ(e.availability)),Object.entries(e.errors).forEach(([I,T])=>{let z=T.generatedName,U=Sw.of(mF);r.builder.enableUniqueErrorsPerEndpoint&&(z=`${e.generatedRequestName}${T.generatedName}`,T.schema!=null&&(T.schema.type!=="reference"&&T.schema.type!=="oneOf"?T.schema.generatedName=`${e.generatedRequestName}${T.schema.generatedName}`:T.schema.type==="oneOf"&&(T.schema.value.generatedName=`${e.generatedRequestName}${T.schema.value.generatedName}`)));let q={"status-code":parseInt(I)},V=nHy({location:THy,namespaceOverride:c});if(T.schema!=null){let Y=vC({schema:T.schema,context:r,fileContainingReference:V,declarationFile:V,namespace:c,declarationDepth:0});q.type=W4(Y),q.docs=T.description}r.builder.addError(V,{name:z,schema:r.isErrorUnknownSchema(parseInt(I))?{...q,type:"unknown"}:q}),l.errors==null&&(l.errors=[]);let $=r.builder.addImport({file:t,fileToImport:V});l.errors.push($!=null?`${$}.${z}`:z),q.type!=null&&T.examples?.forEach(Y=>{let k={value:gPe(Y.example),name:Y.name,docs:Y.description};r.builder.addErrorExample(V,{name:z,example:k})})}),e.examples.length>0&&(l.examples=DcI({endpointExamples:e.examples,context:r})),e.retries!=null&&(l.retries=CcI({retries:e.retries})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[PNf,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:i}}function DcI({endpointExamples:e,context:t}){return e.map(r=>{try{return CHy({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function CcI({retries:e}){if(e!=null)switch(e.type){case"disabled":return{disabled:e.value??void 0};default:ku(e)}}function IcI({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:a,pathParameters:o,queryParameters:c,nonRequestReferencedSchemas:f,headers:u,usedNames:s,namespace:l}){if(n.type==="json"||n.type==="formUrlEncoded"){let m=n.schema.type==="reference"?n.schema.schema:void 0,A=n.schema.type==="reference"?r.getSchema(n.schema.schema,l):n.schema;if(A?.type!=="object"||m!=null&&f.includes(m)){let z=vC({schema:n.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),U={schemaIdsToExclude:[],value:{body:z}},q=Object.keys(o??{}).length>0,V=Object.keys(c??{}).length>0,$=Object.keys(u??{}).length>0;return q&&(U.value["path-parameters"]=o),V&&(U.value["query-parameters"]=c),$&&(U.value.headers=u),(q||V||$)&&(U.value.name=i??a),n.contentType!=null&&(U.value["content-type"]=n.contentType),n.description!=null&&(U.value.docs=n.description),U}let P=Object.fromEntries(A.properties.filter(z=>z.readonly==null?!0:!(MHy(e.method)&&z.readonly)).map(z=>{let U=vC({schema:z.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:1}),q=z.nameOverride??z.key,V=RJ(z.availability);if(!s.has(q)&&z.audiences.length<=0)return s.add(q),z.nameOverride!=null?[z.key,{type:W4(U),docs:sno(U),name:z.nameOverride,availability:V}]:[z.key,V?{...typeof U=="string"?{type:U}:U,availability:V}:U];let $={type:W4(U),docs:sno(U)};return s.has(q)&&($.name=z.generatedName),z.audiences.length>0&&($.audiences=z.audiences),V!=null&&($.availability=V),s.add(q),[z.key,$]})),C=A.allOf.map(z=>{let U=vC({schema:p1.reference(z),fileContainingReference:t,context:r,namespace:l,declarationDepth:0});return W4(U)}).filter(z=>z!=="unknown"),I={properties:P};C.length>0&&(I.extends=C),n.additionalProperties&&(I["extra-properties"]=!0);let T={name:i??A.nameOverride??A.generatedName,"path-parameters":o,"query-parameters":c,headers:u,body:I};return n.contentType!=null&&(T["content-type"]=n.contentType),n.description!=null&&(T.docs=n.description),{schemaIdsToExclude:m!=null?[m]:[],value:T}}else if(n.type==="octetStream"){let m={body:"bytes","content-type":n.contentType??C8.APPLICATION_OCTET_STREAM,"query-parameters":c};return c!=null&&(m.name=i??a),n.description!=null&&(m.docs=n.description),{schemaIdsToExclude:[],value:m}}else if(n.type==="multipart"){let m=Object.fromEntries(n.properties.map(A=>{if(A.schema.type==="file"){let P=A.schema.isArray?"list<file>":"file";if(P=A.schema.isOptional?`optional<${P}>`:P,A.description!=null||A.contentType!=null){let C={type:P};if(A.description!=null&&(C.docs=A.description),A.contentType!=null){let I=A.contentType.split(",")[0];C["content-type"]=I}return[A.key,C]}return[A.key,P]}else{let P=vC({schema:A.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(A.contentType||A.exploded||A.encoding){let C=typeof P=="string"?{type:P}:P;A.contentType!=null&&(C["content-type"]=A.contentType),A.encoding==="form"?C.style="form":A.encoding==="json"?C.style="json":A.exploded&&(C.style="exploded"),P=C}return[A.key,P]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??a,"path-parameters":o,"query-parameters":c,headers:u,body:{properties:m},"content-type":C8.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else ku(n)}function McI({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:ku(t)}}function BcI({location:e,namespaceOverride:t}){return t!=null?{...e,file:RX(Sw.of(t),e.file)}:e}function TcI(e){let t=e.namespace,r=e.tags.filter(f=>f!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:Sw.of(`${$A(r)}.yml`),endpointId:e.summary!=null?$A(e.summary):$A(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Sw.of(mF),endpointId:$A(e.summary)}:{file:Sw.of(mF),endpointId:$A(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Sw.of(mF),endpointId:n};let i=uko(r),a=uko(n);if(tse(i,a))return{file:Sw.of("__package__.yml"),endpointId:r};let o=NcI({operationId:n,tag:r,path:e.path,method:e.method});if(o!=null)return o;let c=[];for(let f=0;f<i.length;++f){let u=i[f];if(u!=null&&u===a[f])c.push(u);else{let s=$A(r);return{file:Sw.of(`${s}.yml`),endpointId:n,tag:r}}}if(c.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Sw.of($A(c.join("_"))+".yml"),endpointId:$A(a.slice(c.length).join("_")),tag:r}}function cko(e){let t=e.tags[0];if(e.sdkName!=null){let r=oNf({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Sw.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return BcI({namespaceOverride:e.namespace,location:TcI(e)})}function uko(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=vdt(t),t}var qcI=new RegExp("[^a-zA-Z0-9{}]+"),RcI=new RegExp("[{}]","g");function NcI({operationId:e,tag:t,path:r,method:n}){let a=`${r.split(qcI).join("_").replaceAll(RcI,"_")}_${n.toLowerCase()}`;if(e.endsWith(a))return{file:Sw.of($A(t)+".yml"),endpointId:$A(e.slice(0,-1*a.length)),tag:t}}function qHy(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let a of r){let{endpointId:o,file:c,tag:f}=cko(a),u=c.split(".")[0];u!=null&&t.add(u);let s;if(a.sdkName!=null){let A=e.ir.groups;for(let P of a.sdkName.groupName){let C=typeof P=="string"?P:P.name,I=A[C];if(I==null)break;if(I.summary!=null||I.description!=null){s=A[C];break}}}let l=f==null?void 0:n.tagsById[f];e.setInState(Cse.Endpoint),e.setEndpointMethod(a.method);let m=BHy({context:e,endpoint:a,declarationFile:c});e.unsetEndpointMethod(),e.unsetInState(Cse.Endpoint),i=[...i,...m.schemaIdsToExclude],e.builder.addEndpoint(c,{name:o,schema:m.value,source:a.source!=null?wPi(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(c,{"display-name":s?.summary??l?.id,docs:s?.description??l?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}function RHy(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?jPi(r.groupName):void 0,i=vC({schema:p1.primitive(r),context:e,fileContainingReference:Sw.of(mF),namespace:n,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:W4(i),docs:r.description??void 0}})}}function NHy(e){for(let t of e.ir.webhooks){let r=zcI({webhook:t,context:e});if(r==null)continue;let n=H3u(t.sdkName,t.namespace),i={};for(let o of t.headers)i[o.name]=gVr({header:o,context:e,fileContainingReference:r.file,namespace:n});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:i,payload:vC({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0}),examples:t.examples!=null?t.examples.map(o=>({docs:o.description,name:o.name,payload:gPe(o.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function FcI({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:RX(Sw.of(t),e.file)}:e}function xcI({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:Sw.of(mF),endpointId:n};let i=uko(r),a=uko(n);if(tse(i,a))return{file:Sw.of("__package__.yml"),endpointId:r};let o=[];for(let c=0;c<i.length;++c){let f=i[c];if(f!=null&&f===a[c])o.push(f);else{let u=$A(r);return{file:Sw.of(`${u}.yml`),endpointId:n,tag:r}}}if(o.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Sw.of($A(o.join("_"))+".yml"),endpointId:$A(a.slice(o.length).join("_")),tag:r}}function zcI({webhook:e,context:t}){return e.sdkName!=null?{file:rHy({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:FcI({namespaceOverride:e.namespace,location:xcI({webhook:e,context:t})})}var QcI=Sw.of(mF);function xHy(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return FHy({namespace:e.namespace,groupName:e.groupName});case"oneOf":return FHy({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return QcI;default:ku(e)}}function FHy({namespace:e,groupName:t}){return e!=null&&t!=null?Z6i([{type:"namespace",name:e},...t]):e!=null?Z6i([{type:"namespace",name:e}]):Z6i(t)}var PNf="external",THy=Sw.of(mF);function zHy({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,a]of Object.entries(e)){if(t.includes(i))continue;let o=xHy(a),c=cHy({schema:a,context:n,declarationFile:o,namespace:r,declarationDepth:0});if(W3i(c.schema)){let f=W4(c.schema);if(f===(c.name??i)||f===`optional<${c.name??i}>`||f===`nullable<${c.name??i}>`||f===`optional<nullable<${c.name??i}>>`)continue}n.builder.addType(o,{name:c.name??i,schema:c.schema})}}function QHy(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),AHy(e),PHy(e),wHy(e),_Hy(e),RHy(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(PNf);let t=qHy(e),r=t.sdkGroups;e.setInState(Cse.Webhook),NHy(e),e.unsetInState(Cse.Webhook),e.setInState(Cse.Channel);for(let i of Object.values(e.ir.channels)){let a=Z6i(i.groupName);bHy({channel:i,context:e,declarationFile:a})}e.unsetInState(Cse.Channel);let n=LcI({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});zHy({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:n,namespace:void 0,context:e});for(let[i,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))zHy({schemas:a,schemaIdsToExclude:n,namespace:i,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 LcI({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let n=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),i=new Set(t);for(let a of n)r.includes(a)||i.add(a);return Array.from(i)}var lko=class{context;constructor(t){this.context=t}};var G3u=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[o,c]of Object.entries(n.files)){let f=i!=null?Sw.of(`${i}${"/"}${o}`):Sw.of(o);t[f]=c}let a=Object.keys(n.directories).sort();for(let o of a){let c=i!=null?`${i}${"/"}${o}`:o,f=n.directories[o];r(f,c)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Sw.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}};var Gla=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new G3u,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:a}){let o=this.getOrCreateFile(t);o.service==null&&(o.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(o.service.auth=r),n!=null&&(o.service["base-path"]=n),i!=null&&(o.service["display-name"]=i),a!=null&&(o.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 jLr(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 n of Object.values(this.rootApiFile["auth-schemes"]))LHy(n)&&t.push(n.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(LHy(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}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:n}){if(t===r)return;let i=n??$A((Bdt(r)+"/"+Dia(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Sw.of(Qk))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=fau(Bdt(QHa.of(`/${t}`)),QHa.of(`/${r}`)),i;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[i]=fau(Bdt(QHa.of(`/${t}`)),QHa.of(`/${r}`)),i}addType(t,{name:r,schema:n}){if(t===Sw.of(Qk))return;let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let a=i.types[r];a!=null&&(typeof a=="string"?i.types[r]={type:a,examples:[n]}:(a.examples==null&&(a.examples=[]),a.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let a=i.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(c=>tse(c,n))??!1)||a.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(a.service.source=i),a.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=RX(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([i,a])=>[i,{...a,path:RX(r,a.path)}]))});for(let i of Object.values(t))i.service!=null&&(i.service={...i.service,endpoints:Object.fromEntries(Object.entries(i.service.endpoints).map(([a,o])=>[a,{...o,path:RX(r,o.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===mF?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 LHy(e){return e?.header!=null}var J3u=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;wrapReferencesToNullableInOptional;coerceOptionalSchemasToNullable;groupEnvironmentsByHost;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;urlIdMap=new Map;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:n,environmentOverrides:i,globalHeaderOverrides:a,authOverrides:o}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=i,this.authOverrides=o,this.globalHeaderOverrides=a,this.detectGlobalHeaders=n?.detectGlobalHeaders??!0,this.objectQueryParameters=n?.objectQueryParameters??!1,this.respectReadonlySchemas=n?.respectReadonlySchemas??!1,this.respectNullableSchemas=n?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=n?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=n?.inlinePathParameters??!1,this.useBytesForBinaryResponse=n?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=n?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=n?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=n?.enableUniqueErrorsPerEndpoint??!1,this.wrapReferencesToNullableInOptional=n?.wrapReferencesToNullableInOptional??!0,this.coerceOptionalSchemasToNullable=n?.coerceOptionalSchemasToNullable??!0,this.groupEnvironmentsByHost=n?.groupEnvironmentsByHost??!1,this.builder=new Gla(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let c={};if(!this.enableUniqueErrorsPerEndpoint)for(let f of r.endpoints)for(let[u,s]of Object.entries(f.errors)){let l=parseInt(u),m=c[l];m==null&&s.schema!=null?c[l]=s.schema:m!=null&&s.schema!=null&&Axe(m,s.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}setUrlId(t,r){this.urlIdMap.set(t,r)}getUrlId(t){return this.urlIdMap.get(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(Cse.Channel,Cse.Endpoint,Cse.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:ku(t)}}markObjectSchemaAsReferenced(t,r){for(let n of t.allOf)this.markSchemaIdAsReferenced(n.schema,r);for(let n of t.properties)this.markSchemaAsReferenced(n.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let n of Object.values(t.schemas))this.markSchemaAsReferenced(n,r);return;case"undiscriminated":for(let n of t.schemas)this.markSchemaAsReferenced(n,r);return;default:ku(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let n=this.getSchema(t,r);n!=null&&this.markSchemaAsReferenced(n,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function wNf(e){let t=new J3u(e);return QHy(t)}var K3u=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:n,absoluteFilePath:i}){let a=wNf({taskContext:t,ir:r,options:ZZo({overrides:{...n,respectReadonlySchemas:n?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:n?.respectNullableSchemas??this.args.respectNullableSchemas,wrapReferencesToNullableInOptional:n?.wrapReferencesToNullableInOptional??this.args.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:n?.coerceOptionalSchemasToNullable??this.args.coerceOptionalSchemasToNullable,onlyIncludeReferencedSchemas:n?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:n?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:n?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:n?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:n?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums,groupEnvironmentsByHost:n?.groupEnvironmentsByHost??this.args.groupEnvironmentsByHost}}),authOverrides:n?.auth!=null?{auth:n.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:i??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:jg.dump(a.rootApiFile)},namedDefinitionFiles:{...Bg(a.definitionFiles,o=>({absoluteFilepath:i??this.args.absoluteFilePath,rawContents:jg.dump(o),contents:o})),[Sw.of(mF)]:{absoluteFilepath:i??this.args.absoluteFilePath,rawContents:jg.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var fko=class extends lqr{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;wrapReferencesToNullableInOptional;coerceOptionalSchemasToNullable;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;inlineAllOfSchemas;resolveAliases;groupEnvironmentsByHost;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.wrapReferencesToNullableInOptional=t.wrapReferencesToNullableInOptional,this.coerceOptionalSchemasToNullable=t.coerceOptionalSchemasToNullable,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.inlineAllOfSchemas=t.inlineAllOfSchemas,this.resolveAliases=t.resolveAliases,this.groupEnvironmentsByHost=t.groupEnvironmentsByHost,this.converter=new K3u(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:n},i){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:n},i);return this.converter.convert({context:t,ir:a,settings:i,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let n=await this.getDefinition({context:t},r);return new int({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion})}};var Xve={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 uno={of(e){return e}};var UHy={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},jNf={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:UHy,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},vb={SOURCE:uno.of("source"),SDK_NAMESPACE:uno.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:uno.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:uno.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:uno.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",RETRIES:"x-fern-retries",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 uU={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,resolveAliases:!1,groupMultiApiEnvironments:!1,groupEnvironmentsByHost:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0};function yht({options:e,overrides:t}){return{disableExamples:t?.disableExamples??uU.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??uU.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??uU.useTitlesAsName,audiences:t?.audiences??e?.audiences??uU.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??uU.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??uU.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??uU.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??uU.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??uU.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??uU.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??uU.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??uU.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??uU.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??uU.objectQueryParameters,filter:t?.filter??e?.filter??uU.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??uU.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??uU.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??uU.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??uU.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??uU.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??uU.preserveSingleSchemaOneOf,inlineAllOfSchemas:t?.inlineAllOfSchemas??e?.inlineAllOfSchemas??uU.inlineAllOfSchemas,resolveAliases:t?.resolveAliases??e?.resolveAliases??uU.resolveAliases,groupMultiApiEnvironments:t?.groupMultiApiEnvironments??e?.groupMultiApiEnvironments??uU.groupMultiApiEnvironments,groupEnvironmentsByHost:t?.groupEnvironmentsByHost??e?.groupEnvironmentsByHost??uU.groupEnvironmentsByHost,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??uU.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??uU.coerceOptionalSchemasToNullable}}var VHy={naming:"v1"};function av(e,t){let r=Array.isArray(t)?t:[t];for(let n of r){let i=e[n];if(i!=null)return i}}function dko(e,t,r,n,i=[]){try{let a=av(e,t);if(a!=null)return r.parse(a)}catch{let o=vdt(i).join(" -> ");n.error(`${o.length>0?`${o}: `:""}Failed to parse ${t}`)}}function Jla(e){let t=av(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 WHy({schema:e,logger:t}){return av(e,vb.ENCODING)??void 0}function HHy(e){return av(e,vb.FERN_ENUM)}function GHy({nameOverride:e,generatedName:t,title:r,schema:n,description:i,availability:a}){let o=av(n,vb.SDK_NAMESPACE),c=av(n,vb.SDK_GROUP_NAME),f=av(n,vb.TYPE_DEFINITION);if(f!=null)return pko({fernType:f,nameOverride:e,generatedName:t,title:r,description:i,availability:a,namespace:o,groupName:typeof c=="string"?[c]:c})}function pko({fernType:e,nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c}){return ree({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>{switch(f.v1){case"BASE_64":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.base64({example:void 0})});case"BOOLEAN":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.boolean({default:void 0,example:void 0})});case"DATE":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.date({example:void 0})});case"DATE_TIME":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.datetime({example:void 0})});case"FLOAT":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.float({example:void 0})});case"DOUBLE":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.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 Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.uint({default:void 0,example:void 0})});case"INTEGER":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.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 Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.uint64({default:void 0,example:void 0})});case"LONG":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Bh.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:tm.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:ku(f.v1)}},unknown:()=>Bh.unknown({nameOverride:t,generatedName:r,title:n,example:void 0,description:i,availability:a,namespace:o,groupName:c}),map:({keyType:f,valueType:u})=>f?.type==="primitive"&&u!=null?Bh.map({nameOverride:t,generatedName:r,title:n,key:f,value:u,description:i,availability:a,namespace:o,groupName:c,encoding:void 0,example:void 0,inline:void 0}):void 0,list:f=>f!=null?Bh.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,namespace:o,groupName:c,example:void 0,inline:void 0}):void 0,optional:f=>f!=null?Bh.optional({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,namespace:o,groupName:c,inline:void 0}):void 0,nullable:f=>f!=null?Bh.nullable({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,namespace:o,groupName:c,inline:void 0}):void 0,set:f=>f!=null?Bh.array({nameOverride:t,generatedName:r,title:n,value:f,description:i,availability:a,namespace:o,groupName:c,example:void 0,inline:void 0}):void 0,literal:f=>Bh.literal({nameOverride:t,generatedName:r,title:n,value:f._visit({string:u=>IV.string(u),boolean:u=>IV.boolean(u),_other:()=>{throw new Error("Unexpected literal type")}}),description:i,availability:a,namespace:o,groupName:c}),named:f=>Bh.reference({schema:f,nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,source:vPe.openapi({file:"<memory>"})})}})}function JHy(e){let t=av(e,vb.SOURCE);if(t!=null)return t.endsWith(".proto")?vPe.protobuf({file:t}):vPe.openapi({file:t})}function Kla(e){if(e!=null&&typeof e=="boolean")return e}function n0(e){return e?.$ref!=null}function KHy({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,additionalProperties:i,description:a,availability:o,wrapAsOptional:c,wrapAsNullable:f,context:u,namespace:s,groupName:l,example:m,encoding:A,source:P}){return i===void 0&&(i=u.options.additionalPropertiesDefaultsTo),ENf({nameOverride:e,generatedName:t,title:r,wrapAsOptional:c,wrapAsNullable:f,description:a,availability:o,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:tm.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:typeof i=="boolean"||_ko(i,u.options)?Bh.unknown({...UcI(i),generatedName:`${t}Value`}):$Hy(RS(i,!1,u.options.optionalAdditionalProperties?f:!1,u,[...n,"Value"],P,s,void 0,void 0,void 0)),namespace:s,groupName:l,example:m,encoding:A})}function $Hy(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=$Hy(e.value);break;case"oneOf":e.value.inline=!0;break;default:ku(e)}return e}function ENf({nameOverride:e,generatedName:t,title:r,keySchema:n,valueSchema:i,wrapAsOptional:a,wrapAsNullable:o,description:c,availability:f,namespace:u,groupName:s,example:l,encoding:m}){let A=Bh.map({nameOverride:e,generatedName:t,title:r,description:c,availability:f,key:n,value:i,namespace:u,groupName:s,encoding:m,example:l,inline:void 0});return o&&(A=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:A,description:c,availability:f,namespace:u,groupName:s,inline:void 0})),a&&(A=Bh.optional({nameOverride:e,generatedName:t,title:r,value:A,description:c,availability:f,namespace:u,groupName:s,inline:void 0})),A}function _ko(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!(n0(e)||"type"in e&&e.type!=null||"oneOf"in e&&e.oneOf!=null||"anyOf"in e&&e.anyOf!=null||"allOf"in e&&e.allOf!=null||"enum"in e&&e.enum!=null)}function UcI(e){let t={nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0};return e==null||typeof e=="boolean"||n0(e)||typeof e!="object"||(e.title!=null&&(t.title=e.title),e.description!=null&&(t.description=e.description)),t}function YHy({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,item:i,description:a,availability:o,wrapAsOptional:c,wrapAsNullable:f,context:u,namespace:s,groupName:l,example:m,source:A}){let P=i==null?Bh.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:l}):RS(i,!1,!1,u,[...n,"Item"],A,s);return VcI({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:l,itemSchema:P,wrapAsOptional:c,wrapAsNullable:f,description:a,availability:o,example:m})}function VcI({nameOverride:e,generatedName:t,title:r,itemSchema:n,wrapAsOptional:i,wrapAsNullable:a,description:o,availability:c,namespace:f,groupName:u,example:s}){let l=Bh.array({nameOverride:e,generatedName:t,title:r,value:n,description:o,availability:c,namespace:f,groupName:u,example:s,inline:void 0});return a&&(l=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:l,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),i&&(l=Bh.optional({nameOverride:e,generatedName:t,title:r,value:l,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),l}function mPe(e){switch(av(e,vb.AVAILABILITY)){case"deprecated":return ide.Deprecated;case"beta":return ide.Beta;case"generally-available":return ide.GenerallyAvailable;default:break}if(!n0(e)&&e.deprecated)return ide.Deprecated}function SNf({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:o,required:c,wrapAsOptional:f,wrapAsNullable:u,discriminator:s,context:l,namespace:m,groupName:A,encoding:P,source:C}){let I=s.propertyName,T=Object.fromEntries(Object.entries(s.mapping??{}).map(([U,q])=>{let V=EPi({$ref:q},!1,!1,l,[q],P,C,m);return l.markReferencedByDiscriminatedUnion({$ref:q},I,1),[U,V]})),z=Object.entries(i).filter(([U])=>U!==I).map(([U,q])=>{let V=c!=null&&c.includes(U),[$,re]=l.options.coerceOptionalSchemasToNullable?[!1,!V]:[!V,!1],Y=RS(q,$,re,l,[...n,U],C,m);return{key:U,schema:Y}});return XHy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:f,wrapAsNullable:u,properties:z,description:a,availability:o,discriminant:I,subtypes:T,namespace:m,groupName:A,source:C})}function DNf({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,availability:o,required:c,wrapAsOptional:f,wrapAsNullable:u,discriminant:s,variants:l,context:m,namespace:A,groupName:P,encoding:C,source:I}){let T=Object.fromEntries(Object.entries(l).map(([U,q])=>{if(n0(q)){let V=EPi(q,!1,!1,m,[q.$ref],C,I,A);return m.markReferencedByDiscriminatedUnion(q,s,1),[U,V]}else{let V=cno(q,!1,!1,m,[...n,U],C,I,A,new Set([s]));return[U,V]}})),z=Object.entries(i).filter(([U])=>U!==s).map(([U,q])=>{let V=c!=null&&c.includes(U),[$,re]=m.options.coerceOptionalSchemasToNullable?[!1,!V]:[!V,!1],Y=RS(q,$,re,m,[...n,U],I,A);return{key:U,schema:Y}});return XHy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:f,wrapAsNullable:u,properties:z,description:a,availability:o,discriminant:s,subtypes:T,namespace:A,groupName:P,source:I})}function XHy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:n,wrapAsNullable:i,properties:a,description:o,availability:c,discriminant:f,subtypes:u,namespace:s,groupName:l,source:m}){let A=Bh.oneOf(ont.discriminated({description:o,availability:c,discriminantProperty:f,nameOverride:e,generatedName:t,title:r,schemas:u,commonProperties:a,namespace:s,groupName:l,encoding:void 0,source:m,inline:void 0}));return i&&(A=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:A,namespace:s,groupName:l,description:o,availability:c,inline:void 0})),n&&(A=Bh.optional({nameOverride:e,generatedName:t,title:r,value:A,namespace:s,groupName:l,description:o,availability:c,inline:void 0})),A}function ZHy(e){if(e.proto!=null)return Sro.protobuf({typeName:e.proto.type})}function e7i({nameOverride:e,generatedName:t,title:r,fernEnum:n,enumVarNames:i,enumValues:a,_default:o,description:c,availability:f,wrapAsOptional:u,wrapAsNullable:s,namespace:l,groupName:m,context:A,source:P,inline:C}){let I=HcI(i??[]),T=new Set(a),z=Array.from(T).map((q,V)=>{let $=n?.[q],re=I[V],Y=ino.test(q),k=$?.name??re,ne=Y?q:ano(q);return k!=null&&!ino.test(k)&&(A?.logger.warn(`Enum name override ${k} is not a valid name. Falling back on ${ne}.`),k=void 0),{nameOverride:k,generatedName:ne,value:q,description:$?.description,availability:f,casing:{snake:$?.casing?.snake??void 0,pascal:$?.casing?.pascal??void 0,screamingSnake:$?.casing?.screamingSnake??void 0,camel:$?.casing?.camel??void 0}}}),U=o!=null?z.find(q=>q.value===o):void 0;return WcI({wrapAsOptional:u,wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:z,_default:U,description:c,availability:f,namespace:l,groupName:m,source:P,inline:C})}function WcI({wrapAsOptional:e,wrapAsNullable:t,nameOverride:r,generatedName:n,title:i,values:a,_default:o,description:c,availability:f,namespace:u,groupName:s,source:l,inline:m}){let A=Bh.enum({nameOverride:r,generatedName:n,title:i,values:a,description:c,availability:f,default:o,example:void 0,namespace:u,groupName:s,source:l,inline:m});return t&&(A=Bh.nullable({nameOverride:r,generatedName:n,title:i,value:A,description:c,availability:f,namespace:u,groupName:s,inline:m})),e&&(A=Bh.optional({nameOverride:r,generatedName:n,title:i,value:A,description:c,availability:f,namespace:u,groupName:s,inline:m})),A}function HcI(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(n=>n[r]===t[r]);)r++;return e.map(n=>n.substring(r))}function kHy({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:f,multipleOf:u,description:s,availability:l,wrapAsOptional:m,wrapAsNullable:A,example:P,namespace:C,groupName:I}){return n==="int64"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.int64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="uint32"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.uint({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="uint64"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.uint64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.int({default:i,minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:f,multipleOf:u,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I})}function GcI(e){return typeof e=="string"?IV.string(e):typeof e=="boolean"?IV.boolean(e):IV.string(`${e}`)}function eGy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:n,wrapAsNullable:i,value:a,description:o,availability:c,namespace:f,groupName:u}){let s=Bh.literal({nameOverride:e,generatedName:t,title:r,value:GcI(a),description:o,availability:c,namespace:f,groupName:u});return i&&(s=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:s,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),n&&(s=Bh.optional({nameOverride:e,generatedName:t,title:r,value:s,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),s}function CNf({nameOverride:e,generatedName:t,title:r,format:n,_default:i,minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:f,multipleOf:u,description:s,availability:l,wrapAsOptional:m,wrapAsNullable:A,example:P,namespace:C,groupName:I}){return n==null||n==="double"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.double({default:i,minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:f,multipleOf:u,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="float"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="int32"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.int({default:i,minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:f,multipleOf:u,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="int64"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.int64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="uint32"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.uint({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="uint64"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.uint64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):n==="time-delta"?Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I}):Ise({nameOverride:e,generatedName:t,title:r,primitive:tm.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:I})}var JcI={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},KcI={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}}},$cI={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}}},YcI={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},XcI={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},ZcI={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},kcI={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},elI={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function hko(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],n=[JcI,KcI,$cI,YcI,XcI,ZcI,kcI,elI],i;do{i=t;for(let a of n)if(a.isApplicable(t)){let{refUnderProcessing:o,newBreadcrumbs:c}=a.applyStrategy(t);t=o,r=[...r,...c]}}while(t.join("")!==i.join(""));return r}function Xne(e,t){let n=e.map(i=>/^[^a-zA-Z0-9]+$/.test(i)?i:X9($A(i))).join("");return/^\d/.test(n)?iko(n)??n:n}function tGy(e){let t=e.join("_");return $A(t)}function Q6(e){switch(e.type){case"object":return p1.object({allOf:e.allOf,properties:e.properties.map(t=>rlI(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 p1.array({description:e.description,availability:e.availability,value:Q6(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return p1.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 p1.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 p1.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Q6(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return p1.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Q6(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return p1.primitive({description:e.description,availability:e.availability,schema:rGy(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return p1.map({description:e.description,availability:e.availability,key:p1.primitive({description:e.key.description,availability:e.key.availability,schema:rGy(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:Q6(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 p1.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 p1.oneOf(tlI(e.value));case"unknown":return p1.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:ku(e)}}function tlI(e){switch(e.type){case"discriminated":return _Vr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:Q6(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,Q6(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return _Vr.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>Q6(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:ku(e)}}function rGy(e){switch(e.type){case"string":return Rq.string(e);case"base64":return Rq.base64();case"boolean":return Rq.boolean(e);case"date":return Rq.date();case"datetime":return Rq.datetime();case"double":return Rq.double(e);case"float":return Rq.float();case"int":return Rq.int(e);case"int64":return Rq.int64(e);case"uint":return Rq.uint();case"uint64":return Rq.uint64();default:ku(e)}}function rlI(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:Q6(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function $3u(e,t){return Axe(Q6(e),Q6(t))}function nGy({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,properties:i,description:a,required:o,wrapAsOptional:c,wrapAsNullable:f,allOf:u,context:s,propertiesToExclude:l,namespace:m,groupName:A,fullExamples:P,additionalProperties:C,availability:I,source:T}){let z=[...o??[]],U={...iGy({properties:i,breadcrumbs:n,context:s})},q=[],V=[];for(let ne of u)if(!s.options.inlineAllOfSchemas&&n0(ne)){let Oe=s.resolveSchemaReference(ne);if(Oe.discriminator!=null&&Oe.discriminator.mapping!=null)continue;if(Oe.oneOf!=null||Oe.anyOf!=null){let me=Oe.oneOf??Oe.anyOf;if(me!=null){for(let ve of me){let Ce=n0(ve)?s.resolveSchemaReference(ve):ve,Be=RS(Ce,!1,!1,s.DUMMY,n,T,m);Be.type==="object"&&q.push(...Be.properties.map(Se=>Se.schema.type!=="optional"&&Se.schema.type!=="nullable"?{...Se,schema:Bh.optional({nameOverride:void 0,generatedName:"",title:void 0,value:Se.schema,description:void 0,availability:Se.availability,namespace:void 0,groupName:void 0,inline:void 0})}:Se))}continue}}let he=t7i(ne);if(he==null)continue;V.push({schemaId:he,convertedSchema:INf(ne,[he],T,s.options.preserveSchemaIds),properties:aGy({schema:ne,context:s,breadcrumbs:n,source:T,namespace:m})}),s.markSchemaAsReferencedByNonRequest(he)}else if(n0(ne)){let Oe=s.resolveSchemaReference(ne),he=RS(Oe,!1,!1,s,n,T,m);he.type==="object"&&q.push(...he.properties)}else{let Oe=ne.required??[];q=q.map(me=>(me.schema.type==="optional"||me.schema.type==="nullable")&&Oe.includes(me.key)?{...me,schema:me.schema.value}:me);let he=RS(ne,!1,!1,s,n,T,m);he.type==="object"&&q.push(...he.properties)}let $={};for(let ne of V)for(let[Oe,he]of Object.entries(ne.properties)){let me=$[Oe];me!=null?(me.schemaIds.push(ne.schemaId),me.schemas.some(Ce=>$3u(Ce,he))||me.schemas.push(he)):$[Oe]={schemaIds:[ne.schemaId],schemas:[he]}}let re=[];for(let[ne,Oe]of Object.entries($))Oe.schemaIds.length>1&&re.push({propertyKey:ne,allOfSchemaIds:Oe.schemaIds,conflictingTypeSignatures:Oe.schemas.length>1});let Y=Object.fromEntries(Object.entries(U).filter(([ne,Oe])=>!(!n0(Oe)&&Oe.type==="null"))),k=Object.entries(Y).map(([ne,Oe])=>{let he=av(Oe,vb.AUDIENCES)??[],me=mPe(Oe),ve=n0(Oe)?!1:Oe.readOnly,Ce=n0(Oe)?!1:Oe.writeOnly,Se=!(z.includes(ne)&&!ve),jt=av(Oe,vb.FERN_PROPERTY_NAME),bt=[...n,ne],ze=tGy(bt),Me=RS(Oe,Se,!1,s,bt,T,m),Zt={};for(let dt of V){let Ar=dt.properties[ne];Ar!=null&&!$3u(Me,Ar)?Zt[dt.schemaId]={differentSchema:!0}:Ar!=null&&(Zt[dt.schemaId]={differentSchema:!1})}return{key:ne,schema:Me,nameOverride:jt,audiences:he,conflict:Zt,generatedName:ze,availability:me,readonly:ve,writeonly:Ce}});return k.push(...q.map(ne=>{let Oe=ne.conflict;for(let he of V){let me=he.properties[ne.key];me!=null&&!$3u(ne.schema,me)?Oe[he.schemaId]={differentSchema:!0}:me!=null&&(Oe[he.schemaId]={differentSchema:!1})}return{...ne,conflict:Oe}})),nlI({nameOverride:e,generatedName:t,title:r,wrapAsOptional:c,wrapAsNullable:f,properties:k.filter(ne=>!l.has(ne.key)),description:a,allOf:V.map(ne=>ne.convertedSchema),allOfPropertyConflicts:re,namespace:m,groupName:A,fullExamples:P,additionalProperties:C,availability:I,source:T,context:s})}function nlI({nameOverride:e,generatedName:t,title:r,wrapAsOptional:n,wrapAsNullable:i,properties:a,description:o,allOf:c,allOfPropertyConflicts:f,namespace:u,groupName:s,fullExamples:l,additionalProperties:m,availability:A,source:P,context:C}){let I=Bh.object({description:o,properties:a,nameOverride:e,generatedName:t,title:r,allOf:c,allOfPropertyConflicts:f,namespace:u,groupName:s,fullExamples:l,additionalProperties:_ko(m,C.options),availability:A,source:P,inline:void 0});return i&&(I=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:I,description:o,availability:A,namespace:u,groupName:s,inline:void 0})),n&&(I=Bh.optional({nameOverride:e,generatedName:t,title:r,value:I,description:o,availability:A,namespace:u,groupName:s,inline:void 0})),I}function iGy({properties:e,breadcrumbs:t,context:r}){return Object.fromEntries(Object.entries(e).filter(([n,i])=>{let a=av(i,vb.IGNORE);return a&&r.logger.debug(`Property ${t.join(".")}.${n} is marked with x-fern-ignore. Skipping.`),!a}))}function aGy({schema:e,context:t,breadcrumbs:r,source:n,namespace:i}){let a={},[o,c]=n0(e)?[t.resolveSchemaReference(e),hko(e.$ref)]:[e,r];for(let f of o.allOf??[])a={...a,...aGy({schema:f,context:t,breadcrumbs:c,source:n,namespace:i})};for(let[f,u]of Object.entries(iGy({properties:o.properties??{},breadcrumbs:r,context:t}))){let s=RS(u,!1,!1,t,[...c,f],n,i);a[f]=s}return a}function r7i({nameOverride:e,generatedName:t,title:r,breadcrumbs:n,description:i,availability:a,wrapAsOptional:o,wrapAsNullable:c,context:f,subtypes:u,namespace:s,groupName:l,encoding:m,source:A,subtypePrefixOverrides:P}){let C=olI({schemas:u}),I=u.flatMap((z,U)=>{if(!n0(z)&&z.enum!=null&&f.options.coerceEnumsToLiterals&&z.type==="string")return z.enum.map(V=>Bh.literal({nameOverride:void 0,generatedName:Xne([t,V],f.options.preserveSchemaIds),title:void 0,value:IV.string(String(V)),namespace:s,groupName:void 0,description:void 0,availability:V.availability}));let q=C[U];if(P!=null){let V=P[U];V!=null&&"name"in V&&(q=V.name)}return[RS(z,!1,!1,f,[...n,q??`${U}`],A,s)]}),T=ilI(I);return alI({uniqueSubtypes:T,nameOverride:e,generatedName:t,title:r,wrapAsOptional:o,wrapAsNullable:c,description:i,availability:a,namespace:s,groupName:l,context:f,encoding:m,source:A})}function ilI(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r],i=!1;for(let a=r+1;a<e.length;++a){let o=e[a];if(n!=null&&o!=null&&Axe(n,o)){i=!0;break}}n!=null&&!i&&t.push(n)}return t}function alI({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:n,wrapAsOptional:i,wrapAsNullable:a,description:o,availability:c,namespace:f,groupName:u,context:s,encoding:l,source:m}){if(Object.entries(e).every(([P,C])=>C.type==="literal")){let P={},C=[];return Object.entries(e).forEach(([I,T])=>{T.type==="literal"&&T.value.type==="string"&&(C.push(T.value.value),T.description!=null&&(P[T.value.value]={description:T.description}))}),e7i({nameOverride:t,generatedName:r,title:n,wrapAsOptional:i,wrapAsNullable:a,description:o,availability:c,fernEnum:P,enumVarNames:void 0,enumValues:C,_default:void 0,namespace:f,groupName:u,context:s,source:m,inline:void 0})}if(e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf){let P=e[0];return a&&(P=Bh.nullable({nameOverride:t,generatedName:r,title:n,value:P,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),i&&(P=Bh.optional({nameOverride:t,generatedName:r,title:n,value:P,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),P}return oGy({nameOverride:t,generatedName:r,title:n,wrapAsOptional:i,wrapAsNullable:a,description:o,availability:c,subtypes:e,namespace:f,groupName:u,encoding:l,source:m})}function MNf({nameOverride:e,generatedName:t,title:r,description:n,availability:i,wrapAsOptional:a,wrapAsNullable:o,context:c,namespace:f,groupName:u,discriminator:s,encoding:l,source:m}){let A=Object.entries(s.mapping??{}).map(([I,T],z)=>{let U={$ref:T},q=EPi(U,!1,!1,c,[T],l,m,f);return c.markSchemaWithDiscriminantValue(U,s.propertyName,I),q.type==="object"&&(q.properties={[s.propertyName]:Bh.literal({nameOverride:void 0,generatedName:Xne([t,I],c.options.preserveSchemaIds),title:void 0,value:IV.string(I),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...q.properties.filter(V=>V.key!==s.propertyName)}),q}),P=[];for(let I=0;I<A.length;++I){let T=A[I],z=!1;for(let U=I+1;U<A.length;++U){let q=A[U];if(T!=null&&q!=null&&Axe(T,q)){z=!0;break}}T!=null&&!z&&P.push(T)}if(Object.entries(P).every(([I,T])=>T.type==="literal")){let I={},T=[];return Object.entries(P).forEach(([z,U])=>{U.type==="literal"&&U.value.type==="string"&&(T.push(U.value.value),U.description!=null&&(I[U.value.value]={description:U.description}))}),e7i({nameOverride:e,generatedName:t,title:r,wrapAsOptional:a,wrapAsNullable:o,description:n,availability:i,fernEnum:I,enumVarNames:void 0,enumValues:T,_default:void 0,namespace:f,groupName:u,context:c,source:m,inline:void 0})}return P.length===1&&P[0]!=null&&!c.options.preserveSingleSchemaOneOf?P[0]:oGy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:a,wrapAsNullable:o,description:n,availability:i,subtypes:P,namespace:f,groupName:u,encoding:l,source:m})}function olI({schemas:e}){let t={},r=0;for(let a of e){if(!n0(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let o=Object.keys(a.properties),c={},f=o;for(let[u,s]of Object.entries(t)){let l=weu(s,o);f=weu(f,s),c[u]=l}c[r]=f,t=c}}r++}let n=[],i=0;for(let a of e){let o=t[i];if(o!=null&&o.length>0){let c=o.sort();if(c[0]!=null){n.push(c[0]),++i;continue}}n0(a)?n.push(X6i(i)??`${i}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?n.push(""):n.push(X6i(i)??`${i}`),++i}return n}function oGy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:n,wrapAsNullable:i,description:a,availability:o,subtypes:c,namespace:f,groupName:u,encoding:s,source:l}){let m=Bh.oneOf(ont.undiscriminated({description:a,availability:o,nameOverride:e,generatedName:t,title:r,schemas:c,namespace:f,groupName:u,encoding:s,source:l,inline:void 0}));return i&&(m=Bh.nullable({nameOverride:e,generatedName:t,title:r,value:m,description:a,availability:o,namespace:f,groupName:u,inline:void 0})),n&&(m=Bh.optional({nameOverride:e,generatedName:t,title:r,value:m,description:a,availability:o,namespace:f,groupName:u,inline:void 0})),m}function lno(e){if(e.default!=null&&typeof e.default=="string")return e.default}function Y3u({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let n=Jla(e);for(let i of n??[])if(typeof i=="number")return i;if(r&&typeof r=="number")return r}function sGy({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let n=Jla(e);for(let i of n??[])if(typeof i=="boolean")return i;if(r&&typeof r=="boolean")return r}function mVr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let n=Jla(e);for(let i of n??[])if(typeof i=="string")return i;if(r&&typeof r=="string")return r}function uGy({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let n=Jla(e);for(let i of n??[])if(Array.isArray(i))return i;if(r&&Array.isArray(r))return r}var $la="#/components/schemas/";function fGy(e,t){let r=n0(e)?t.resolveSchemaReference(e):e;switch(r.type){case"boolean":case"number":case"string":case"integer":return!0;case"array":return fGy(r.items,t);case"object":return!1;case void 0:return!1;default:return t.logger.warn("Unhandled schema type. Will not inline this schema",JSON.stringify(r)),!1}}function slI(e,t,r){return r.options.resolveAliases?typeof r.options.resolveAliases=="object"&&r.options.resolveAliases.except?.includes(e)?!1:fGy(t,r):!1}function RS(e,t,r,n,i,a,o,c=!1,f=new Set,u){let s=JHy(e)??a,l=hlI({schema:e,logger:n.logger});if(n0(e)){let m=t7i(e);return m!=null?slI(m,e,n)?cno(n.resolveSchemaReference(e),t,r,n,hko(e.$ref),l,s,o,f,c,u):(c?n.markSchemaAsReferencedByRequest(m):n.markSchemaAsReferencedByNonRequest(m),EPi(e,t,r,n,i,l,s,o)):cno(n.resolveSchemaReference(e),t,r,n,hko(e.$ref),l,s,o,f,c,u)}return cno(e,t,r,n,i,l,s,o,f,c,u)}function EPi(e,t,r,n,i,a,o,c){let f=e.$ref.includes("properties")?cno(n.resolveSchemaReference(e),t,r,n,i,a,o,c,new Set):Bh.reference(INf(e,i,o,n.options.preserveSchemaIds));if(r===!1){let u=n.resolveSchemaReference(e);(u.nullable===!0||Array.isArray(u.type)&&u.type.length>=2&&u.type.includes("null"))&&(r=!0)}return r&&(f=Bh.nullable({title:void 0,nameOverride:void 0,generatedName:Xne(i,n.options.preserveSchemaIds),value:f,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0})),t&&(f=Bh.optional({title:void 0,nameOverride:void 0,generatedName:Xne(i,n.options.preserveSchemaIds),value:f,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0})),f}function ulI(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function cno(e,t,r,n,i,a,o,c,f=new Set,u=!1,s){typeof e=="string"&&(e={type:e});let l=av(e,vb.TYPE_NAME)??(n.options.useTitlesAsName?ulI(e.title):void 0),m=av(e,vb.SDK_GROUP_NAME)??av(e,Xve.TAGS)?.[0],A=(typeof m=="string"?[m]:m)??[];A=n.resolveGroupName(A);let P=Xne(i,n.options.preserveSchemaIds),C=e.title,I=e.description,T=mPe(e),z=[];e.example!=null&&z.push({name:void 0,value:e.example,description:void 0});let U=av(e,Xve.EXAMPLES);U!=null&&Object.keys(U).length>0&&z.push(...Object.entries(U).map(([$,re])=>({name:re?.summary??$,value:re.value,description:re.description})));let q=Jla(e);q!=null&&Object.keys(q).length>0&&z.push(...q.map($=>({name:void 0,value:$,description:void 0})));let V=GHy({schema:e,description:I,title:C,nameOverride:l,generatedName:P,availability:T});if(V!=null){let $=V;return r&&($=Bh.nullable({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:$})),t&&($=Bh.optional({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:$})),$}try{if(Array.isArray(e.type)){let Y=e.type.indexOf("null"),k=Y!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&k)e.type.splice(Y,1),e.type=e.type[0],e.nullable=!0;else if(k&&(e.type.splice(Y,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let ne=new Set([...e.oneOf,...e.type]);e.oneOf=[...ne]}}if(r=r||e.nullable===!0,"const"in e&&(e.enum=[e.const]),e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(e.enum=e.enum.filter(k=>k!==null),!k3u(e.enum))return Ise({nameOverride:l,generatedName:P,title:C,primitive:tm.string({default:lno(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:mVr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A,wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T});let Y=HHy(e);return n.options.coerceEnumsToLiterals&&e.enum.length===1&&e.enum[0]!=null&&Y==null?eGy({nameOverride:l,generatedName:P,title:C,wrapAsOptional:t,wrapAsNullable:r,value:e.enum[0],description:I,availability:T,namespace:c,groupName:A}):e7i({nameOverride:l,generatedName:P,title:C,fernEnum:Y,enumVarNames:av(e,[Xve.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,namespace:c,groupName:A,context:n,source:o,inline:void 0})}if(k3u(e.type)&&e.type.length>1){let Y=e.type.includes("null"),k=e.type.filter(ne=>ne!=="null").map(ne=>({type:ne,nullable:Y}));return r7i({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,subtypes:k,namespace:c,groupName:A,encoding:a,source:o})}if(e.type==="boolean"){let Y=av(e,vb.BOOLEAN_LITERAL);return Y!=null?cGy({nameOverride:l,generatedName:P,title:C,literal:IV.boolean(Y),wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T,namespace:c,groupName:A}):Ise({nameOverride:l,generatedName:P,title:C,primitive:tm.boolean({default:clI(e.default),example:sGy({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T,namespace:c,groupName:A})}if(e.type==="number")return CNf({nameOverride:l,generatedName:P,title:C,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Kla(e.exclusiveMinimum),exclusiveMaximum:Kla(e.exclusiveMaximum),multipleOf:e.multipleOf,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:Y3u({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="integer")return kHy({nameOverride:l,generatedName:P,title:C,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Kla(e.exclusiveMinimum),exclusiveMaximum:Kla(e.exclusiveMaximum),multipleOf:e.multipleOf,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:Y3u({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="float")return CNf({nameOverride:l,generatedName:P,title:C,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Kla(e.exclusiveMinimum),exclusiveMaximum:Kla(e.exclusiveMaximum),multipleOf:e.multipleOf,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:Y3u({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="string"){if(e.format==="date-time")return Ise({nameOverride:l,generatedName:P,title:C,primitive:tm.datetime({example:mVr({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T,namespace:c,groupName:A});if(e.format==="date"&&n.options.typeDatesAsStrings===!1)return Ise({nameOverride:l,generatedName:P,title:C,primitive:tm.date({example:mVr({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T,namespace:c,groupName:A});if(e.format==="json-string"){let k=Bh.unknown({nameOverride:l,generatedName:P,title:C,description:I,availability:T,namespace:c,groupName:A,example:void 0});return r&&(k=Bh.nullable({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:k})),t&&(k=Bh.optional({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:k})),k}let Y=pGy(e,"const");return Y!=null?cGy({nameOverride:l,generatedName:P,title:C,literal:IV.string(Y),wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T,namespace:c,groupName:A}):Ise({nameOverride:l,generatedName:P,title:C,primitive:tm.string({default:lno(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:mVr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A,wrapAsOptional:t,wrapAsNullable:r,description:I,availability:T})}if(e.type==="array")return YHy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,item:e.items,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,example:uGy({schema:e,logger:n.logger,fallback:s}),source:o});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&X3u(e))return KHy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,additionalProperties:e.additionalProperties,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,encoding:a,example:e.example,source:o});if(e.oneOf!=null&&e.oneOf.length>0&&av(e,vb.IS_DISCRIMINATED)===!1)return r7i({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,subtypes:e.oneOf,namespace:c,groupName:A,encoding:a,source:o});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return n.options.discriminatedUnionV2?MNf({nameOverride:l,generatedName:P,title:C,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,discriminator:e.discriminator,encoding:a,source:o}):SNf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,encoding:a,source:o});if(e.oneOf!=null&&e.oneOf.length>0){let Y=av(e,vb.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return n.options.discriminatedUnionV2||Y?MNf({nameOverride:l,generatedName:P,title:C,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,discriminator:e.discriminator,encoding:a,source:o}):SNf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,encoding:a,source:o});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(n.options.preserveSingleSchemaOneOf)return r7i({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,subtypes:e.oneOf.filter(ne=>n0(ne)||ne.type!=="null"),encoding:a,namespace:c,groupName:A,source:o});let k=RS(e.oneOf[0],t,r,n,i,o,c,u);return fno(k,I,c,A)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let he=e.oneOf[0],me=e.oneOf[1];if(!n0(he)&&he.type==="null")return RS(me,!1,!0,n,i,o,c);if(!n0(me)&&me.type==="null")return RS(he,!1,!0,n,i,o,c)}let k=dlI({schemas:e.oneOf});if(k!=null)return e7i({nameOverride:l,generatedName:P,title:C,fernEnum:void 0,enumVarNames:void 0,enumValues:k,_default:e.default,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,namespace:c,groupName:A,context:n,source:o,inline:void 0});let ne=lGy({schemas:e.oneOf,context:n});if(ne!=null&&!n.options.discriminatedUnionV2&&!Y)return DNf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},required:e.required,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,discriminant:ne.discriminant,variants:ne.schemas,context:n,namespace:c,groupName:A,encoding:a,source:o});let Oe=e.oneOf.filter(he=>!n0(he)&&he.type==="null").length>0;return r7i({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r||Oe,context:n,subtypes:e.oneOf.filter(he=>n0(he)||he.type!=="null"),encoding:a,namespace:c,groupName:A,source:o})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let ne=RS(e.anyOf[0],t,r,n,i,o,c,u);return fno(ne,I,c,A)}if(e.anyOf.length===2){let[ne,Oe]=e.anyOf;if(ne!=null&&Oe!=null){if(!n0(ne)&&ne.type==="null"){let he=RS(Oe,!1,!0,n,i,o,c);return fno(he,I,c,A)}else if(!n0(Oe)&&Oe.type==="null"){let he=RS(ne,!1,!0,n,i,o,c);return fno(he,I,c,A)}}}let Y=lGy({schemas:e.anyOf,context:n});if(Y!=null&&!n.options.discriminatedUnionV2)return DNf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},required:e.required,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,discriminant:Y.discriminant,variants:Y.schemas,context:n,namespace:c,groupName:A,encoding:a,source:o});let k=e.anyOf.filter(ne=>!n0(ne)&&ne.type==="null").length>0;return r7i({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r||k,context:n,subtypes:e.anyOf.filter(ne=>n0(ne)||ne.type!=="null"),encoding:a,namespace:c,groupName:A,source:o})}if(e.allOf!=null||e.properties!=null){let Y=[];for(let ne of e.allOf??[])(n0(ne)||Object.keys(ne).length>0)&&Y.push(ne);if((e.properties==null||X3u(e))&&Y.length===1&&Y[0]!=null){let ne=RS(Y[0],t,r,n,i,o,c,u);return fno(ne,I,c,A)}let k=Y.filter(ne=>{let Oe=Z3u(ne);return Oe||n.logger.debug(`Skipping non-object allOf element: ${JSON.stringify(ne)}`),Oe});if((e.properties==null||X3u(e))&&k.length===1&&k[0]!=null){let ne=RS(k[0],t,r,n,i,o,c,u);return fno(ne,I,c,A)}return nGy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},description:I,required:e.required,wrapAsOptional:t,wrapAsNullable:r,allOf:k,context:n,propertiesToExclude:f,namespace:c,groupName:A,fullExamples:z,additionalProperties:e.additionalProperties,availability:T,encoding:a,source:o})}if(e.type==="object"&&llI(e)&&flI(e)&&X3u(e))return ENf({nameOverride:l,generatedName:P,title:C,description:I,availability:T,wrapAsOptional:t,wrapAsNullable:r,keySchema:{nameOverride:void 0,generatedName:`${P}Key`,title:void 0,description:void 0,availability:void 0,schema:tm.string({default:lno(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:mVr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A},valueSchema:Bh.unknown({nameOverride:void 0,generatedName:`${P}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:c,groupName:A}),namespace:c,groupName:A,encoding:a,example:e.example});e.type!=null&&n.logger.warn(`Failed to parse an OpenAPI schema at the following location: ${i.join("->")}. Coercing to unknown.`);let $=e.example??e.default,re=Bh.unknown({nameOverride:l,generatedName:P,title:C,description:I,availability:T,namespace:c,groupName:A,example:$});return r&&(re=Bh.nullable({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:re})),t&&(re=Bh.optional({availability:T,namespace:c,groupName:A,description:I,generatedName:P,inline:void 0,nameOverride:l,title:C,value:re})),re}catch($){return n.logger.debug(`Error converting schema: ${$.message}
2677
- Location: ${i.join("-> ")}`),Bh.unknown({nameOverride:l,generatedName:P,title:C,description:I,availability:T,namespace:c,groupName:A,example:void 0})}}function clI(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 t7i(e){if(e.$ref.startsWith($la))return e.$ref.replace($la,"")}function INf(e,t,r,n){let i=av(e,vb.TYPE_NAME),a=Xne(t,n),o=e.description,c=mPe(e),f=t7i(e);if(f==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return p1.reference({generatedName:a,nameOverride:i,title:void 0,schema:f,description:o??void 0,availability:c,namespace:void 0,groupName:void 0,source:r})}function llI(e){return e.oneOf==null||e.oneOf.length===0}function flI(e){return e.allOf==null||e.allOf.length===0}function X3u(e){return e.properties==null||I8(e.properties)===0}function k3u(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function fno(e,t,r,n){return e.type==="reference"?Bh.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n}):e.type==="optional"?Bh.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0}):e.type==="nullable"?Bh.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0}):e}function Z3u(e){return n0(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Z3u(t)):e.oneOf!=null?e.oneOf.every(t=>Z3u(t)):e.anyOf!=null?e.anyOf.every(t=>Z3u(t)):!1}function cGy({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:a,availability:o,nameOverride:c,generatedName:f,title:u}){let s=Bh.literal({nameOverride:c,generatedName:f,title:u,value:e,namespace:n,groupName:i,description:a,availability:o});return r&&(s=Bh.nullable({nameOverride:c,generatedName:f,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),t&&(s=Bh.optional({nameOverride:c,generatedName:f,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),s}function Ise({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:a,availability:o,generatedName:c,nameOverride:f,title:u}){i=typeof i=="string"?[i]:i;let s=Bh.primitive({nameOverride:f,generatedName:c,title:u,schema:e,description:a,availability:o,namespace:n,groupName:i});return r&&(s=Bh.nullable({nameOverride:f,generatedName:c,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),t&&(s=Bh.optional({nameOverride:f,generatedName:c,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),s}function dlI({schemas:e}){let t=new Set;for(let r of e){if(n0(r))return;if(r.enum!=null&&k3u(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function lGy({schemas:e,context:t}){let r={};for(let n of e){let i=dGy({schema:n,context:t});for(let[a,o]of Object.entries(i)){let c=r[a];c!=null?c[o]=n:r[a]={[o]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length)return{discriminant:n,schemas:i}}function dGy({schema:e,context:t}){let r=n0(e)?t.resolveSchemaReference(e):e;return plI({schema:r,context:t})}function plI({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=dGy({schema:n,context:t});for(let[a,o]of Object.entries(i??{}))r[a]=o}return r}for(let[n,i]of Object.entries(e.properties??{})){let a=n0(i)?t.resolveSchemaReference(i):i;a.type==="string"&&a.enum!=null&&k3u(a.enum)&&_lI(a.enum).length===1&&a.enum[0]!=null&&(r[n]=a.enum[0]);let o=pGy(a,"const");a.type==="string"&&o!=null&&(r[n]=o),n==="type"&&a.example!=null&&(r[n]=a.example)}return r}function _lI(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 pGy(e,t){let r=e[t];if(r!=null)return r}function hlI({schema:e,logger:t}){let r=WHy({schema:e,logger:t});if(r!=null)return ZHy(r)}var dno=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith($la))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let n=t.$ref.substring($la.length).split("/"),i=this.document.components;if(i==null||i.schemas==null)throw new Error("Document does not have components.schemas.");let[a,o,c]=n;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let f=i.schemas[a];if(f==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(n0(f)&&(f=this.resolveSchemaReference(f)),o==="properties"&&c!=null){let u=f.properties?.[c];if(u==null)throw new Error(`Property "${c}" not found on "${a}". Full ref: ${t.$ref}`);n0(u)?f=this.resolveSchemaReference(u):f=u}return f}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}};var ezu=class extends dno{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",n=this.document.components;if(n==null||n.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let i=t.$ref.substring(r.length),a=n.messages[i];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function pno(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let n={};for(let[i,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[i]=a;continue}let o=a.namespace;n[o]??={},n[o][i]=a;continue}case"oneOf":case"unknown":r[i]=a;continue;default:ku(a)}return{rootSchemas:r,namespacedSchemas:n}}function n7i(e){if(typeof e=="string")return TS.primitive(zO.string(e));if(typeof e=="number")return Number.isInteger(e)?TS.primitive(zO.int(e)):TS.primitive(zO.double(e));if(typeof e=="boolean")return TS.primitive(zO.boolean(e));if(Array.isArray(e)){let t=e.map(r=>n7i(r));return t.length===0?void 0:TS.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=n7i(n);i!=null&&t.push({key:zO.string(r),value:i})}return TS.map(t)}}function yko(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function _Gy(e){if(e!=null&&Array.isArray(e))return e}var i7i=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,n){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=n}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:a,options:o,skipReadonly:c}){switch(n.type){case"enum":return typeof r=="string"&&hGy({schema:n,value:r})?TS.enum(r):n.values[0]!=null?TS.enum(n.values[0]?.value):void 0;case"literal":return TS.literal(n.value);case"nullable":{if(r==null&&!this.hasExample(n.value,0,a,o)&&this.exceedsMaxDepth(i,o))return TS.null({});let f=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:o,skipReadonly:c});return f??TS.null({})}case"optional":{if(r==null&&!this.hasExample(n.value,0,a,o)&&(o.ignoreOptionals||this.exceedsMaxDepth(i,o))||Object.is(r,null))return;let f=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:o,skipReadonly:c});return f!=null&&f.type==="array"&&f.value.length===0||f!=null&&f.type==="map"&&f.value.length===0||f!=null&&f.type==="object"&&Object.keys(f.properties).length===0?void 0:f}case"primitive":{let f=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:o});return TS.primitive(f)}case"reference":{let f=this.schemas[n.schema];if(f!=null&&!a.has(n.schema)){a.add(n.schema);let u=f?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),s=this.buildExampleHelper({example:r,schema:f,exampleId:t,visitedSchemaIds:a,depth:i,options:o,skipReadonly:u||this.context.options.respectReadonlySchemas?c:!1});return a.delete(n.schema),s}return}case"oneOf":switch(n.value.type){case"discriminated":{let f={},u={},s={},l=yko(r),m=l?.[n.value.discriminantProperty],A=n.value.schemas[m],P=[],C=this.getDiscriminatedUnionVariantSchema(n.value,l);C!=null&&P.push(C),P.push(...Object.entries(n.value.schemas));for(let I of P)if(m!=null&&A!=null&&A.type==="object"){u=this.getAllProperties(A),s=this.getAllRequiredProperties(A),f[n.value.discriminantProperty]=TS.primitive(zO.string(m));break}else{let T=this.buildExampleHelper({exampleId:t,schema:I[1],example:void 0,visitedSchemaIds:a,depth:i,options:o,skipReadonly:c});if(T!=null){this.mergeExampleWith(T,f),f[n.value.discriminantProperty]=TS.primitive(zO.string(I[0]));break}}for(let I of n.value.commonProperties){u[I.key]={schema:I.schema,readonly:!1};let T=this.getResolvedSchema(I.schema);T.type!=="optional"&&T.type!=="nullable"&&(s[I.key]=I.schema)}for(let[I,T]of Object.entries(u)){let z=I in s;if(z&&l?.[I]!=null){let U=this.buildExampleHelper({schema:T.schema,exampleId:t,example:l[I],visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});if(U!=null)f[I]=U;else return}else{let U=this.buildExampleHelper({exampleId:t,schema:T.schema,example:l?.[I],visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});if(U!=null)f[I]=U;else if(z)return}}return TS.oneOf(U6i.discriminated(f))}case"undiscriminated":{let f=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(f!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:f,visitedSchemaIds:a,depth:i,options:o,skipReadonly:c});break}}return;case"unknown":if(r!=null){let f=n7i(r);if(f!=null)return TS.unknown(f)}return o.ignoreOptionals||this.exceedsMaxDepth(i,o)?void 0:o.isParameter?TS.primitive(zO.string(o.name??"string")):TS.map([{key:zO.string("key"),value:TS.primitive(zO.string("value"))}]);case"array":{let f=_Gy(r),u=[];if(f!=null&&f.length>0)for(let s of f){let l=this.buildExampleHelper({exampleId:t,example:s,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&u.push(l)}else if(n.example!=null&&n.example.length>0)for(let s of n.example){let l=this.buildExampleHelper({exampleId:t,example:s,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&u.push(l)}else{let s=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});s!=null&&u.push(s)}return TS.array(u)}case"map":{let f=yko(r??n.example);if(f!=null&&Object.entries(f).length>0){let l=[];for(let[m,A]of Object.entries(f)){let P=this.buildExampleFromPrimitive({schema:n.key.schema,example:m,options:o}),C=this.buildExampleHelper({exampleId:t,example:A,schema:n.value,visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});C!=null&&l.push({key:P,value:C})}return TS.map(l)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return TS.map([{key:zO.string("key"),value:TS.unknown(TS.primitive(zO.string("value")))}]);let u=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...o,name:"key"}}),s=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:a,depth:i+1,options:{...o,name:"value"},skipReadonly:c});return s!=null&&s.type!=="null"?TS.map([{key:u,value:s}]):TS.map([])}case"object":{let f={},u=n.fullExamples?.find(A=>A.name===t)??n.fullExamples?.find(A=>A.name==null)??n.fullExamples?.[0],s=yko(r)??(u!=null?yko(u.value):{})??{},l=this.getAllProperties(n),m=this.getAllRequiredProperties(n);for(let[A,P]of Object.entries(l)){if(c&&P.readonly||P.schema._visit({optional:z=>typeof z.availability=="string"&&z.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 C=A in m,I=Object.keys(s).includes(A),T=this.buildExampleHelper({schema:P.schema,exampleId:t,example:s[A],visitedSchemaIds:a,depth:i+1,options:{...o,name:A},skipReadonly:c});if(C&&T!=null)f[A]=T;else{if(C)return;(I&&T!=null||!o.ignoreOptionals&&T!=null)&&(f[A]=T)}}if(n.additionalProperties){for(let[A,P]of Object.entries(s))if(!(A in f)){let C=this.buildExampleHelper({schema:Bh.unknown({example:P,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:P,visitedSchemaIds:a,depth:i+1,options:{...o,name:A},skipReadonly:c});C!=null&&(f[A]=C)}}return TS.object({properties:f})}default:ku(n)}}mergeExampleWith(t,r){t._visit({array:xc,enum:xc,literal:xc,map:n=>{for(let i of n){let a=i.key;a.type==="string"&&(r[a.value]=i.value)}},object:n=>{for(let[i,a]of Object.entries(n.properties))r[i]=a},oneOf:n=>{if(n.type==="discriminated")for(let[i,a]of Object.entries(n.value))r[i]=a;else this.mergeExampleWith(n.value,r)},primitive:xc,unknown:xc,null:xc,_other:xc})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,o)=>o.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return hGy({schema:t,value:r})?5:0;case"object":{if(!Iq(r))return 0;let n=this.getAllProperties(t),i=0;for(let[a,o]of Object.entries(n))r[a]!=null?(i++,i+=this.calcExampleHeuristic(o.schema,r[a])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!Iq(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,a)=>a-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let o of t.properties)if(this.hasExample(o.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!n.has(t.schema)){n.add(t.schema);let o=this.hasExample(a,r,n,i);return n.delete(t.schema),o}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,n,i));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(r[n.key]=n.schema)}for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?zO.string(t):r.example!=null?zO.string(r.example):zO.string(n.name??FP.STRING);case"base64":return t!=null&&typeof t=="string"?zO.base64(t):r.example!=null?zO.base64(r.example):zO.base64(FP.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?zO.boolean(t):r.example!=null?zO.boolean(r.example):zO.boolean(FP.BOOLEAN);case"date":return t!=null&&typeof t=="string"?zO.date(t):r.example!=null?zO.date(r.example):zO.date(FP.DATE);case"datetime":return t!=null&&typeof t=="string"?zO.datetime(t):r.example!=null?zO.datetime(r.example):zO.datetime(FP.DATE_TIME);case"double":return t!=null&&typeof t=="number"?zO.double(t):r.example!=null?zO.double(r.example):zO.double(FP.DOUBLE);case"float":return t!=null&&typeof t=="number"?zO.float(t):r.example!=null?zO.float(r.example):zO.float(FP.FLOAT);case"int":return t!=null&&typeof t=="number"?zO.int(t):r.example!=null?zO.int(r.example):zO.int(FP.INT);case"int64":return t!=null&&typeof t=="number"?zO.int64(t):r.example!=null?zO.int64(r.example):zO.int64(FP.INT64);case"uint":return t!=null&&typeof t=="number"?zO.uint(t):r.example!=null?zO.uint(r.example):zO.uint(FP.UINT);case"uint64":return t!=null&&typeof t=="number"?zO.uint64(t):r.example!=null?zO.uint64(r.example):zO.uint64(FP.UINT64);default:ku(r)}}};function hGy({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function pqr(e){switch(e.type){case"object":return Bh.object({allOf:e.allOf,properties:e.properties.map(t=>vlI(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 Bh.array({description:e.description,availability:e.availability,value:pqr(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 Bh.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 Bh.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 Bh.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:pqr(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Bh.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:pqr(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Bh.primitive({description:e.description,availability:e.availability,schema:yGy(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Bh.map({description:e.description,availability:e.availability,key:Bh.primitive({description:e.key.description,availability:e.key.availability,schema:yGy(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:pqr(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 Bh.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 Bh.oneOf(ylI(e.value));case"unknown":return Bh.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:ku(e)}}function ylI(e){switch(e.type){case"discriminated":return ont.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:pqr(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,pqr(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return ont.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>pqr(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:ku(e)}}function yGy(e){switch(e.type){case"string":return tm.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return tm.base64({example:void 0});case"boolean":return tm.boolean({default:e.default,example:void 0});case"date":return tm.date({example:void 0});case"datetime":return tm.datetime({example:void 0});case"double":return tm.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 tm.float({example:void 0});case"int":return tm.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 tm.int64({default:e.default,example:void 0});case"uint":return tm.uint({default:void 0,example:void 0});case"uint64":return tm.uint64({default:void 0,example:void 0});default:ku(e)}}function vlI(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:pqr(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function tzu(e){return e.type!=="optional"&&e.type!=="nullable"}function BNf(e){return e==="POST"||e==="PUT"||e==="PATCH"}function vko(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 rzu=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,n){this.schemas=t,this.context=r,this.globalHeaders=n,this.schemas=t,this.exampleTypeFactory=new i7i(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){let r=glI(t.request),n=mlI(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let m=this.exampleTypeFactory.buildExample({skipReadonly:BNf(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&i.push([void 0,m])}else for(let{name:m,value:A}of r.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:BNf(t.method),schema:r.schema,exampleId:m,example:A,options:{isParameter:!1,ignoreOptionals:!0}});P!=null&&i.push([m,P])}if(l&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(n!=null&&n.type==="present"){let l=this.isSchemaRequired(n.schema);if(n.examples.length===0){let m=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});m!=null&&(t.response?.type==="json"?a.push([void 0,dht.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,dht.withStreaming({sse:t.response?.type==="streamingSse",events:[m]})]))}else for(let{name:m,value:A}of n.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:m,example:A,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});P!=null&&(t.response?.type==="json"?a.push([m,dht.withoutStreaming(P)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,dht.withStreaming({sse:t.response?.type==="streamingSse",events:[P]})]))}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];for(let l of t.pathParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&o.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:A})}let c=[];for(let l of t.queryParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&c.push({name:l.name,value:A})}let f=[];for(let l of t.headers){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&f.push({name:l.name,value:A})}for(let l of this.globalHeaders){let m=l.schema!=null?pqr(l.schema):Bh.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:tm.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),A=this.exampleTypeFactory.buildExample({schema:m,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),A==null)return[];A!=null&&f.push({name:l.header,value:A})}let u=[];t.request!=null&&t.response!=null?u=blI(i,a):t.request!=null?u=i.map(([l,m])=>({id:l,request:m,response:void 0})):t.response!=null&&(u=a.map(([l,m])=>({id:l,request:void 0,response:m})));let s=t.examples.filter(l=>vko(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let m=l.value["code-samples"];if(m!=null)return this.convertCodeSamples(m)}return}else return l.codeSamples}).filter(l=>pj(l));return u.length===0?[fht.full({name:void 0,description:void 0,pathParameters:o,queryParameters:c,headers:f,request:void 0,response:void 0,codeSamples:s})]:u.map(({id:l,request:m,response:A})=>fht.full({name:l,description:void 0,pathParameters:o,queryParameters:c,headers:f,request:m,response:A,codeSamples:s}))}convertCodeSamples(t){return t.map(r=>"language"in r?dVr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):dVr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?ade.Csharp:r.sdk,code:r.code})).filter(pj)}isSchemaRequired(t){return tzu(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function blI(e,t){let r=[];if(e.length<=1){let[i,a]=e[0]??[];if(t.length===0)return r.push({id:i,request:a,response:void 0}),r;for(let[o,c]of t)r.push({id:o??i,request:a,response:c});return r}if(t.length<=1){let[i,a]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:a}),r;for(let[o,c]of e)r.push({id:o??i,request:c,response:a});return r}let n=new Set;for(let[i,a]of e){let o=t.find(([f])=>f==null)?.[1]??t[0]?.[1];if(i==null){if(o==null)continue;r.push({id:void 0,request:a,response:o});continue}let c=!1;for(let f=0;f<t.length;f++){let[u,s]=t[f];u==null||n.has(f)||i===u&&(r.push({id:i,request:a,response:s}),u!=null&&n.add(f),c=!0)}!c&&o!=null&&r.push({id:i,request:a,response:o})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[a,o]=t[i],c=e.find(([f])=>f==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:o})}return r}function glI(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:OlI(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function mlI(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 _qr(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return _qr(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return _qr(e.value.value);default:return!1}case"null":return!0;default:ku(e)}}function OlI(e){return Bh.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:pqr(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(pj),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 _no=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new i7i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:a}){let o=[];for(let c of r){let f=[];for(let l of n.queryParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});A!=null&&!_qr(A)&&(A=void 0),!(m&&A==null)&&A!=null&&f.push({name:l.name,value:A})}let u=[];for(let l of n.headers){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});A!=null&&!_qr(A)&&(A=void 0),!(m&&A==null)&&A!=null&&u.push({name:l.name,value:A})}let s=[];for(let l of c.messages){let m=t.getExampleMessageReference(l),A=t.resolveMessageReference({$ref:m}),P=n0(A.payload)?t.resolveSchemaReference(A.payload):A.payload,C=this.exampleTypeFactory.buildExample({schema:RS(P,!1,!1,t,[l.messageId],i,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});C!=null&&s.push({messageType:l.type,payload:C,description:void 0})}o.push({name:c.summary,queryParameters:f,headers:u,description:c.description,messages:s})}return o}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let o of t.queryParameters){let c=this.isSchemaRequired(o.schema),f=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!_qr(f)&&(f=void 0),c&&f==null)return;f!=null&&i.push({name:o.name,value:f})}let a=[];for(let o of t.headers){let c=this.isSchemaRequired(o.schema),f=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!_qr(f)&&(f=void 0),c&&f==null)return;f!=null&&a.push({name:o.name,value:f})}for(let o of r){let c=this.exampleTypeFactory.buildExample({schema:o.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&n.messages.push({messageType:o.type,payload:c,description:void 0})}return n}isSchemaRequired(t){return tzu(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 bCe={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 nzu(e){return av(e,bCe.FERN_EXAMPLES)??[]}function izu(e,t){return t.includes("://")?t:`${e}://${t}`}function azu(e){return e.startsWith("/")?e:"/"+e}function gGy({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let a={},o={};for(let[u,s]of Object.entries(i.components?.schemas??{})){let l=RS(s,!1,!1,e,[u],r,e.namespace);a[u]=l}let c=new _no(a,e),f={};for(let[u,s]of Object.entries(i.servers??{}))f[u]={name:u,url:izu(s.protocol,s.url)};for(let[u,s]of Object.entries(i.channels??{})){let l=av(s,bCe.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${u} is marked with x-fern-ignore. Skipping.`);continue}let m=[];if(s.parameters!=null)for(let[T,z]of Object.entries(s.parameters??{}))m.push({name:T,description:z.description,parameterNameOverride:void 0,schema:z.schema!=null?RS(z.schema,!1,!1,e,t,r,e.namespace):Bh.primitive({schema:tm.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:mPe(z),source:r});let A=[],P=[];if(s.bindings?.ws!=null){if(s.bindings.ws.headers!=null){let T=s.bindings.ws.headers.required??[];for(let[z,U]of Object.entries(s.bindings.ws.headers.properties??{})){if(n0(U)){let re=e.resolveSchemaReference(U);A.push({name:z,schema:EPi(U,!1,!1,e,t,void 0,r,e.namespace),description:re.description,parameterNameOverride:void 0,env:void 0,availability:mPe(re),source:r});continue}let q=T.includes(z),[V,$]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];A.push({name:z,schema:RS(U,V,$,e,[...t,z],r,e.namespace),description:U.description,parameterNameOverride:void 0,env:void 0,availability:mPe(U),source:r})}}if(s.bindings.ws.query!=null){let T=s.bindings.ws.query.required??[];for(let[z,U]of Object.entries(s.bindings.ws.query.properties??{})){if(n0(U)){let re=e.resolveSchemaReference(U);P.push({name:z,schema:EPi(U,!1,!1,e,t,void 0,r,e.namespace),description:re.description,parameterNameOverride:void 0,availability:mPe(re),source:r});continue}let q=T.includes(z),[V,$]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];P.push({name:z,schema:RS(U,V,$,e,[...t,z],r,e.namespace),description:U.description,parameterNameOverride:void 0,availability:mPe(U),source:r})}}}let C;s.publish!=null&&("oneOf"in s.publish.message?C=vGy({generatedName:s.publish.operationId??"PublishEvent",event:s.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):C=bGy({action:"Publish",channelPath:u,message:s.publish.message,context:e,source:r}));let I;if(s.subscribe!=null&&("oneOf"in s.subscribe.message?I=vGy({generatedName:s.subscribe.operationId??"SubscribeEvent",event:s.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):I=bGy({action:"Subscribe",channelPath:u,message:s.subscribe.message,context:e,source:r})),A.length>0||P.length>0||C!=null||I!=null){let T=nzu(s),z=[];if(T.length>0)z=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:T,handshake:{headers:A,queryParameters:P},source:r,namespace:e.namespace});else{let $=[];C!=null&&$.push({type:"publish",payload:C}),I!=null&&$.push({type:"subscribe",payload:I});let re=c.buildWebsocketSessionExample({handshake:{headers:A,queryParameters:P},messages:$});re!=null&&z.push(re)}let U=av(s,bCe.FERN_CHANNEL_ADDRESS),q=U??azu(u),V=[];C!=null&&V.push({origin:"client",name:"publish",body:Q6(C)}),I!=null&&V.push({origin:"server",name:"subscribe",body:Q6(I)}),o[u]={audiences:av(s,vb.AUDIENCES)??[],handshake:{headers:A.map($=>({...$,schema:Q6($.schema),env:$.env})),queryParameters:P.map($=>({...$,schema:Q6($.schema)})),pathParameters:m.map($=>({...$,parameterNameOverride:void 0,schema:Q6($.schema)}))},groupName:e.resolveGroupName([av(s,bCe.FERN_SDK_GROUP_NAME)??u]),messages:V,servers:(s.servers?.map($=>f[$])??Object.values(f)).filter($=>$!=null&&$.name!=null).map($=>({...$,name:$.name})),summary:av(s,bCe.FERN_DISPLAY_NAME),path:q,description:s.description,examples:z,source:r}}}return{groupedSchemas:pno(e.namespace,a),channels:o??void 0,servers:Object.values(f).map(u=>({...u,name:u.name})),basePath:av(i,bCe.BASE_PATH)}}function vGy({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:a,asyncApiOptions:o}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],f=[];for(let u of t.message.oneOf){let s,l={type:"notFound"};if(n0(u)){let m=r.resolveMessageReference(u);!n0(m.payload)&&o.naming==="v2"?(l=m.name?{type:"name",name:m.name}:l,s={...m.payload,title:m.name??m.payload.title,description:m.name??m.payload.description}):s=m.payload}else s=u;f.push(l),c.push(s)}return r7i({description:t.description??t.message.description,availability:mPe(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypePrefixOverrides:o.naming==="v2"?f:[]})}}function bGy({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let a=r.payload;return n0(r.payload)&&(a=n.resolveSchemaReference(r.payload)),RS(a,!1,!1,n,[t,e],i,n.namespace)}}var ozu=class extends dno{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 n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(n)){let f=t.$ref.split("/"),u=f[2],s=f[4];if(u==null||s==null||!this.document.channels?.[u])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${u}`);let m=this.document.channels[u].messages?.[s];if(m==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in m&&!r?this.resolveMessageReference(m):{name:s,...m}}let a=this.document.components;if(!t.$ref.startsWith(i)||!a?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let o=t.$ref.substring(i.length),c=a.messages[o];if(c==null)throw new Error(`${t.$ref} is undefined`);return{name:o,...c}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var mGy="#/channels/",OGy="#/servers/",TNf="$message.";function PGy({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let a={},o={},c={},f=[],u={};e.logger.debug("Parsing V3 AsyncAPI...");for(let[T,z]of Object.entries(i.components?.schemas??{}))a[T]=RS(z,!1,!1,e,[T],r,e.namespace);for(let[T,z]of Object.entries(i.channels??{}))if(o[T]||(o[T]={}),z.messages)for(let[U,q]of Object.entries(z.messages))if(c[U]||(c[U]=[]),e.isReferenceObject(q)){let V=e.resolveMessageReference(q);c[U].push({channelId:T,payload:V.payload})}else e.isMessageWithPayload(q)&&c[U].push({channelId:T,payload:q.payload});for(let[T,z]of Object.entries(c))if(z.length===1){let U=z[0],q=U.channelId;o[q]=o[q]||{},o[q][T]=RS(U.payload,!1,!1,e,[T],r,e.namespace)}else{f.push(T);for(let{channelId:U,payload:q}of z){let V=`${U}_${T}`;o[U]||(o[U]={}),o[U][V]=RS(q,!1,!1,e,[V],r,e.namespace)}}let s=Object.values(o).reduce((T,z)=>({...T,...z}),{}),l=new _no(s,e),m={};for(let[T,z]of Object.entries(i.servers??{}))m[T]={name:T,url:izu(z.protocol,z.host)};let A={};for(let[T,z]of Object.entries(i.operations??{})){if(av(z,bCe.IGNORE))continue;let U=AlI(z);if(A[U]||(A[U]={subscribe:[],publish:[],__parsedMessages:[]}),z.action==="receive")A[U].subscribe.push(...z.messages);else if(z.action==="send")A[U].publish.push(...z.messages);else throw new Error(`Operation ${T} has an invalid action: ${z.action}`)}for(let[T,z]of Object.entries(A)){let U=[];U.push(...AGy({messages:z.subscribe,channelPath:T,origin:"server",messageSchemas:o[T]??{},duplicatedMessageIds:f,context:e})),U.push(...AGy({messages:z.publish,channelPath:T,origin:"client",messageSchemas:o[T]??{},duplicatedMessageIds:f,context:e})),A[T]!=null&&(A[T].__parsedMessages=U)}for(let[T,z]of Object.entries(i.channels??{})){if(av(z,bCe.IGNORE))continue;let U=[],q=[],V=[];if(z.parameters!=null)for(let[$,re]of Object.entries(z.parameters)){let Y=e.isReferenceObject(re)?e.resolveParameterReference(re):re,{type:k,parameterKey:ne}=Y.location!=null?PlI(Y.location):{type:z.address?.includes(`={${$}}`)?"query":"path",parameterKey:$},Oe=av(Y,bCe.FERN_PARAMETER_OPTIONAL),he=X9($A(T))+X9($A($)),me={...Y,type:"string",title:he,example:Y.examples?.[0],default:Y.default,enum:Y.enum,required:void 0},ve=RS(me,!1,!1,e,[ne],r,e.namespace);Oe&&(ve=Bh.optional({value:ve,description:void 0,availability:void 0,generatedName:"",title:he,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let Ce={name:ne,description:Y.description,parameterNameOverride:void 0,schema:ve,variableReference:void 0,availability:mPe(re),source:r};k==="header"?U.push({...Ce,env:void 0}):k==="path"?q.push(Ce):(k==="payload"||k==="query")&&V.push(Ce)}if(U.length>0||V.length>0||A[T]!=null&&(A[T].publish!=null||A[T].subscribe!=null)){let $=nzu(z),re=A[T]?.__parsedMessages??[],Y=[];if($.length>0)Y=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:$,handshake:{headers:U,queryParameters:V},source:r,namespace:e.namespace});else{let he=[],{examplePublishMessage:me,exampleSubscribeMessage:ve}=jlI({messages:re,messageSchemas:o[T]??{}});me!=null&&he.push(me),ve!=null&&he.push(ve);let Ce=l.buildWebsocketSessionExample({handshake:{headers:U,queryParameters:V},messages:he});Ce!=null&&Y.push(Ce)}let k=av(z,bCe.FERN_SDK_GROUP_NAME),ne=(z.servers?.map(he=>wlI(m,he))??Object.values(m)).map(he=>({...he,name:he.name})),Oe=z.address?.split("?")[0]??azu(T);u[T]={audiences:av(z,vb.AUDIENCES)??[],handshake:{headers:U.map(he=>({...he,schema:Q6(he.schema),env:he.env})),queryParameters:V.map(he=>({...he,schema:Q6(he.schema)})),pathParameters:q.map(he=>({...he,parameterNameOverride:void 0,schema:Q6(he.schema)}))},groupName:e.resolveGroupName(typeof k=="string"?[k]:k??[T]),messages:re,summary:av(z,bCe.FERN_DISPLAY_NAME),servers:ne,path:Oe,description:z.description,examples:Y,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${T} as it does not qualify for inclusion (no headers, query params, or operations)`)}let P=pno(e.namespace,a),C=Object.values(m).map(T=>({...T,name:T.name})),I=av(i,bCe.BASE_PATH);return{groupedSchemas:P,channels:u,servers:C,basePath:I}}function AlI(e){if(!e.channel.$ref.startsWith(mGy))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(mGy.length)}function PlI(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(TNf))throw new Error(`Invalid location format: ${e}; expected ${TNf} prefix`);let n=t.substring(TNf.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,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 wlI(e,t){if(!t.$ref.startsWith(OGy))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(OGy.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function AGy({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:a}){let o=[];return e.forEach((c,f)=>{let s=a.resolveMessageReference(c,!0).name;i.includes(s)&&(s=`${t}_${s}`);let l=n[s];l!=null&&o.push({origin:r,name:s??`${r}Message${f+1}`,body:Q6(l)})}),o}function jlI({messages:e,messageSchemas:t}){let r=e.find(o=>o.origin==="client")?.name,n=e.find(o=>o.origin==="server")?.name,i=r!=null?t[r]:void 0,a=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:a!=null&&n!=null?{type:n,payload:a}:void 0}}function wGy({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:a}){let o=[];if(a!=null&&o.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?o.push(c.tags[0].name):i.naming!=="v2"&&o.push("websocket");let f=new ezu({document:c,taskContext:t,options:r,namespace:a});return gGy({context:f,breadcrumbs:o,source:n,asyncApiOptions:i,document:c})}else{let c=e,f=new ozu({document:c,taskContext:t,options:r,namespace:a});return PGy({context:f,breadcrumbs:o,source:n,asyncApiOptions:i,document:c})}}function jGy(e){return av(e,vb.ASYNC_CONFIG)}var EGy="$request.";function SGy(e){let t=av(e,vb.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:ElI(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function ElI(e){return e.startsWith(EGy)?e.slice(EGy.length):e}function DGy(e){let t=e;if(t.cursor!=null)return ant.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return ant.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 ant.custom({results:r.results})}throw new Error("Invalid pagination extension")}function CGy(e,t){let r=av(t,vb.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=av(e,vb.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:DGy(n)}return DGy(r)}}function IGy(e){let t=SlI(e),r={};return qNf({obj:t,occurrences:r,breadcrumbs:[]}),r}function qNf({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)qNf({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)qNf({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function SlI(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?bko(r.get):void 0,put:r?.put!=null?bko(r.put):void 0,post:r?.post!=null?bko(r.post):void 0,patch:r?.patch!=null?bko(r.patch):void 0,delete:r?.delete!=null?bko(r.delete):void 0}]))}}function bko(e){return{...e,requestBody:e.requestBody!=null?n0(e.requestBody)?e.requestBody:DlI(e.requestBody):void 0}}function DlI(e){let t,r;for(let n in e.content){let i=C8.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[C8.MULTIPART_FORM_DATA]:r}}:e}var szu=class{endpoints;parser=new Joa;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 n=[];for(let i of r){let a=this.parser.tryParse(i);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${a.method} ${a.path}`)}return n}};var MGy="#/components/parameters/",BGy="#/components/responses/",TGy="#/components/examples/",qGy="#/components/requestBodies/",RGy="#/components/securitySchemes/",hno=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=IGy(t),this.options=i,this.source=a,this.filter=new szu({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=o}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let a=parseInt(i,10);if(isNaN(a)||a<0||a>=n.length)return{"x-fern-type":"unknown"};n=n[a]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(n0(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(MGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(MGy.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(qGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(qGy.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(BGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(BGy.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(TGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(TGy.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(RGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(RGy.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}};var Yla=class extends hno{constructor({document:t,taskContext:r,options:n,source:i,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var ClI=nl.object({lang:nl.string(),label:nl.optional(nl.string()),source:nl.string()}),RNf=nl.array(ClI);var NGy={README_EXT:"x-readme"};function IlI(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Iq(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function FGy(e){let t=av(e,NGy.README_EXT);if(!Iq(t))return[];let r=t["code-samples"];if(!IlI(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function xGy(e,t,r){let i=(av(t,vb.EXAMPLES)??[]).filter(u=>{let s=FX.serialization.ExampleEndpointCallSchema.parse(u);return s.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),s.ok}),a=dko(t,Xve.REDOCLY_CODE_SAMPLES_KEBAB,RNf,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...dko(t,Xve.REDOCLY_CODE_SAMPLES_CAMEL,RNf,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&i.push({"code-samples":c.map(u=>({name:u.label??u.lang,language:u.lang,code:u.source,install:void 0,docs:void 0}))});let f=FGy(t);return f.length>0&&i.push({"code-samples":f}),i.map(fht.unknown)}function zGy(e){let t=av(e,vb.AVAILABILITY);if(t==="ga"||t==="generally-available")return ide.GenerallyAvailable;if(t==="beta"||t==="pre-release")return ide.Beta;if(t==="deprecated")return ide.Deprecated;if(e.deprecated)return ide.Deprecated}function QGy(e){let t=av(e,vb.RETRIES);if(t!=null&&t.disabled===!0)return BFu.RetriesConfiguration.disabled(t.disabled)}function uzu(e,t){return{url:MlI({url:e.url,variables:e.variables??{}}),description:e.description,name:BlI(e,t),audiences:av(e,vb.AUDIENCES)}}function MlI({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function BlI(e,t){let r=av(e,[vb.SERVER_NAME_V1,vb.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}function LGy(e){return av(e,vb.PARAMETER_NAME)}function UGy(e){return av(e,vb.SDK_VARIABLE)}function czu({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:a}){let o={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let f=av(c,vb.IGNORE);if(f!=null&&f){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let u=n0(c)?n.resolveParameterReference(c):c,s=u.required??!1,l=mPe(u),m=[...i,u.name],A=Xne(m,n.options.preserveSchemaIds),[P,C]=n.options.coerceOptionalSchemasToNullable?[!1,!s]:[!s,!1],I=u.schema!=null?RS(u.schema,P,C,n,m,a,n.namespace,!1,new Set,mVr({schema:u,logger:n.logger})):s?Bh.primitive({nameOverride:void 0,generatedName:A,title:void 0,schema:tm.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:mVr({schema:u,logger:n.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):Bh.optional({nameOverride:void 0,generatedName:A,title:void 0,value:Bh.primitive({nameOverride:void 0,generatedName:A,title:void 0,schema:tm.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:mVr({schema:u,logger:n.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(u.in==="header"&&u.schema!=null&&!n0(u.schema)&&u.schema.default!=null){let z=u.schema.default;typeof z=="string"&&z.length>0&&(I=Bh.literal({nameOverride:void 0,generatedName:A,title:void 0,value:IV.string(z),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let T={name:u.name,schema:I,description:u.description,parameterNameOverride:LGy(u),availability:l,source:a};u.in==="query"?o.queryParameters.push(T):u.in==="path"?o.pathParameters.push({...T,variableReference:UGy(u)}):u.in==="header"?!TlI.has(u.name.toLowerCase())&&!n.authHeaders.has(u.name)?o.headers.push({...T,env:void 0}):n.logger.debug(`Ignoring ${u.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${u.in} parameter, ${u.name}, in ${t.toUpperCase()} ${e}`)}return o}var TlI=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function VGy(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r,schema:i??{},examples:gko(n,t)}}}function qlI(e){return e.includes("json")||e==="*/*"}function NNf({content:e,context:t}){for(let[r,n]of Object.entries(e))if(lzu({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function lzu({mediaType:e,mediaTypeObject:t,context:r}){if(!qlI(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:gko(t,r)}}function fzu({content:e,context:t}){let r=NNf({content:e,context:t});if(!r)return;let[n,i]=r;return lzu({mediaType:n,mediaTypeObject:i,context:t})}function WGy(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:gko(n,t)}}}function gko(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=av(e,Xve.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,a])=>({name:a.summary??i,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,a])=>{let o=n0(a)?t.resolveExampleReference(a):a;return{name:o.summary??i,value:o.value,description:o.description}})),r}function RlI({content:e,context:t}){for(let[r,n]of Object.entries(e))if(GGy({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function GGy({mediaType:e,mediaTypeObject:t,context:r}){if(C8.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:gko(t,r)}}function NlI({content:e}){for(let[t,r]of Object.entries(e))if(JGy({mediaType:t,mediaTypeObject:r}))return[t,r]}function JGy({mediaType:e,mediaTypeObject:t}){if(C8.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function KGy({mediaType:e}){return C8.parse(e)?.isBinary()??!1}function FlI({content:e}){for(let[t,r]of Object.entries(e))if(KGy({mediaType:t}))return[t,r]}function xlI(e,t){let r=n0(e)?FNf(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!n0(i)&&i.type==="string"&&i.format==="binary")!=null}function pzu({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}){let c=FlI({content:e});if(c){let[m,A]=c;return OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o})}let f=NlI({content:e}),u=NNf({content:e,context:n}),s=zlI({json:u,multipart:f,document:r,visitor:{json:([m,A])=>OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}),multipart:([m,A])=>OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}),neither:()=>{}}});if(s)return s;let l=RlI({content:e,context:n});if(l){let[m,A]=l;return OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o})}}function zlI({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!i?.schema&&!a?.schema?n.neither():i?.schema&&a?.schema?i.schema&&xlI(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):a?.schema?n.multipart(t):n.neither()}function OVr({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:a,source:o,namespace:c}){let f=QlI({mediaTypeObject:t});if(KGy({mediaType:e}))return hCe.octetStream({description:r,source:o,sdkMethodName:f,contentType:e});let u=JGy({mediaType:e,mediaTypeObject:t}),s=u?.schema,l=u?.encoding;if(s){let P=n0(s)?FNf(s,n):{id:void 0,schema:s},C=RS(P.schema,!1,!1,i,a,o,c,!1),I=[];if(C.type==="object"){let T=new Set(P.schema.required??[]);for(let z of C.properties){let U=T.has(z.key),{isFile:q,isOptional:V,isArray:$,description:re}=dzu({schema:z.schema,isOptional:!U});if(q){let Y=HGy(z.key,l);I.push({key:z.key,schema:pVr.file({isOptional:V,isArray:$,description:re}),description:re,contentType:Y,exploded:!1,encoding:Y==null?i.options.defaultFormParameterEncoding:void 0})}else{let Y=HGy(z.key,l);I.push({key:z.key,schema:pVr.json(z.schema),description:void 0,contentType:Y,exploded:l?.[z.key]?.explode,encoding:Y==null?i.options.defaultFormParameterEncoding:UlI(Y)})}}}return hCe.multipart({name:n0(s)&&i.getNumberOfOccurrencesForRef(s)===1?P.id:void 0,description:P.schema.description,properties:I,source:o,sdkMethodName:f})}let m=lzu({mediaType:e,mediaTypeObject:t,context:i});if(m){let P=RS(m.schema,!1,!1,i,a,o,c,!0);return hCe.json({description:void 0,schema:P,contentType:m.contentType,fullExamples:m.examples,additionalProperties:!n0(m.schema)&&_ko(m.schema.additionalProperties,i.options),source:o,sdkMethodName:f})}let A=GGy({mediaType:e,mediaTypeObject:t,context:i});if(A!=null&&A.schema!=null){let P=RS(A.schema,!1,!1,i,a,o,c,!1);return hCe.formUrlEncoded({schema:P,description:r,contentType:A.contentType,source:o,fullExamples:A.examples,additionalProperties:!1,sdkMethodName:f})}}function QlI({mediaTypeObject:e}){return av(e,vb.SDK_METHOD_NAME)}var LlI={"application/json":"json"};function UlI(e){return e?LlI[e]:void 0}function FNf(e,t){if(!e.$ref.startsWith($la))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=t7i(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return n0(n)?FNf(n,t):{id:r,schema:n}}function dzu({schema:e,isOptional:t,isArray:r,description:n}){return WlI(e)?dzu({schema:e.value,isOptional:!0,isArray:r,description:e.description}):HlI(e)?dzu({schema:e.value,isOptional:t,isArray:r,description:e.description}):GlI(e)?dzu({schema:e.value,isOptional:t,isArray:!0,description:e.description}):VlI(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function VlI(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function WlI(e){return e.type==="optional"}function HlI(e){return e.type==="nullable"}function GlI(e){return e.type==="array"}function HGy(e,t){return t?.[e]?.contentType}var xNf={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"},$Gy=new Set(Object.values(xNf));var JlI=["200","201","202","204"];function XGy({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:a,source:o}){if(t==null)return{value:void 0,errors:{}};let c=KlI({responses:t,context:r,source:o,namespace:r.namespace}),f=!1,u;for(let s of i!=null?[i]:JlI){let l=t[s];l!=null&&(f=!0,u==null&&(u=YGy({operationContext:e,response:l,context:r,responseBreadcrumbs:n,streamFormat:a,source:o,namespace:r.namespace,statusCode:typeof s=="string"?parseInt(s):s})))}if(u==null&&!f&&t.default!=null&&(u=YGy({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:a,source:o,namespace:r.namespace})),u!=null)switch(u.type){case"json":return{value:u,errors:c};case"streamingJson":case"streamingSse":return{value:u,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:u,errors:c};default:ku(u)}return{value:void 0,errors:c}}function YGy({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:a,namespace:o,statusCode:c}){let f=n0(r)?n.resolveResponseReference(r):r;if(f.content!=null&&Object.entries(f.content).find(([m,A])=>{if(A.schema==null)return!1;let P=n0(A.schema)?n.resolveSchemaReference(A.schema):A.schema;return P.type==="string"&&P.format==="binary"}))return n.options.useBytesForBinaryResponse&&t==null?VL.bytes({description:f.description,source:a,statusCode:c}):VL.file({description:f.description,source:a,statusCode:c});let u=VGy(f.content??{},n);if(u!=null&&t!=null)switch(t){case"json":return VL.streamingJson({statusCode:c,description:f.description,responseProperty:av(e.operation,vb.RESPONSE_PROPERTY),fullExamples:u.examples,schema:RS(u.schema,!1,!1,n,i,a,o),source:a});case"sse":return VL.streamingSse({description:f.description,responseProperty:void 0,fullExamples:u.examples,schema:RS(u.schema,!1,!1,n,i,a,o),source:a,statusCode:c})}let s=fzu({context:n,content:f.content??{}});if(s){if(t!=null)switch(t){case"json":return VL.streamingJson({description:f.description,responseProperty:void 0,fullExamples:s.examples,schema:RS(s.schema,!1,!1,n,i,a,o),source:a,statusCode:c});case"sse":return VL.streamingSse({description:f.description,responseProperty:void 0,fullExamples:s.examples,schema:RS(s.schema,!1,!1,n,i,a,o),source:a,statusCode:c})}return VL.json({description:f.description,schema:RS(s.schema,!1,!1,n,i,a,o),responseProperty:av(e.operation,vb.RESPONSE_PROPERTY),fullExamples:s.examples,source:a,statusCode:c})}for(let[l,m]of Object.entries(f.content??{})){let A=C8.parse(l);if(A!=null){if(A.isOctetStream()||A.isPDF()||A.isAudio()||A.isImage()||A.isVideo()||A.isMultiPartMixed())return VL.file({description:f.description,source:a,statusCode:c});if(A.isPlainText()){let P=m.schema;if(P==null)return VL.text({description:f.description,source:a,statusCode:c});let C=n0(P)?n.resolveSchemaReference(P):P;return C.type==="string"&&C.format==="byte"?VL.file({description:f.description,source:a,statusCode:c}):VL.text({description:f.description,source:a,statusCode:c})}}}}function KlI({responses:e,context:t,source:r,namespace:n}){let i={};for(let[a,o]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let f=n0(o)?t.resolveResponseReference(o):o,u=WGy(f.content??{},t),s=xNf[c];if(s==null){t.logger.warn(`No error name found for status code ${a}`);continue}i[c]={statusCode:c,nameOverride:void 0,generatedName:s,description:f.description,schema:RS(u?.schema??{},!1,!1,t,[s,"Body"],r,n),fullExamples:u?.examples,source:r}}return i}function SPi({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:a}){let{document:o,operation:c,path:f,method:u,baseBreadcrumbs:s}=e,l=av(c,vb.IDEMPOTENT),m=av(c,[vb.REQUEST_NAME_V1,vb.REQUEST_NAME_V2]),A=[...s,"Request"],P=czu({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:A,path:f,httpMethod:u,source:a}),C=/{([^}]+)}/g,I=[...f.matchAll(C)].map(k=>k[1]).filter(k=>k!==void 0);if(I.length>0){let k=new Map(P.pathParameters.map(he=>[he.name,he])),ne=[],Oe=new Set;for(let he of I){let me=k.get(he);Oe.add(he),me?ne.push(me):ne.push({name:he,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Bh.primitive({schema:tm.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})}for(let he of P.pathParameters)Oe.has(he.name)||ne.push(he);P.pathParameters=ne}let T=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let k=n0(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,ne=Object.values(k.content).every(he=>YlI({mediaTypeObject:he})!=null),Oe=[];if(ne)return Oe.push(...Object.entries(k.content).map(([he,me])=>{let ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:new Yla({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:A,source:a,namespace:t.namespace});return ZGy({context:t,convertedParameters:P})&&ve!=null&&(ve.type==="json"||ve.type==="formUrlEncoded")&&ve.schema.type!=="object"&&c.requestBody!=null?ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:t,requestBreadcrumbs:[...A,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:t,requestBreadcrumbs:[...A],source:a,namespace:t.namespace})),ve}).filter(he=>he!=null)),Oe.length===0?[void 0]:Oe;{let he=pzu({content:k.content,description:k.description,document:o,context:new Yla({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:A,source:a,namespace:t.namespace});return ZGy({context:t,convertedParameters:P})&&he!=null&&(he.type==="json"||he.type==="formUrlEncoded")&&he.schema.type!=="object"&&c.requestBody!=null?he=pzu({content:k.content,description:k.description,document:o,context:t,requestBreadcrumbs:[...A,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(he=pzu({content:k.content,description:k.description,document:o,context:t,requestBreadcrumbs:[...A],source:a,namespace:t.namespace})),[he]}})(),z=T.length>1,U=[...s,"Response"],q=XGy({operationContext:e,streamFormat:i,responses:c.responses,context:t,responseBreadcrumbs:U,responseStatusCode:r,source:a}),V=QGy(c),$=zGy(c),re=xGy(e,c,t),Y=av(c,vb.SERVER_NAME_V2);return T.map(k=>({summary:c.summary,internal:av(c,Xve.INTERNAL),idempotent:l,audiences:av(c,vb.AUDIENCES)??[],operationId:c.operationId!=null&&n!=null?c.operationId+"_"+n:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:XlI({operationContext:e,request:k}),pathParameters:P.pathParameters,queryParameters:P.queryParameters,headers:P.headers,requestNameOverride:m??void 0,generatedRequestName:Xne(z?$lI({breadcrumbs:A,request:k}):A,t.options.preserveSchemaIds),request:k,response:q.value,errors:q.errors,servers:Y!=null?[{name:Y,url:void 0,audiences:void 0}]:(c.servers??[]).map(ne=>uzu(ne,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:klI(c,o),security:ZlI(c),availability:$,method:u,path:f,examples:re,pagination:e.pagination,source:a,retries:V}))}function $lI({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function YlI({mediaTypeObject:e}){return av(e,vb.SDK_METHOD_NAME)}function XlI({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 ZlI(e){return e.security??[]}function klI(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function ZGy({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function eJy({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:a,operationParameters:o}=e,c=r.discriminant.name,f=r.discriminant.value,u=r["response-status-code"],s=kGy({context:t,headerToIgnore:c,parameters:a}),l=kGy({context:t,headerToIgnore:c,parameters:o}),m=SPi({operationContext:{...e,pathItemParameters:s,operationParameters:l,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([P])=>parseInt(P)!==u))}},context:t,streamFormat:void 0,source:n}),A=SPi({operationContext:{...e,pathItemParameters:s,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:u,streamFormat:void 0,source:n});return A.forEach(P=>{P.headers.push({name:c,schema:Bh.literal({nameOverride:void 0,generatedName:Xne([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:IV.string(f),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:m,async:A}}function kGy({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=n0(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var zNf="stream";function iJy({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:SPi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=tJy({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let u=t7i(n.schemaReference);u!=null&&t.excludeSchema(u)}let i=rJy({operation:e.operation,response:r.responseStream}),a=SPi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+zNf}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,zNf]},context:t,streamFormat:r.format,suffix:zNf,source:t.source});a.forEach(u=>{u.examples=u.examples.filter(s=>nJy(s,t)!==!1)});let o=tJy({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=rJy({operation:e.operation,response:r.response}),f=SPi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:o?.requestBody,responses:c}},context:t,source:t.source});return f.forEach(u=>{u.examples=u.examples.filter(s=>nJy(s,t)!==!0)}),{streaming:a,nonStreaming:f}}default:ku(r)}}function tJy({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=n0(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=fzu({content:i.content,context:e});if(a==null)return;let o=n0(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(o.allOf==null&&o.properties==null)return;let c=o.properties?.[r.streamConditionProperty];c!=null&&n0(c)&&(c=void 0);let f={...o,properties:{...o.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...c??{}}},title:void 0,required:[...o.required??[],r.streamConditionProperty]};return{requestBody:{content:{[C8.APPLICATION_JSON]:{schema:f}}},schemaReference:n0(a.schema)?a.schema:void 0}}function rJy({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[C8.APPLICATION_JSON]:{schema:t}}}}}function nJy(e,t){return e._visit({unknown:r=>{let n=FX.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var aJy=require("crypto");function oJy({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:a,method:o,baseBreadcrumbs:c,sdkMethodName:f}=t,u=[...c,"Payload"],s=czu({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:u,path:a,httpMethod:o,source:r});if(i.requestBody==null)return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Missing a request body`),[];let l=i.operationId??tfI({path:a,method:o,sdkMethodName:f});if(o!=="POST"&&o!=="GET")return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Not POST or GET`),[];let m=n0(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(m.content).map(([A,P])=>OVr({mediaType:A,mediaTypeObject:P,description:m.description,document:n,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(A=>A!=null).map(A=>{if(A==null||A.type!=="json"&&A.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:i.summary,audiences:av(i,vb.AUDIENCES)??[],sdkName:f,namespace:e.namespace,method:o,operationId:l,tags:e.resolveTagsToTagIds(i.tags),headers:s.headers,generatedPayloadName:Xne(u,e.options.preserveSchemaIds),payload:A.schema,description:i.description,examples:efI(A.fullExamples),source:r}}).filter(A=>A!=null)}function efI(e){if(e==null)return[];let t=[];for(let r of e){let n=n7i(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function tfI({path:e,method:t,sdkMethodName:r}){let n=r?.methodName??rfI(e),i=(0,aJy.createHash)("sha256").update(e).digest("hex").slice(0,8);return nfI(`${n}_${t.toLowerCase()}_${i}`)}function rfI(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function nfI(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function QNf({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=av(r,vb.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=ifI(r,e),o=CGy(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:afI({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:o};if(n)return{type:"webhook",value:oJy({context:e,operationContext:c,source:e.source})};let f=SGy(r);if(f!=null){let l=iJy({context:e,operationContext:c,streamingExtension:f});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let u=jGy(r);if(u!=null){let l=eJy({context:e,operationContext:c,asyncExtension:u,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:SPi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function ifI(e,t){let r=av(e,vb.SDK_METHOD_NAME),n=av(e,vb.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function afI({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let a=[];if(e!=null){if(i&&a.push(e.methodName),e.groupName.length>0){let o=e.groupName[e.groupName.length-1];o!=null&&a.push(typeof o=="string"?o:o.name)}i||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push($A(`${r}_${n.split("/").join("_")}`));return a}function sJy(e,t,r,n){let i=[],a=cJy(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(n.filter.skipEndpoint({method:c.method,path:e})){n.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let f=ofI({operation:c.operation}),u=QNf({context:n,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:f});u&&i.push(u)}return i}function uJy(e,t,r,n){let i=[],a=cJy(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(n.filter.skipEndpoint({method:c.method,path:e})){n.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let f=QNf({context:n,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:!0});f&&i.push(f)}return i}function cJy(e){let t=[];return e.get!=null&&t.push({method:ode.Get,operation:e.get}),e.post!=null&&t.push({method:ode.Post,operation:e.post}),e.put!=null&&t.push({method:ode.Put,operation:e.put}),e.delete!=null&&t.push({method:ode.Delete,operation:e.delete}),e.patch!=null&&t.push({method:ode.Patch,operation:e.patch}),e.head!=null&&t.push({method:ode.Head,operation:e.head}),t}function ofI({operation:e}){return av(e,[vb.WEBHOOK])??!1}function lJy(e){let t=av(e,vb.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=av(e,vb.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function fJy(e){return av(e,vb.FERN_BASIC_AUTH)}function pJy(e,t,r,n){if(n0(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return dJy(i,t,r)}return dJy(e,t,r)}function dJy(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=av(e,Xve.BEARER_FORMAT),i=av(e,vb.FERN_HEADER_AUTH);return nde.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??av(e,vb.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=av(e,vb.FERN_BEARER_TOKEN);return nde.bearer({tokenVariableName:n?.name??av(e,vb.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=fJy(e),i=lJy(e);return nde.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return nde.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return nde.oauth({scopesEnum:sfI(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function sfI(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=e7i({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,o])=>[a,{description:o}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=Q6(n);if(i.type==="enum")return i}}function _Jy(e){return av(e,vb.BASE_PATH)}var ufI=nl.record(nl.string(),nl.object({summary:nl.string().optional(),description:nl.string().optional()}));function hJy({document:e,context:t}){return dko(e,vb.GROUPS,ufI,t.logger)}function yJy({context:e,document:t}){return av(t,vb.FERN_VERSION)??void 0}function vJy(e){let t=av(e,vb.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?pko({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function bJy(e){let t=av(e,vb.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?pko({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function gJy(e,t){let r=av(e,vb.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:Xne([n],t),title:i.title,schema:Rq.string({default:lno(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var cfI="webhooks";function mJy(e){return av(e,cfI)??{}}var mko=class extends hno{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o}){super({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o})}getDummy(){return new Yla({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function OJy(e){return av(e,vb.RESOLUTIONS)}function AJy({openapi:e}){let t=OJy(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let a of n.resolutions)e=lfI({openapi:e,schemaReference:a,schemaName:n.name}),e=PJy({openapi:e,replaceReference:a,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(o=>[i,o]))}}return e}function lfI({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),i=e;for(let a of n){let o=i[a];if(o==null)return e;i=o}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function PJy({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(f=>t.startsWith(f)).sort((f,u)=>u.length-f.length)[0];if(i!=null){let f=n[i];if(f!=null){let u=r.replace(i,f);return PJy({openapi:e,replaceReference:t,schemaReference:u,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(f=>f.replaceAll("~1","/")),o=e;for(let f of a.slice(0,-1)){let u=o[f];if(u==null)return e;o=u}let c=a[a.length-1];return c==null||(o[c]={$ref:r}),e}function jJy({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=AJy({openapi:e});let a=new mko({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),o=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([k,ne])=>{let Oe=pJy(ne,n,t,a);return Oe==null?null:[k,Oe]}).filter(k=>k!==null)),c=new Set(...Object.entries(o).map(([k,ne])=>ne.type==="basic"||ne.type==="bearer"?"Authorization":ne.type==="header"?ne.headerName:null)),f=gJy(e,r.preserveSchemaIds),u=vJy(e),s=bJy(e),l=r.audiences??[],m=[],A=[],P=new mko({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});P.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([k,ne])=>{if(ne==null)return;let Oe=sJy(k,ne,e,P);for(let he of Oe){let me=wJy({operation:he});if(!(l.length>0&&!l.some(ve=>me.includes(ve))))switch(he.type){case"async":m.push(...he.sync),m.push(...he.async);break;case"http":m.push(...he.value);break;case"streaming":m.push(...he.streaming),he.nonStreaming&&m.push(...he.nonStreaming);break;case"webhook":A.push(...he.value);break;default:ku(he)}}}),Object.entries(mJy(e)).forEach(([k,ne])=>{if(ne==null)return;t.logger.debug(`Converting path ${k}`);let Oe=uJy(k,ne,e,P);for(let he of Oe){let me=wJy({operation:he});l.length>0&&!l.some(ve=>me.includes(ve))||A.push(...he.value)}});let C=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([k,ne])=>{let Oe=av(ne,vb.SDK_NAMESPACE);if(!n0(ne)){let he=av(ne,vb.IGNORE);if(he!=null&&he)return[];if($Gy.has(k))return[k,RS({...ne,"x-fern-type-name":`${k}Body`},!1,!1,P,[k],n,Oe??i)]}return[k,RS(ne,!1,!1,P,[k],n,Oe??i)]}).filter(k=>k.length>0)),I=ffI(C,P,n),T=dfI(I,P),z={};for(let[k,ne]of Object.entries(T)){let Oe=Q6(ne);P.isSchemaExcluded(k)||(z[k]=Oe)}let U=new i7i(T,P.nonRequestReferencedSchemas,P),q=A.map(k=>{let Oe=k.examples;if(!r.disableExamples&&Oe.length===0){let he=U.buildExample({schema:k.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});he!=null&&(Oe=[{name:void 0,description:void 0,payload:he}])}return{...k,payload:Q6(k.payload),examples:Oe}}),V=new rzu(T,P,u),$=m.map(k=>{let ne=k.examples,Oe=ne;if(!r.disableExamples&&(ne.length===0||ne.every(vko))){let ve=V.buildEndpointExample(k);ve.length>0&&(Oe=[...ve,...ne.filter(Ce=>!vko(Ce))])}let he=k.request,me=k.response;return{...k,request:he?.type==="json"||he?.type==="formUrlEncoded"?{...he,schema:Q6(he.schema)}:he,response:me?.type==="json"?{...me,schema:Q6(me.schema)}:me,queryParameters:k.queryParameters.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,availability:ve.availability,source:ve.source})),pathParameters:k.pathParameters.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,variableReference:ve.variableReference,availability:ve.availability,source:ve.source})),headers:k.headers.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,env:ve.env,availability:ve.availability,source:ve.source})),examples:Oe,errors:Bg(k.errors,ve=>{let Ce=ve.fullExamples?.map(Be=>{let Se=n7i(Be.value);if(Se!=null)return{name:Be.name,description:Be.description,example:Se}}).filter(pj);if(Ce?.length===0){let Be=U.buildExample({schema:ve.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Be!=null&&Ce.push({name:void 0,description:void 0,example:Be})}return{generatedName:ve.generatedName,nameOverride:ve.nameOverride,schema:Q6(ve.schema),description:ve.description,source:ve.source,examples:Ce}}),retries:k.retries}}),re=hJy({document:e,context:P});return{apiVersion:yJy({context:P,document:e}),basePath:_Jy(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(re??{}).map(([k,ne])=>[k,{summary:ne.summary??void 0,description:ne.description??void 0}])),servers:(e.servers??[]).map(k=>uzu(k,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(k=>[k.name,{id:k.name,description:k.description}])),orderedTagIds:e.tags?.map(k=>k.name)},endpoints:$,webhooks:q,channels:{},groupedSchemas:pno(i,z),securitySchemes:o,hasEndpointsMarkedInternal:$.some(k=>k.internal),nonRequestReferencedSchemas:P.getReferencedSchemas(),variables:f,globalHeaders:u,idempotencyHeaders:s}}function ffI(e,t,r){let n={};for(let[i,a]of Object.entries(e)){if(a.type!=="object"){n[i]=a;continue}let o={$ref:`#/components/schemas/${i}`},c=t.getReferencesFromDiscriminatedUnion(o);if(c==null){n[i]=a;continue}let f={...a,type:"object",properties:a.properties.filter(s=>!c.discriminants.has(s.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(s=>!c.discriminants.has(s.propertyKey)),source:r};n[i]=f;let u=EJy({schema:a,schemas:e});for(let s of[...new Set(u)]){let l=n[s]??e[s];l==null||l.type!=="object"||(n[s]={...l,type:"object",properties:l.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return n}function dfI(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let a={$ref:`#/components/schemas/${n}`},o=t.getDiscriminatedUnionMetadata(a);if(o==null){r[n]=i;continue}let c=[];for(let u of i.properties)if(o.discriminants.has(u.key)){let s=o.discriminants.get(u.key);s!=null&&c.push({...u,schema:Bh.literal({nameOverride:void 0,generatedName:Xne([i.generatedName,s],t.options.preserveSchemaIds),title:void 0,value:IV.string(s),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else c.push(u);let f={...i,type:"object",properties:c};r[n]=f}return r}function EJy({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...EJy({schema:i,schemas:t}))}return r}function _zu(e){return[...new Set(e)]}function wJy({operation:e}){let t=[];switch(e.type){case"async":t=_zu(e.async.flatMap(r=>r.audiences));break;case"http":t=_zu(e.value.flatMap(r=>r.audiences));break;case"streaming":t=_zu(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=_zu(e.value.flatMap(r=>r.audiences));break;default:ku(e)}return t}function Xla({context:e,documents:t,options:r}){let n={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:{}},i=0;for(let a of t)try{let o=a.source!=null?a.source:vPe.openapi({file:"<memory>"});switch(a.type){case"openapi":{let c=jJy({taskContext:e,openApi:a.value,options:yht({options:a.settings,overrides:r}),source:o,namespace:a.namespace});n=yfI(n,c,yht({options:a.settings,overrides:r})),i++;break}case"asyncapi":{let c=wGy({document:a.value,taskContext:e,options:yht({options:a.settings,overrides:r}),source:o,asyncApiOptions:pfI({options:a.settings}),namespace:a.namespace});c.servers!=null&&(n.websocketServers=[...n.websocketServers,...c.servers.map(f=>({...f,audiences:void 0,description:void 0}))]),c.channels!=null&&(n.channels={...n.channels,...c.channels}),c.groupedSchemas!=null&&(n.groupedSchemas=hzu(n.groupedSchemas,c.groupedSchemas)),c.basePath!=null&&(n.basePath=c.basePath),i++;break}default:ku(a)}}catch(o){e.logger.debug(`Skipping parsing document ${a.type==="openapi"?a.value.info?.title:a.source?.file}`),o instanceof Error&&e.logger.debug(o.message,o.stack?`
2677
+ Location: ${i.join("-> ")}`),Bh.unknown({nameOverride:l,generatedName:P,title:C,description:I,availability:T,namespace:c,groupName:A,example:void 0})}}function clI(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 t7i(e){if(e.$ref.startsWith($la))return e.$ref.replace($la,"")}function INf(e,t,r,n){let i=av(e,vb.TYPE_NAME),a=Xne(t,n),o=e.description,c=mPe(e),f=t7i(e);if(f==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return p1.reference({generatedName:a,nameOverride:i,title:void 0,schema:f,description:o??void 0,availability:c,namespace:void 0,groupName:void 0,source:r})}function llI(e){return e.oneOf==null||e.oneOf.length===0}function flI(e){return e.allOf==null||e.allOf.length===0}function X3u(e){return e.properties==null||I8(e.properties)===0}function k3u(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function fno(e,t,r,n){return e.type==="reference"?Bh.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n}):e.type==="optional"?Bh.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0}):e.type==="nullable"?Bh.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0}):e}function Z3u(e){return n0(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Z3u(t)):e.oneOf!=null?e.oneOf.every(t=>Z3u(t)):e.anyOf!=null?e.anyOf.every(t=>Z3u(t)):!1}function cGy({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:a,availability:o,nameOverride:c,generatedName:f,title:u}){let s=Bh.literal({nameOverride:c,generatedName:f,title:u,value:e,namespace:n,groupName:i,description:a,availability:o});return r&&(s=Bh.nullable({nameOverride:c,generatedName:f,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),t&&(s=Bh.optional({nameOverride:c,generatedName:f,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),s}function Ise({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:a,availability:o,generatedName:c,nameOverride:f,title:u}){i=typeof i=="string"?[i]:i;let s=Bh.primitive({nameOverride:f,generatedName:c,title:u,schema:e,description:a,availability:o,namespace:n,groupName:i});return r&&(s=Bh.nullable({nameOverride:f,generatedName:c,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),t&&(s=Bh.optional({nameOverride:f,generatedName:c,title:u,value:s,namespace:n,groupName:i,description:a,availability:o,inline:void 0})),s}function dlI({schemas:e}){let t=new Set;for(let r of e){if(n0(r))return;if(r.enum!=null&&k3u(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function lGy({schemas:e,context:t}){let r={};for(let n of e){let i=dGy({schema:n,context:t});for(let[a,o]of Object.entries(i)){let c=r[a];c!=null?c[o]=n:r[a]={[o]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length)return{discriminant:n,schemas:i}}function dGy({schema:e,context:t}){let r=n0(e)?t.resolveSchemaReference(e):e;return plI({schema:r,context:t})}function plI({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=dGy({schema:n,context:t});for(let[a,o]of Object.entries(i??{}))r[a]=o}return r}for(let[n,i]of Object.entries(e.properties??{})){let a=n0(i)?t.resolveSchemaReference(i):i;a.type==="string"&&a.enum!=null&&k3u(a.enum)&&_lI(a.enum).length===1&&a.enum[0]!=null&&(r[n]=a.enum[0]);let o=pGy(a,"const");a.type==="string"&&o!=null&&(r[n]=o),n==="type"&&a.example!=null&&(r[n]=a.example)}return r}function _lI(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 pGy(e,t){let r=e[t];if(r!=null)return r}function hlI({schema:e,logger:t}){let r=WHy({schema:e,logger:t});if(r!=null)return ZHy(r)}var dno=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith($la))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let n=t.$ref.substring($la.length).split("/"),i=this.document.components;if(i==null||i.schemas==null)throw new Error("Document does not have components.schemas.");let[a,o,c]=n;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let f=i.schemas[a];if(f==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(n0(f)&&(f=this.resolveSchemaReference(f)),o==="properties"&&c!=null){let u=f.properties?.[c];if(u==null)throw new Error(`Property "${c}" not found on "${a}". Full ref: ${t.$ref}`);n0(u)?f=this.resolveSchemaReference(u):f=u}return f}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}};var ezu=class extends dno{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",n=this.document.components;if(n==null||n.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let i=t.$ref.substring(r.length),a=n.messages[i];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function pno(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let n={};for(let[i,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[i]=a;continue}let o=a.namespace;n[o]??={},n[o][i]=a;continue}case"oneOf":case"unknown":r[i]=a;continue;default:ku(a)}return{rootSchemas:r,namespacedSchemas:n}}function n7i(e){if(typeof e=="string")return TS.primitive(zO.string(e));if(typeof e=="number")return Number.isInteger(e)?TS.primitive(zO.int(e)):TS.primitive(zO.double(e));if(typeof e=="boolean")return TS.primitive(zO.boolean(e));if(Array.isArray(e)){let t=e.map(r=>n7i(r));return t.length===0?void 0:TS.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=n7i(n);i!=null&&t.push({key:zO.string(r),value:i})}return TS.map(t)}}function yko(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function _Gy(e){if(e!=null&&Array.isArray(e))return e}var i7i=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,n){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=n}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:a,options:o,skipReadonly:c}){switch(n.type){case"enum":return typeof r=="string"&&hGy({schema:n,value:r})?TS.enum(r):n.values[0]!=null?TS.enum(n.values[0]?.value):void 0;case"literal":return TS.literal(n.value);case"nullable":{if(r==null&&!this.hasExample(n.value,0,a,o)&&this.exceedsMaxDepth(i,o))return TS.null({});let f=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:o,skipReadonly:c});return f??TS.null({})}case"optional":{if(r==null&&!this.hasExample(n.value,0,a,o)&&(o.ignoreOptionals||this.exceedsMaxDepth(i,o))||Object.is(r,null))return;let f=this.buildExampleHelper({schema:n.value,visitedSchemaIds:a,exampleId:t,example:r,depth:i,options:o,skipReadonly:c});return f!=null&&f.type==="array"&&f.value.length===0||f!=null&&f.type==="map"&&f.value.length===0||f!=null&&f.type==="object"&&Object.keys(f.properties).length===0?void 0:f}case"primitive":{let f=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:o});return TS.primitive(f)}case"reference":{let f=this.schemas[n.schema];if(f!=null&&!a.has(n.schema)){a.add(n.schema);let u=f?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),s=this.buildExampleHelper({example:r,schema:f,exampleId:t,visitedSchemaIds:a,depth:i,options:o,skipReadonly:u||this.context.options.respectReadonlySchemas?c:!1});return a.delete(n.schema),s}return}case"oneOf":switch(n.value.type){case"discriminated":{let f={},u={},s={},l=yko(r),m=l?.[n.value.discriminantProperty],A=n.value.schemas[m],P=[],C=this.getDiscriminatedUnionVariantSchema(n.value,l);C!=null&&P.push(C),P.push(...Object.entries(n.value.schemas));for(let I of P)if(m!=null&&A!=null&&A.type==="object"){u=this.getAllProperties(A),s=this.getAllRequiredProperties(A),f[n.value.discriminantProperty]=TS.primitive(zO.string(m));break}else{let T=this.buildExampleHelper({exampleId:t,schema:I[1],example:void 0,visitedSchemaIds:a,depth:i,options:o,skipReadonly:c});if(T!=null){this.mergeExampleWith(T,f),f[n.value.discriminantProperty]=TS.primitive(zO.string(I[0]));break}}for(let I of n.value.commonProperties){u[I.key]={schema:I.schema,readonly:!1};let T=this.getResolvedSchema(I.schema);T.type!=="optional"&&T.type!=="nullable"&&(s[I.key]=I.schema)}for(let[I,T]of Object.entries(u)){let z=I in s;if(z&&l?.[I]!=null){let U=this.buildExampleHelper({schema:T.schema,exampleId:t,example:l[I],visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});if(U!=null)f[I]=U;else return}else{let U=this.buildExampleHelper({exampleId:t,schema:T.schema,example:l?.[I],visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});if(U!=null)f[I]=U;else if(z)return}}return TS.oneOf(U6i.discriminated(f))}case"undiscriminated":{let f=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(f!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:f,visitedSchemaIds:a,depth:i,options:o,skipReadonly:c});break}}return;case"unknown":if(r!=null){let f=n7i(r);if(f!=null)return TS.unknown(f)}return o.ignoreOptionals||this.exceedsMaxDepth(i,o)?void 0:o.isParameter?TS.primitive(zO.string(o.name??"string")):TS.map([{key:zO.string("key"),value:TS.primitive(zO.string("value"))}]);case"array":{let f=_Gy(r),u=[];if(f!=null&&f.length>0)for(let s of f){let l=this.buildExampleHelper({exampleId:t,example:s,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&u.push(l)}else if(n.example!=null&&n.example.length>0)for(let s of n.example){let l=this.buildExampleHelper({exampleId:t,example:s,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&u.push(l)}else{let s=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:a,options:o,skipReadonly:c});s!=null&&u.push(s)}return TS.array(u)}case"map":{let f=yko(r??n.example);if(f!=null&&Object.entries(f).length>0){let l=[];for(let[m,A]of Object.entries(f)){let P=this.buildExampleFromPrimitive({schema:n.key.schema,example:m,options:o}),C=this.buildExampleHelper({exampleId:t,example:A,schema:n.value,visitedSchemaIds:a,depth:i+1,options:o,skipReadonly:c});C!=null&&l.push({key:P,value:C})}return TS.map(l)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return TS.map([{key:zO.string("key"),value:TS.unknown(TS.primitive(zO.string("value")))}]);let u=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...o,name:"key"}}),s=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:a,depth:i+1,options:{...o,name:"value"},skipReadonly:c});return s!=null&&s.type!=="null"?TS.map([{key:u,value:s}]):TS.map([])}case"object":{let f={},u=n.fullExamples?.find(A=>A.name===t)??n.fullExamples?.find(A=>A.name==null)??n.fullExamples?.[0],s=yko(r)??(u!=null?yko(u.value):{})??{},l=this.getAllProperties(n),m=this.getAllRequiredProperties(n);for(let[A,P]of Object.entries(l)){if(c&&P.readonly||P.schema._visit({optional:V=>typeof V.availability=="string"&&V.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 C=A in m,I=Object.keys(s).includes(A),T=s[A],z=this.getSchemaExample(P.schema),U=T??z,q=this.buildExampleHelper({schema:P.schema,exampleId:t,example:U,visitedSchemaIds:a,depth:i+1,options:{...o,name:A},skipReadonly:c});if(C&&q!=null)f[A]=q;else{if(C)return;(I&&q!=null||!o.ignoreOptionals&&q!=null)&&(f[A]=q)}}if(n.additionalProperties){for(let[A,P]of Object.entries(s))if(!(A in f)){let C=this.buildExampleHelper({schema:Bh.unknown({example:P,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:P,visitedSchemaIds:a,depth:i+1,options:{...o,name:A},skipReadonly:c});C!=null&&(f[A]=C)}}return TS.object({properties:f})}default:ku(n)}}mergeExampleWith(t,r){t._visit({array:xc,enum:xc,literal:xc,map:n=>{for(let i of n){let a=i.key;a.type==="string"&&(r[a.value]=i.value)}},object:n=>{for(let[i,a]of Object.entries(n.properties))r[i]=a},oneOf:n=>{if(n.type==="discriminated")for(let[i,a]of Object.entries(n.value))r[i]=a;else this.mergeExampleWith(n.value,r)},primitive:xc,unknown:xc,null:xc,_other:xc})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){if(r==null){let a=t.schemas.find(o=>this.hasExample(o,0,new Set,{ignoreOptionals:!1,isParameter:!1}));return a??t.schemas[0]}return t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,o)=>o.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return hGy({schema:t,value:r})?5:0;case"object":{if(!Iq(r))return 0;let n=this.getAllProperties(t),i=0;for(let[a,o]of Object.entries(n))r[a]!=null?(i++,i+=this.calcExampleHeuristic(o.schema,r[a])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!Iq(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,a)=>a-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let o of t.properties)if(this.hasExample(o.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!n.has(t.schema)){n.add(t.schema);let o=this.hasExample(a,r,n,i);return n.delete(t.schema),o}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,n,i));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(r[n.key]=n.schema)}for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let a=this.getResolvedSchema(i);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}getSchemaExample(t){return t._visit({primitive:r=>r.schema.example,object:r=>r.fullExamples?.[0]?.value,array:r=>r.example,map:r=>r.example,optional:r=>this.getSchemaExample(r.value),enum:r=>r.example,reference:r=>{let n=this.schemas[r.schema];return n!=null?this.getSchemaExample(n):void 0},literal:()=>{},oneOf:()=>{},nullable:r=>this.getSchemaExample(r.value),unknown:r=>r.example,_other:()=>{}})}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?zO.string(t):r.example!=null?zO.string(r.example):zO.string(n.name??FP.STRING);case"base64":return t!=null&&typeof t=="string"?zO.base64(t):r.example!=null?zO.base64(r.example):zO.base64(FP.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?zO.boolean(t):r.example!=null?zO.boolean(r.example):zO.boolean(FP.BOOLEAN);case"date":return t!=null&&typeof t=="string"?zO.date(t):r.example!=null?zO.date(r.example):zO.date(FP.DATE);case"datetime":return t!=null&&typeof t=="string"?zO.datetime(t):r.example!=null?zO.datetime(r.example):zO.datetime(FP.DATE_TIME);case"double":return t!=null&&typeof t=="number"?zO.double(t):r.example!=null?zO.double(r.example):zO.double(FP.DOUBLE);case"float":return t!=null&&typeof t=="number"?zO.float(t):r.example!=null?zO.float(r.example):zO.float(FP.FLOAT);case"int":return t!=null&&typeof t=="number"?zO.int(t):r.example!=null?zO.int(r.example):zO.int(FP.INT);case"int64":return t!=null&&typeof t=="number"?zO.int64(t):r.example!=null?zO.int64(r.example):zO.int64(FP.INT64);case"uint":return t!=null&&typeof t=="number"?zO.uint(t):r.example!=null?zO.uint(r.example):zO.uint(FP.UINT);case"uint64":return t!=null&&typeof t=="number"?zO.uint64(t):r.example!=null?zO.uint64(r.example):zO.uint64(FP.UINT64);default:ku(r)}}};function hGy({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function pqr(e){switch(e.type){case"object":return Bh.object({allOf:e.allOf,properties:e.properties.map(t=>vlI(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 Bh.array({description:e.description,availability:e.availability,value:pqr(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 Bh.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 Bh.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 Bh.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:pqr(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Bh.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:pqr(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Bh.primitive({description:e.description,availability:e.availability,schema:yGy(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Bh.map({description:e.description,availability:e.availability,key:Bh.primitive({description:e.key.description,availability:e.key.availability,schema:yGy(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:pqr(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 Bh.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 Bh.oneOf(ylI(e.value));case"unknown":return Bh.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:ku(e)}}function ylI(e){switch(e.type){case"discriminated":return ont.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:pqr(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,pqr(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return ont.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>pqr(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:ku(e)}}function yGy(e){switch(e.type){case"string":return tm.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return tm.base64({example:void 0});case"boolean":return tm.boolean({default:e.default,example:void 0});case"date":return tm.date({example:void 0});case"datetime":return tm.datetime({example:void 0});case"double":return tm.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 tm.float({example:void 0});case"int":return tm.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 tm.int64({default:e.default,example:void 0});case"uint":return tm.uint({default:void 0,example:void 0});case"uint64":return tm.uint64({default:void 0,example:void 0});default:ku(e)}}function vlI(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:pqr(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function tzu(e){return e.type!=="optional"&&e.type!=="nullable"}function BNf(e){return e==="POST"||e==="PUT"||e==="PATCH"}function vko(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 rzu=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,n){this.schemas=t,this.context=r,this.globalHeaders=n,this.schemas=t,this.exampleTypeFactory=new i7i(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){let r=glI(t.request),n=mlI(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let m=this.exampleTypeFactory.buildExample({skipReadonly:BNf(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&i.push([void 0,m])}else for(let{name:m,value:A}of r.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:BNf(t.method),schema:r.schema,exampleId:m,example:A,options:{isParameter:!1,ignoreOptionals:!0}});P!=null&&i.push([m,P])}if(l&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(n!=null&&n.type==="present"){let l=this.isSchemaRequired(n.schema);if(n.examples.length===0){let m=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});m!=null&&(t.response?.type==="json"?a.push([void 0,dht.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,dht.withStreaming({sse:t.response?.type==="streamingSse",events:[m]})]))}else for(let{name:m,value:A}of n.examples){let P=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:m,example:A,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});P!=null&&(t.response?.type==="json"?a.push([m,dht.withoutStreaming(P)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,dht.withStreaming({sse:t.response?.type==="streamingSse",events:[P]})]))}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];for(let l of t.pathParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&o.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:A})}let c=[];for(let l of t.queryParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&c.push({name:l.name,value:A})}let f=[];for(let l of t.headers){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),m&&A==null)return[];A!=null&&f.push({name:l.name,value:A})}for(let l of this.globalHeaders){let m=l.schema!=null?pqr(l.schema):Bh.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:tm.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),A=this.exampleTypeFactory.buildExample({schema:m,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(A!=null&&!_qr(A)&&(this.logger.debug(`Expected a primitive example but got ${A.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),A=void 0),A==null)return[];A!=null&&f.push({name:l.header,value:A})}let u=[];t.request!=null&&t.response!=null?u=blI(i,a):t.request!=null?u=i.map(([l,m])=>({id:l,request:m,response:void 0})):t.response!=null&&(u=a.map(([l,m])=>({id:l,request:void 0,response:m})));let s=t.examples.filter(l=>vko(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let m=l.value["code-samples"];if(m!=null)return this.convertCodeSamples(m)}return}else return l.codeSamples}).filter(l=>pj(l));return u.length===0?[fht.full({name:void 0,description:void 0,pathParameters:o,queryParameters:c,headers:f,request:void 0,response:void 0,codeSamples:s})]:u.map(({id:l,request:m,response:A})=>fht.full({name:l,description:void 0,pathParameters:o,queryParameters:c,headers:f,request:m,response:A,codeSamples:s}))}convertCodeSamples(t){return t.map(r=>"language"in r?dVr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):dVr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?ade.Csharp:r.sdk,code:r.code})).filter(pj)}isSchemaRequired(t){return tzu(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function blI(e,t){let r=[];if(e.length<=1){let[i,a]=e[0]??[];if(t.length===0)return r.push({id:i,request:a,response:void 0}),r;for(let[o,c]of t)r.push({id:o??i,request:a,response:c});return r}if(t.length<=1){let[i,a]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:a}),r;for(let[o,c]of e)r.push({id:o??i,request:c,response:a});return r}let n=new Set;for(let[i,a]of e){let o=t.find(([f])=>f==null)?.[1]??t[0]?.[1];if(i==null){if(o==null)continue;r.push({id:void 0,request:a,response:o});continue}let c=!1;for(let f=0;f<t.length;f++){let[u,s]=t[f];u==null||n.has(f)||i===u&&(r.push({id:i,request:a,response:s}),u!=null&&n.add(f),c=!0)}!c&&o!=null&&r.push({id:i,request:a,response:o})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[a,o]=t[i],c=e.find(([f])=>f==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:o})}return r}function glI(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:OlI(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function mlI(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 _qr(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return _qr(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return _qr(e.value.value);default:return!1}case"null":return!0;default:ku(e)}}function OlI(e){return Bh.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:pqr(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(pj),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 _no=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new i7i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:a}){let o=[];for(let c of r){let f=[];for(let l of n.queryParameters){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});A!=null&&!_qr(A)&&(A=void 0),!(m&&A==null)&&A!=null&&f.push({name:l.name,value:A})}let u=[];for(let l of n.headers){let m=this.isSchemaRequired(l.schema),A=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});A!=null&&!_qr(A)&&(A=void 0),!(m&&A==null)&&A!=null&&u.push({name:l.name,value:A})}let s=[];for(let l of c.messages){let m=t.getExampleMessageReference(l),A=t.resolveMessageReference({$ref:m}),P=n0(A.payload)?t.resolveSchemaReference(A.payload):A.payload,C=this.exampleTypeFactory.buildExample({schema:RS(P,!1,!1,t,[l.messageId],i,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});C!=null&&s.push({messageType:l.type,payload:C,description:void 0})}o.push({name:c.summary,queryParameters:f,headers:u,description:c.description,messages:s})}return o}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let o of t.queryParameters){let c=this.isSchemaRequired(o.schema),f=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!_qr(f)&&(f=void 0),c&&f==null)return;f!=null&&i.push({name:o.name,value:f})}let a=[];for(let o of t.headers){let c=this.isSchemaRequired(o.schema),f=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!_qr(f)&&(f=void 0),c&&f==null)return;f!=null&&a.push({name:o.name,value:f})}for(let o of r){let c=this.exampleTypeFactory.buildExample({schema:o.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&n.messages.push({messageType:o.type,payload:c,description:void 0})}return n}isSchemaRequired(t){return tzu(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 bCe={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 nzu(e){return av(e,bCe.FERN_EXAMPLES)??[]}function izu(e,t){return t.includes("://")?t:`${e}://${t}`}function azu(e){return e.startsWith("/")?e:"/"+e}function gGy({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let a={},o={};for(let[u,s]of Object.entries(i.components?.schemas??{})){let l=RS(s,!1,!1,e,[u],r,e.namespace);a[u]=l}let c=new _no(a,e),f={};for(let[u,s]of Object.entries(i.servers??{}))f[u]={name:u,url:izu(s.protocol,s.url)};for(let[u,s]of Object.entries(i.channels??{})){let l=av(s,bCe.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${u} is marked with x-fern-ignore. Skipping.`);continue}let m=[];if(s.parameters!=null)for(let[T,z]of Object.entries(s.parameters??{}))m.push({name:T,description:z.description,parameterNameOverride:void 0,schema:z.schema!=null?RS(z.schema,!1,!1,e,t,r,e.namespace):Bh.primitive({schema:tm.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:mPe(z),source:r});let A=[],P=[];if(s.bindings?.ws!=null){if(s.bindings.ws.headers!=null){let T=s.bindings.ws.headers.required??[];for(let[z,U]of Object.entries(s.bindings.ws.headers.properties??{})){if(n0(U)){let re=e.resolveSchemaReference(U);A.push({name:z,schema:EPi(U,!1,!1,e,t,void 0,r,e.namespace),description:re.description,parameterNameOverride:void 0,env:void 0,availability:mPe(re),source:r});continue}let q=T.includes(z),[V,$]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];A.push({name:z,schema:RS(U,V,$,e,[...t,z],r,e.namespace),description:U.description,parameterNameOverride:void 0,env:void 0,availability:mPe(U),source:r})}}if(s.bindings.ws.query!=null){let T=s.bindings.ws.query.required??[];for(let[z,U]of Object.entries(s.bindings.ws.query.properties??{})){if(n0(U)){let re=e.resolveSchemaReference(U);P.push({name:z,schema:EPi(U,!1,!1,e,t,void 0,r,e.namespace),description:re.description,parameterNameOverride:void 0,availability:mPe(re),source:r});continue}let q=T.includes(z),[V,$]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];P.push({name:z,schema:RS(U,V,$,e,[...t,z],r,e.namespace),description:U.description,parameterNameOverride:void 0,availability:mPe(U),source:r})}}}let C;s.publish!=null&&("oneOf"in s.publish.message?C=vGy({generatedName:s.publish.operationId??"PublishEvent",event:s.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):C=bGy({action:"Publish",channelPath:u,message:s.publish.message,context:e,source:r}));let I;if(s.subscribe!=null&&("oneOf"in s.subscribe.message?I=vGy({generatedName:s.subscribe.operationId??"SubscribeEvent",event:s.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):I=bGy({action:"Subscribe",channelPath:u,message:s.subscribe.message,context:e,source:r})),A.length>0||P.length>0||C!=null||I!=null){let T=nzu(s),z=[];if(T.length>0)z=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:T,handshake:{headers:A,queryParameters:P},source:r,namespace:e.namespace});else{let $=[];C!=null&&$.push({type:"publish",payload:C}),I!=null&&$.push({type:"subscribe",payload:I});let re=c.buildWebsocketSessionExample({handshake:{headers:A,queryParameters:P},messages:$});re!=null&&z.push(re)}let U=av(s,bCe.FERN_CHANNEL_ADDRESS),q=U??azu(u),V=[];C!=null&&V.push({origin:"client",name:"publish",body:Q6(C)}),I!=null&&V.push({origin:"server",name:"subscribe",body:Q6(I)}),o[u]={audiences:av(s,vb.AUDIENCES)??[],handshake:{headers:A.map($=>({...$,schema:Q6($.schema),env:$.env})),queryParameters:P.map($=>({...$,schema:Q6($.schema)})),pathParameters:m.map($=>({...$,parameterNameOverride:void 0,schema:Q6($.schema)}))},groupName:e.resolveGroupName([av(s,bCe.FERN_SDK_GROUP_NAME)??u]),messages:V,servers:(s.servers?.map($=>f[$])??Object.values(f)).filter($=>$!=null&&$.name!=null).map($=>({...$,name:$.name})),summary:av(s,bCe.FERN_DISPLAY_NAME),path:q,description:s.description,examples:z,source:r}}}return{groupedSchemas:pno(e.namespace,a),channels:o??void 0,servers:Object.values(f).map(u=>({...u,name:u.name})),basePath:av(i,bCe.BASE_PATH)}}function vGy({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:a,asyncApiOptions:o}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],f=[];for(let u of t.message.oneOf){let s,l={type:"notFound"};if(n0(u)){let m=r.resolveMessageReference(u);!n0(m.payload)&&o.naming==="v2"?(l=m.name?{type:"name",name:m.name}:l,s={...m.payload,title:m.name??m.payload.title,description:m.name??m.payload.description}):s=m.payload}else s=u;f.push(l),c.push(s)}return r7i({description:t.description??t.message.description,availability:mPe(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypePrefixOverrides:o.naming==="v2"?f:[]})}}function bGy({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let a=r.payload;return n0(r.payload)&&(a=n.resolveSchemaReference(r.payload)),RS(a,!1,!1,n,[t,e],i,n.namespace)}}var ozu=class extends dno{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 n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(n)){let f=t.$ref.split("/"),u=f[2],s=f[4];if(u==null||s==null||!this.document.channels?.[u])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${u}`);let m=this.document.channels[u].messages?.[s];if(m==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in m&&!r?this.resolveMessageReference(m):{name:s,...m}}let a=this.document.components;if(!t.$ref.startsWith(i)||!a?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let o=t.$ref.substring(i.length),c=a.messages[o];if(c==null)throw new Error(`${t.$ref} is undefined`);return{name:o,...c}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var mGy="#/channels/",OGy="#/servers/",TNf="$message.";function PGy({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let a={},o={},c={},f=[],u={};e.logger.debug("Parsing V3 AsyncAPI...");for(let[T,z]of Object.entries(i.components?.schemas??{}))a[T]=RS(z,!1,!1,e,[T],r,e.namespace);for(let[T,z]of Object.entries(i.channels??{}))if(o[T]||(o[T]={}),z.messages)for(let[U,q]of Object.entries(z.messages))if(c[U]||(c[U]=[]),e.isReferenceObject(q)){let V=e.resolveMessageReference(q);c[U].push({channelId:T,payload:V.payload})}else e.isMessageWithPayload(q)&&c[U].push({channelId:T,payload:q.payload});for(let[T,z]of Object.entries(c))if(z.length===1){let U=z[0],q=U.channelId;o[q]=o[q]||{},o[q][T]=RS(U.payload,!1,!1,e,[T],r,e.namespace)}else{f.push(T);for(let{channelId:U,payload:q}of z){let V=`${U}_${T}`;o[U]||(o[U]={}),o[U][V]=RS(q,!1,!1,e,[V],r,e.namespace)}}let s=Object.values(o).reduce((T,z)=>({...T,...z}),{}),l=new _no(s,e),m={};for(let[T,z]of Object.entries(i.servers??{}))m[T]={name:T,url:izu(z.protocol,z.host)};let A={};for(let[T,z]of Object.entries(i.operations??{})){if(av(z,bCe.IGNORE))continue;let U=AlI(z);if(A[U]||(A[U]={subscribe:[],publish:[],__parsedMessages:[]}),z.action==="receive")A[U].subscribe.push(...z.messages);else if(z.action==="send")A[U].publish.push(...z.messages);else throw new Error(`Operation ${T} has an invalid action: ${z.action}`)}for(let[T,z]of Object.entries(A)){let U=[];U.push(...AGy({messages:z.subscribe,channelPath:T,origin:"server",messageSchemas:o[T]??{},duplicatedMessageIds:f,context:e})),U.push(...AGy({messages:z.publish,channelPath:T,origin:"client",messageSchemas:o[T]??{},duplicatedMessageIds:f,context:e})),A[T]!=null&&(A[T].__parsedMessages=U)}for(let[T,z]of Object.entries(i.channels??{})){if(av(z,bCe.IGNORE))continue;let U=[],q=[],V=[];if(z.parameters!=null)for(let[$,re]of Object.entries(z.parameters)){let Y=e.isReferenceObject(re)?e.resolveParameterReference(re):re,{type:k,parameterKey:ne}=Y.location!=null?PlI(Y.location):{type:z.address?.includes(`={${$}}`)?"query":"path",parameterKey:$},Oe=av(Y,bCe.FERN_PARAMETER_OPTIONAL),he=X9($A(T))+X9($A($)),me={...Y,type:"string",title:he,example:Y.examples?.[0],default:Y.default,enum:Y.enum,required:void 0},ve=RS(me,!1,!1,e,[ne],r,e.namespace);Oe&&(ve=Bh.optional({value:ve,description:void 0,availability:void 0,generatedName:"",title:he,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let Ce={name:ne,description:Y.description,parameterNameOverride:void 0,schema:ve,variableReference:void 0,availability:mPe(re),source:r};k==="header"?U.push({...Ce,env:void 0}):k==="path"?q.push(Ce):(k==="payload"||k==="query")&&V.push(Ce)}if(U.length>0||V.length>0||A[T]!=null&&(A[T].publish!=null||A[T].subscribe!=null)){let $=nzu(z),re=A[T]?.__parsedMessages??[],Y=[];if($.length>0)Y=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:$,handshake:{headers:U,queryParameters:V},source:r,namespace:e.namespace});else{let he=[],{examplePublishMessage:me,exampleSubscribeMessage:ve}=jlI({messages:re,messageSchemas:o[T]??{}});me!=null&&he.push(me),ve!=null&&he.push(ve);let Ce=l.buildWebsocketSessionExample({handshake:{headers:U,queryParameters:V},messages:he});Ce!=null&&Y.push(Ce)}let k=av(z,bCe.FERN_SDK_GROUP_NAME),ne=(z.servers?.map(he=>wlI(m,he))??Object.values(m)).map(he=>({...he,name:he.name})),Oe=z.address?.split("?")[0]??azu(T);u[T]={audiences:av(z,vb.AUDIENCES)??[],handshake:{headers:U.map(he=>({...he,schema:Q6(he.schema),env:he.env})),queryParameters:V.map(he=>({...he,schema:Q6(he.schema)})),pathParameters:q.map(he=>({...he,parameterNameOverride:void 0,schema:Q6(he.schema)}))},groupName:e.resolveGroupName(typeof k=="string"?[k]:k??[T]),messages:re,summary:av(z,bCe.FERN_DISPLAY_NAME),servers:ne,path:Oe,description:z.description,examples:Y,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${T} as it does not qualify for inclusion (no headers, query params, or operations)`)}let P=pno(e.namespace,a),C=Object.values(m).map(T=>({...T,name:T.name})),I=av(i,bCe.BASE_PATH);return{groupedSchemas:P,channels:u,servers:C,basePath:I}}function AlI(e){if(!e.channel.$ref.startsWith(mGy))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(mGy.length)}function PlI(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(TNf))throw new Error(`Invalid location format: ${e}; expected ${TNf} prefix`);let n=t.substring(TNf.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,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 wlI(e,t){if(!t.$ref.startsWith(OGy))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(OGy.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function AGy({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:a}){let o=[];return e.forEach((c,f)=>{let s=a.resolveMessageReference(c,!0).name;i.includes(s)&&(s=`${t}_${s}`);let l=n[s];l!=null&&o.push({origin:r,name:s??`${r}Message${f+1}`,body:Q6(l)})}),o}function jlI({messages:e,messageSchemas:t}){let r=e.find(o=>o.origin==="client")?.name,n=e.find(o=>o.origin==="server")?.name,i=r!=null?t[r]:void 0,a=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:a!=null&&n!=null?{type:n,payload:a}:void 0}}function wGy({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:a}){let o=[];if(a!=null&&o.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?o.push(c.tags[0].name):i.naming!=="v2"&&o.push("websocket");let f=new ezu({document:c,taskContext:t,options:r,namespace:a});return gGy({context:f,breadcrumbs:o,source:n,asyncApiOptions:i,document:c})}else{let c=e,f=new ozu({document:c,taskContext:t,options:r,namespace:a});return PGy({context:f,breadcrumbs:o,source:n,asyncApiOptions:i,document:c})}}function jGy(e){return av(e,vb.ASYNC_CONFIG)}var EGy="$request.";function SGy(e){let t=av(e,vb.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:ElI(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function ElI(e){return e.startsWith(EGy)?e.slice(EGy.length):e}function DGy(e){let t=e;if(t.cursor!=null)return ant.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return ant.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 ant.custom({results:r.results})}throw new Error("Invalid pagination extension")}function CGy(e,t){let r=av(t,vb.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=av(e,vb.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:DGy(n)}return DGy(r)}}function IGy(e){let t=SlI(e),r={};return qNf({obj:t,occurrences:r,breadcrumbs:[]}),r}function qNf({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)qNf({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)qNf({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function SlI(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?bko(r.get):void 0,put:r?.put!=null?bko(r.put):void 0,post:r?.post!=null?bko(r.post):void 0,patch:r?.patch!=null?bko(r.patch):void 0,delete:r?.delete!=null?bko(r.delete):void 0}]))}}function bko(e){return{...e,requestBody:e.requestBody!=null?n0(e.requestBody)?e.requestBody:DlI(e.requestBody):void 0}}function DlI(e){let t,r;for(let n in e.content){let i=C8.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[C8.MULTIPART_FORM_DATA]:r}}:e}var szu=class{endpoints;parser=new Joa;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 n=[];for(let i of r){let a=this.parser.tryParse(i);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${a.method} ${a.path}`)}return n}};var MGy="#/components/parameters/",BGy="#/components/responses/",TGy="#/components/examples/",qGy="#/components/requestBodies/",RGy="#/components/securitySchemes/",hno=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=IGy(t),this.options=i,this.source=a,this.filter=new szu({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=o}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let a=parseInt(i,10);if(isNaN(a)||a<0||a>=n.length)return{"x-fern-type":"unknown"};n=n[a]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(n0(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(MGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(MGy.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(qGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(qGy.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(BGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(BGy.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(TGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(TGy.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(RGy))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(RGy.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return n0(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}};var Yla=class extends hno{constructor({document:t,taskContext:r,options:n,source:i,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var ClI=nl.object({lang:nl.string(),label:nl.optional(nl.string()),source:nl.string()}),RNf=nl.array(ClI);var NGy={README_EXT:"x-readme"};function IlI(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Iq(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function FGy(e){let t=av(e,NGy.README_EXT);if(!Iq(t))return[];let r=t["code-samples"];if(!IlI(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function xGy(e,t,r){let i=(av(t,vb.EXAMPLES)??[]).filter(u=>{let s=FX.serialization.ExampleEndpointCallSchema.parse(u);return s.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),s.ok}),a=dko(t,Xve.REDOCLY_CODE_SAMPLES_KEBAB,RNf,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...dko(t,Xve.REDOCLY_CODE_SAMPLES_CAMEL,RNf,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&i.push({"code-samples":c.map(u=>({name:u.label??u.lang,language:u.lang,code:u.source,install:void 0,docs:void 0}))});let f=FGy(t);return f.length>0&&i.push({"code-samples":f}),i.map(fht.unknown)}function zGy(e){let t=av(e,vb.AVAILABILITY);if(t==="ga"||t==="generally-available")return ide.GenerallyAvailable;if(t==="beta"||t==="pre-release")return ide.Beta;if(t==="deprecated")return ide.Deprecated;if(e.deprecated)return ide.Deprecated}function QGy(e){let t=av(e,vb.RETRIES);if(t!=null&&t.disabled===!0)return BFu.RetriesConfiguration.disabled(t.disabled)}function uzu(e,t){return{url:MlI({url:e.url,variables:e.variables??{}}),description:e.description,name:BlI(e,t),audiences:av(e,vb.AUDIENCES)}}function MlI({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function BlI(e,t){let r=av(e,[vb.SERVER_NAME_V1,vb.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}function LGy(e){return av(e,vb.PARAMETER_NAME)}function UGy(e){return av(e,vb.SDK_VARIABLE)}function czu({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:a}){let o={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let f=av(c,vb.IGNORE);if(f!=null&&f){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let u=n0(c)?n.resolveParameterReference(c):c,s=u.required??!1,l=mPe(u),m=[...i,u.name],A=Xne(m,n.options.preserveSchemaIds),[P,C]=n.options.coerceOptionalSchemasToNullable?[!1,!s]:[!s,!1],I=u.schema!=null?RS(u.schema,P,C,n,m,a,n.namespace,!1,new Set,mVr({schema:u,logger:n.logger})):s?Bh.primitive({nameOverride:void 0,generatedName:A,title:void 0,schema:tm.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:mVr({schema:u,logger:n.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):Bh.optional({nameOverride:void 0,generatedName:A,title:void 0,value:Bh.primitive({nameOverride:void 0,generatedName:A,title:void 0,schema:tm.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:mVr({schema:u,logger:n.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(u.in==="header"&&u.schema!=null&&!n0(u.schema)&&u.schema.default!=null){let z=u.schema.default;typeof z=="string"&&z.length>0&&(I=Bh.literal({nameOverride:void 0,generatedName:A,title:void 0,value:IV.string(z),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let T={name:u.name,schema:I,description:u.description,parameterNameOverride:LGy(u),availability:l,source:a};u.in==="query"?o.queryParameters.push(T):u.in==="path"?o.pathParameters.push({...T,variableReference:UGy(u)}):u.in==="header"?!TlI.has(u.name.toLowerCase())&&!n.authHeaders.has(u.name)?o.headers.push({...T,env:void 0}):n.logger.debug(`Ignoring ${u.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${u.in} parameter, ${u.name}, in ${t.toUpperCase()} ${e}`)}return o}var TlI=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function VGy(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n.schema;return{contentType:r,schema:i??{},examples:gko(n,t)}}}function qlI(e){return e.includes("json")||e==="*/*"}function NNf({content:e,context:t}){for(let[r,n]of Object.entries(e))if(lzu({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function lzu({mediaType:e,mediaTypeObject:t,context:r}){if(!qlI(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:gko(t,r)}}function fzu({content:e,context:t}){let r=NNf({content:e,context:t});if(!r)return;let[n,i]=r;return lzu({mediaType:n,mediaTypeObject:i,context:t})}function WGy(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:gko(n,t)}}}function gko(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=av(e,Xve.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,a])=>({name:a.summary??i,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,a])=>{let o=n0(a)?t.resolveExampleReference(a):a;return{name:o.summary??i,value:o.value,description:o.description}})),r}function RlI({content:e,context:t}){for(let[r,n]of Object.entries(e))if(GGy({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function GGy({mediaType:e,mediaTypeObject:t,context:r}){if(C8.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:gko(t,r)}}function NlI({content:e}){for(let[t,r]of Object.entries(e))if(JGy({mediaType:t,mediaTypeObject:r}))return[t,r]}function JGy({mediaType:e,mediaTypeObject:t}){if(C8.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function KGy({mediaType:e}){return C8.parse(e)?.isBinary()??!1}function FlI({content:e}){for(let[t,r]of Object.entries(e))if(KGy({mediaType:t}))return[t,r]}function xlI(e,t){let r=n0(e)?FNf(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!n0(i)&&i.type==="string"&&i.format==="binary")!=null}function pzu({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}){let c=FlI({content:e});if(c){let[m,A]=c;return OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o})}let f=NlI({content:e}),u=NNf({content:e,context:n}),s=zlI({json:u,multipart:f,document:r,visitor:{json:([m,A])=>OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}),multipart:([m,A])=>OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o}),neither:()=>{}}});if(s)return s;let l=RlI({content:e,context:n});if(l){let[m,A]=l;return OVr({mediaType:m,mediaTypeObject:A,description:t,document:r,context:n,requestBreadcrumbs:i,source:a,namespace:o})}}function zlI({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!i?.schema&&!a?.schema?n.neither():i?.schema&&a?.schema?i.schema&&xlI(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):a?.schema?n.multipart(t):n.neither()}function OVr({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:a,source:o,namespace:c}){let f=QlI({mediaTypeObject:t});if(KGy({mediaType:e}))return hCe.octetStream({description:r,source:o,sdkMethodName:f,contentType:e});let u=JGy({mediaType:e,mediaTypeObject:t}),s=u?.schema,l=u?.encoding;if(s){let P=n0(s)?FNf(s,n):{id:void 0,schema:s},C=RS(P.schema,!1,!1,i,a,o,c,!1),I=[];if(C.type==="object"){let T=new Set(P.schema.required??[]);for(let z of C.properties){let U=T.has(z.key),{isFile:q,isOptional:V,isArray:$,description:re}=dzu({schema:z.schema,isOptional:!U});if(q){let Y=HGy(z.key,l);I.push({key:z.key,schema:pVr.file({isOptional:V,isArray:$,description:re}),description:re,contentType:Y,exploded:!1,encoding:Y==null?i.options.defaultFormParameterEncoding:void 0})}else{let Y=HGy(z.key,l);I.push({key:z.key,schema:pVr.json(z.schema),description:void 0,contentType:Y,exploded:l?.[z.key]?.explode,encoding:Y==null?i.options.defaultFormParameterEncoding:UlI(Y)})}}}return hCe.multipart({name:n0(s)&&i.getNumberOfOccurrencesForRef(s)===1?P.id:void 0,description:P.schema.description,properties:I,source:o,sdkMethodName:f})}let m=lzu({mediaType:e,mediaTypeObject:t,context:i});if(m){let P=RS(m.schema,!1,!1,i,a,o,c,!0);return hCe.json({description:void 0,schema:P,contentType:m.contentType,fullExamples:m.examples,additionalProperties:!n0(m.schema)&&_ko(m.schema.additionalProperties,i.options),source:o,sdkMethodName:f})}let A=GGy({mediaType:e,mediaTypeObject:t,context:i});if(A!=null&&A.schema!=null){let P=RS(A.schema,!1,!1,i,a,o,c,!1);return hCe.formUrlEncoded({schema:P,description:r,contentType:A.contentType,source:o,fullExamples:A.examples,additionalProperties:!1,sdkMethodName:f})}}function QlI({mediaTypeObject:e}){return av(e,vb.SDK_METHOD_NAME)}var LlI={"application/json":"json"};function UlI(e){return e?LlI[e]:void 0}function FNf(e,t){if(!e.$ref.startsWith($la))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=t7i(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return n0(n)?FNf(n,t):{id:r,schema:n}}function dzu({schema:e,isOptional:t,isArray:r,description:n}){return WlI(e)?dzu({schema:e.value,isOptional:!0,isArray:r,description:e.description}):HlI(e)?dzu({schema:e.value,isOptional:t,isArray:r,description:e.description}):GlI(e)?dzu({schema:e.value,isOptional:t,isArray:!0,description:e.description}):VlI(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function VlI(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function WlI(e){return e.type==="optional"}function HlI(e){return e.type==="nullable"}function GlI(e){return e.type==="array"}function HGy(e,t){return t?.[e]?.contentType}var xNf={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"},$Gy=new Set(Object.values(xNf));var JlI=["200","201","202","204"];function XGy({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:a,source:o}){if(t==null)return{value:void 0,errors:{}};let c=KlI({responses:t,context:r,source:o,namespace:r.namespace}),f=!1,u;for(let s of i!=null?[i]:JlI){let l=t[s];l!=null&&(f=!0,u==null&&(u=YGy({operationContext:e,response:l,context:r,responseBreadcrumbs:n,streamFormat:a,source:o,namespace:r.namespace,statusCode:typeof s=="string"?parseInt(s):s})))}if(u==null&&!f&&t.default!=null&&(u=YGy({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:a,source:o,namespace:r.namespace})),u!=null)switch(u.type){case"json":return{value:u,errors:c};case"streamingJson":case"streamingSse":return{value:u,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:u,errors:c};default:ku(u)}return{value:void 0,errors:c}}function YGy({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:a,namespace:o,statusCode:c}){let f=n0(r)?n.resolveResponseReference(r):r;if(f.content!=null&&Object.entries(f.content).find(([m,A])=>{if(A.schema==null)return!1;let P=n0(A.schema)?n.resolveSchemaReference(A.schema):A.schema;return P.type==="string"&&P.format==="binary"}))return n.options.useBytesForBinaryResponse&&t==null?VL.bytes({description:f.description,source:a,statusCode:c}):VL.file({description:f.description,source:a,statusCode:c});let u=VGy(f.content??{},n);if(u!=null&&t!=null)switch(t){case"json":return VL.streamingJson({statusCode:c,description:f.description,responseProperty:av(e.operation,vb.RESPONSE_PROPERTY),fullExamples:u.examples,schema:RS(u.schema,!1,!1,n,i,a,o),source:a});case"sse":return VL.streamingSse({description:f.description,responseProperty:void 0,fullExamples:u.examples,schema:RS(u.schema,!1,!1,n,i,a,o),source:a,statusCode:c})}let s=fzu({context:n,content:f.content??{}});if(s){if(t!=null)switch(t){case"json":return VL.streamingJson({description:f.description,responseProperty:void 0,fullExamples:s.examples,schema:RS(s.schema,!1,!1,n,i,a,o),source:a,statusCode:c});case"sse":return VL.streamingSse({description:f.description,responseProperty:void 0,fullExamples:s.examples,schema:RS(s.schema,!1,!1,n,i,a,o),source:a,statusCode:c})}return VL.json({description:f.description,schema:RS(s.schema,!1,!1,n,i,a,o),responseProperty:av(e.operation,vb.RESPONSE_PROPERTY),fullExamples:s.examples,source:a,statusCode:c})}for(let[l,m]of Object.entries(f.content??{})){let A=C8.parse(l);if(A!=null){if(A.isOctetStream()||A.isPDF()||A.isAudio()||A.isImage()||A.isVideo()||A.isMultiPartMixed())return VL.file({description:f.description,source:a,statusCode:c});if(A.isPlainText()){let P=m.schema;if(P==null)return VL.text({description:f.description,source:a,statusCode:c});let C=n0(P)?n.resolveSchemaReference(P):P;return C.type==="string"&&C.format==="byte"?VL.file({description:f.description,source:a,statusCode:c}):VL.text({description:f.description,source:a,statusCode:c})}}}}function KlI({responses:e,context:t,source:r,namespace:n}){let i={};for(let[a,o]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let f=n0(o)?t.resolveResponseReference(o):o,u=WGy(f.content??{},t),s=xNf[c];if(s==null){t.logger.warn(`No error name found for status code ${a}`);continue}i[c]={statusCode:c,nameOverride:void 0,generatedName:s,description:f.description,schema:RS(u?.schema??{},!1,!1,t,[s,"Body"],r,n),fullExamples:u?.examples,source:r}}return i}function SPi({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:a}){let{document:o,operation:c,path:f,method:u,baseBreadcrumbs:s}=e,l=av(c,vb.IDEMPOTENT),m=av(c,[vb.REQUEST_NAME_V1,vb.REQUEST_NAME_V2]),A=[...s,"Request"],P=czu({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:A,path:f,httpMethod:u,source:a}),C=/{([^}]+)}/g,I=[...f.matchAll(C)].map(k=>k[1]).filter(k=>k!==void 0);if(I.length>0){let k=new Map(P.pathParameters.map(he=>[he.name,he])),ne=[],Oe=new Set;for(let he of I){let me=k.get(he);Oe.add(he),me?ne.push(me):ne.push({name:he,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Bh.primitive({schema:tm.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})}for(let he of P.pathParameters)Oe.has(he.name)||ne.push(he);P.pathParameters=ne}let T=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let k=n0(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,ne=Object.values(k.content).every(he=>YlI({mediaTypeObject:he})!=null),Oe=[];if(ne)return Oe.push(...Object.entries(k.content).map(([he,me])=>{let ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:new Yla({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:A,source:a,namespace:t.namespace});return ZGy({context:t,convertedParameters:P})&&ve!=null&&(ve.type==="json"||ve.type==="formUrlEncoded")&&ve.schema.type!=="object"&&c.requestBody!=null?ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:t,requestBreadcrumbs:[...A,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(ve=OVr({mediaType:he,mediaTypeObject:me,description:k.description,document:o,context:t,requestBreadcrumbs:[...A],source:a,namespace:t.namespace})),ve}).filter(he=>he!=null)),Oe.length===0?[void 0]:Oe;{let he=pzu({content:k.content,description:k.description,document:o,context:new Yla({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:A,source:a,namespace:t.namespace});return ZGy({context:t,convertedParameters:P})&&he!=null&&(he.type==="json"||he.type==="formUrlEncoded")&&he.schema.type!=="object"&&c.requestBody!=null?he=pzu({content:k.content,description:k.description,document:o,context:t,requestBreadcrumbs:[...A,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(he=pzu({content:k.content,description:k.description,document:o,context:t,requestBreadcrumbs:[...A],source:a,namespace:t.namespace})),[he]}})(),z=T.length>1,U=[...s,"Response"],q=XGy({operationContext:e,streamFormat:i,responses:c.responses,context:t,responseBreadcrumbs:U,responseStatusCode:r,source:a}),V=QGy(c),$=zGy(c),re=xGy(e,c,t),Y=av(c,vb.SERVER_NAME_V2);return T.map(k=>({summary:c.summary,internal:av(c,Xve.INTERNAL),idempotent:l,audiences:av(c,vb.AUDIENCES)??[],operationId:c.operationId!=null&&n!=null?c.operationId+"_"+n:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:XlI({operationContext:e,request:k}),pathParameters:P.pathParameters,queryParameters:P.queryParameters,headers:P.headers,requestNameOverride:m??void 0,generatedRequestName:Xne(z?$lI({breadcrumbs:A,request:k}):A,t.options.preserveSchemaIds),request:k,response:q.value,errors:q.errors,servers:Y!=null?[{name:Y,url:void 0,audiences:void 0}]:(c.servers??[]).map(ne=>uzu(ne,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:klI(c,o),security:ZlI(c),availability:$,method:u,path:f,examples:re,pagination:e.pagination,source:a,retries:V}))}function $lI({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function YlI({mediaTypeObject:e}){return av(e,vb.SDK_METHOD_NAME)}function XlI({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 ZlI(e){return e.security??[]}function klI(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function ZGy({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function eJy({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:a,operationParameters:o}=e,c=r.discriminant.name,f=r.discriminant.value,u=r["response-status-code"],s=kGy({context:t,headerToIgnore:c,parameters:a}),l=kGy({context:t,headerToIgnore:c,parameters:o}),m=SPi({operationContext:{...e,pathItemParameters:s,operationParameters:l,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([P])=>parseInt(P)!==u))}},context:t,streamFormat:void 0,source:n}),A=SPi({operationContext:{...e,pathItemParameters:s,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:u,streamFormat:void 0,source:n});return A.forEach(P=>{P.headers.push({name:c,schema:Bh.literal({nameOverride:void 0,generatedName:Xne([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:IV.string(f),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:m,async:A}}function kGy({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=n0(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var zNf="stream";function iJy({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:SPi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=tJy({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let u=t7i(n.schemaReference);u!=null&&t.excludeSchema(u)}let i=rJy({operation:e.operation,response:r.responseStream}),a=SPi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+zNf}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,zNf]},context:t,streamFormat:r.format,suffix:zNf,source:t.source});a.forEach(u=>{u.examples=u.examples.filter(s=>nJy(s,t)!==!1)});let o=tJy({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=rJy({operation:e.operation,response:r.response}),f=SPi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:o?.requestBody,responses:c}},context:t,source:t.source});return f.forEach(u=>{u.examples=u.examples.filter(s=>nJy(s,t)!==!0)}),{streaming:a,nonStreaming:f}}default:ku(r)}}function tJy({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=n0(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=fzu({content:i.content,context:e});if(a==null)return;let o=n0(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(o.allOf==null&&o.properties==null)return;let c=o.properties?.[r.streamConditionProperty];c!=null&&n0(c)&&(c=void 0);let f={...o,properties:{...o.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...c??{}}},title:void 0,required:[...o.required??[],r.streamConditionProperty]};return{requestBody:{content:{[C8.APPLICATION_JSON]:{schema:f}}},schemaReference:n0(a.schema)?a.schema:void 0}}function rJy({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[C8.APPLICATION_JSON]:{schema:t}}}}}function nJy(e,t){return e._visit({unknown:r=>{let n=FX.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var aJy=require("crypto");function oJy({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:a,method:o,baseBreadcrumbs:c,sdkMethodName:f}=t,u=[...c,"Payload"],s=czu({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:u,path:a,httpMethod:o,source:r});if(i.requestBody==null)return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Missing a request body`),[];let l=i.operationId??tfI({path:a,method:o,sdkMethodName:f});if(o!=="POST"&&o!=="GET")return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Not POST or GET`),[];let m=n0(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(m.content).map(([A,P])=>OVr({mediaType:A,mediaTypeObject:P,description:m.description,document:n,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(A=>A!=null).map(A=>{if(A==null||A.type!=="json"&&A.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:i.summary,audiences:av(i,vb.AUDIENCES)??[],sdkName:f,namespace:e.namespace,method:o,operationId:l,tags:e.resolveTagsToTagIds(i.tags),headers:s.headers,generatedPayloadName:Xne(u,e.options.preserveSchemaIds),payload:A.schema,description:i.description,examples:efI(A.fullExamples),source:r}}).filter(A=>A!=null)}function efI(e){if(e==null)return[];let t=[];for(let r of e){let n=n7i(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function tfI({path:e,method:t,sdkMethodName:r}){let n=r?.methodName??rfI(e),i=(0,aJy.createHash)("sha256").update(e).digest("hex").slice(0,8);return nfI(`${n}_${t.toLowerCase()}_${i}`)}function rfI(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function nfI(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function QNf({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=av(r,vb.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=ifI(r,e),o=CGy(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:afI({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:o};if(n)return{type:"webhook",value:oJy({context:e,operationContext:c,source:e.source})};let f=SGy(r);if(f!=null){let l=iJy({context:e,operationContext:c,streamingExtension:f});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let u=jGy(r);if(u!=null){let l=eJy({context:e,operationContext:c,asyncExtension:u,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:SPi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function ifI(e,t){let r=av(e,vb.SDK_METHOD_NAME),n=av(e,vb.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function afI({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let a=[];if(e!=null){if(i&&a.push(e.methodName),e.groupName.length>0){let o=e.groupName[e.groupName.length-1];o!=null&&a.push(typeof o=="string"?o:o.name)}i||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push($A(`${r}_${n.split("/").join("_")}`));return a}function sJy(e,t,r,n){let i=[],a=cJy(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(n.filter.skipEndpoint({method:c.method,path:e})){n.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let f=ofI({operation:c.operation}),u=QNf({context:n,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:f});u&&i.push(u)}return i}function uJy(e,t,r,n){let i=[],a=cJy(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(n.filter.skipEndpoint({method:c.method,path:e})){n.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let f=QNf({context:n,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:!0});f&&i.push(f)}return i}function cJy(e){let t=[];return e.get!=null&&t.push({method:ode.Get,operation:e.get}),e.post!=null&&t.push({method:ode.Post,operation:e.post}),e.put!=null&&t.push({method:ode.Put,operation:e.put}),e.delete!=null&&t.push({method:ode.Delete,operation:e.delete}),e.patch!=null&&t.push({method:ode.Patch,operation:e.patch}),e.head!=null&&t.push({method:ode.Head,operation:e.head}),t}function ofI({operation:e}){return av(e,[vb.WEBHOOK])??!1}function lJy(e){let t=av(e,vb.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=av(e,vb.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function fJy(e){return av(e,vb.FERN_BASIC_AUTH)}function pJy(e,t,r,n){if(n0(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return dJy(i,t,r)}return dJy(e,t,r)}function dJy(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=av(e,Xve.BEARER_FORMAT),i=av(e,vb.FERN_HEADER_AUTH);return nde.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??av(e,vb.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=av(e,vb.FERN_BEARER_TOKEN);return nde.bearer({tokenVariableName:n?.name??av(e,vb.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=fJy(e),i=lJy(e);return nde.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return nde.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return nde.oauth({scopesEnum:sfI(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function sfI(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=e7i({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,o])=>[a,{description:o}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=Q6(n);if(i.type==="enum")return i}}function _Jy(e){return av(e,vb.BASE_PATH)}var ufI=nl.record(nl.string(),nl.object({summary:nl.string().optional(),description:nl.string().optional()}));function hJy({document:e,context:t}){return dko(e,vb.GROUPS,ufI,t.logger)}function yJy({context:e,document:t}){return av(t,vb.FERN_VERSION)??void 0}function vJy(e){let t=av(e,vb.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?pko({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function bJy(e){let t=av(e,vb.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?pko({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function gJy(e,t){let r=av(e,vb.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:Xne([n],t),title:i.title,schema:Rq.string({default:lno(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var cfI="webhooks";function mJy(e){return av(e,cfI)??{}}var mko=class extends hno{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o}){super({document:t,taskContext:r,authHeaders:n,options:i,source:a,namespace:o})}getDummy(){return new Yla({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function OJy(e){return av(e,vb.RESOLUTIONS)}function AJy({openapi:e}){let t=OJy(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let a of n.resolutions)e=lfI({openapi:e,schemaReference:a,schemaName:n.name}),e=PJy({openapi:e,replaceReference:a,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(o=>[i,o]))}}return e}function lfI({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),i=e;for(let a of n){let o=i[a];if(o==null)return e;i=o}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function PJy({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(f=>t.startsWith(f)).sort((f,u)=>u.length-f.length)[0];if(i!=null){let f=n[i];if(f!=null){let u=r.replace(i,f);return PJy({openapi:e,replaceReference:t,schemaReference:u,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(f=>f.replaceAll("~1","/")),o=e;for(let f of a.slice(0,-1)){let u=o[f];if(u==null)return e;o=u}let c=a[a.length-1];return c==null||(o[c]={$ref:r}),e}function jJy({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=AJy({openapi:e});let a=new mko({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),o=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([k,ne])=>{let Oe=pJy(ne,n,t,a);return Oe==null?null:[k,Oe]}).filter(k=>k!==null)),c=new Set(...Object.entries(o).map(([k,ne])=>ne.type==="basic"||ne.type==="bearer"?"Authorization":ne.type==="header"?ne.headerName:null)),f=gJy(e,r.preserveSchemaIds),u=vJy(e),s=bJy(e),l=r.audiences??[],m=[],A=[],P=new mko({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});P.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([k,ne])=>{if(ne==null)return;let Oe=sJy(k,ne,e,P);for(let he of Oe){let me=wJy({operation:he});if(!(l.length>0&&!l.some(ve=>me.includes(ve))))switch(he.type){case"async":m.push(...he.sync),m.push(...he.async);break;case"http":m.push(...he.value);break;case"streaming":m.push(...he.streaming),he.nonStreaming&&m.push(...he.nonStreaming);break;case"webhook":A.push(...he.value);break;default:ku(he)}}}),Object.entries(mJy(e)).forEach(([k,ne])=>{if(ne==null)return;t.logger.debug(`Converting path ${k}`);let Oe=uJy(k,ne,e,P);for(let he of Oe){let me=wJy({operation:he});l.length>0&&!l.some(ve=>me.includes(ve))||A.push(...he.value)}});let C=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([k,ne])=>{let Oe=av(ne,vb.SDK_NAMESPACE);if(!n0(ne)){let he=av(ne,vb.IGNORE);if(he!=null&&he)return[];if($Gy.has(k))return[k,RS({...ne,"x-fern-type-name":`${k}Body`},!1,!1,P,[k],n,Oe??i)]}return[k,RS(ne,!1,!1,P,[k],n,Oe??i)]}).filter(k=>k.length>0)),I=ffI(C,P,n),T=dfI(I,P),z={};for(let[k,ne]of Object.entries(T)){let Oe=Q6(ne);P.isSchemaExcluded(k)||(z[k]=Oe)}let U=new i7i(T,P.nonRequestReferencedSchemas,P),q=A.map(k=>{let Oe=k.examples;if(!r.disableExamples&&Oe.length===0){let he=U.buildExample({schema:k.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});he!=null&&(Oe=[{name:void 0,description:void 0,payload:he}])}return{...k,payload:Q6(k.payload),examples:Oe}}),V=new rzu(T,P,u),$=m.map(k=>{let ne=k.examples,Oe=ne;if(!r.disableExamples&&(ne.length===0||ne.every(vko))){let ve=V.buildEndpointExample(k);ve.length>0&&(Oe=[...ve,...ne.filter(Ce=>!vko(Ce))])}let he=k.request,me=k.response;return{...k,request:he?.type==="json"||he?.type==="formUrlEncoded"?{...he,schema:Q6(he.schema)}:he,response:me?.type==="json"?{...me,schema:Q6(me.schema)}:me,queryParameters:k.queryParameters.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,availability:ve.availability,source:ve.source})),pathParameters:k.pathParameters.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,variableReference:ve.variableReference,availability:ve.availability,source:ve.source})),headers:k.headers.map(ve=>({description:ve.description,name:ve.name,schema:Q6(ve.schema),parameterNameOverride:ve.parameterNameOverride,env:ve.env,availability:ve.availability,source:ve.source})),examples:Oe,errors:Bg(k.errors,ve=>{let Ce=ve.fullExamples?.map(Be=>{let Se=n7i(Be.value);if(Se!=null)return{name:Be.name,description:Be.description,example:Se}}).filter(pj);if(Ce?.length===0){let Be=U.buildExample({schema:ve.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Be!=null&&Ce.push({name:void 0,description:void 0,example:Be})}return{generatedName:ve.generatedName,nameOverride:ve.nameOverride,schema:Q6(ve.schema),description:ve.description,source:ve.source,examples:Ce}}),retries:k.retries}}),re=hJy({document:e,context:P});return{apiVersion:yJy({context:P,document:e}),basePath:_Jy(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(re??{}).map(([k,ne])=>[k,{summary:ne.summary??void 0,description:ne.description??void 0}])),servers:(e.servers??[]).map(k=>uzu(k,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(k=>[k.name,{id:k.name,description:k.description}])),orderedTagIds:e.tags?.map(k=>k.name)},endpoints:$,webhooks:q,channels:{},groupedSchemas:pno(i,z),securitySchemes:o,hasEndpointsMarkedInternal:$.some(k=>k.internal),nonRequestReferencedSchemas:P.getReferencedSchemas(),variables:f,globalHeaders:u,idempotencyHeaders:s}}function ffI(e,t,r){let n={};for(let[i,a]of Object.entries(e)){if(a.type!=="object"){n[i]=a;continue}let o={$ref:`#/components/schemas/${i}`},c=t.getReferencesFromDiscriminatedUnion(o);if(c==null){n[i]=a;continue}let f={...a,type:"object",properties:a.properties.filter(s=>!c.discriminants.has(s.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(s=>!c.discriminants.has(s.propertyKey)),source:r};n[i]=f;let u=EJy({schema:a,schemas:e});for(let s of[...new Set(u)]){let l=n[s]??e[s];l==null||l.type!=="object"||(n[s]={...l,type:"object",properties:l.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return n}function dfI(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let a={$ref:`#/components/schemas/${n}`},o=t.getDiscriminatedUnionMetadata(a);if(o==null){r[n]=i;continue}let c=[];for(let u of i.properties)if(o.discriminants.has(u.key)){let s=o.discriminants.get(u.key);s!=null&&c.push({...u,schema:Bh.literal({nameOverride:void 0,generatedName:Xne([i.generatedName,s],t.options.preserveSchemaIds),title:void 0,value:IV.string(s),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else c.push(u);let f={...i,type:"object",properties:c};r[n]=f}return r}function EJy({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...EJy({schema:i,schemas:t}))}return r}function _zu(e){return[...new Set(e)]}function wJy({operation:e}){let t=[];switch(e.type){case"async":t=_zu(e.async.flatMap(r=>r.audiences));break;case"http":t=_zu(e.value.flatMap(r=>r.audiences));break;case"streaming":t=_zu(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=_zu(e.value.flatMap(r=>r.audiences));break;default:ku(e)}return t}function Xla({context:e,documents:t,options:r}){let n={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:{}},i=0;for(let a of t)try{let o=a.source!=null?a.source:vPe.openapi({file:"<memory>"});switch(a.type){case"openapi":{let c=jJy({taskContext:e,openApi:a.value,options:yht({options:a.settings,overrides:r}),source:o,namespace:a.namespace});n=yfI(n,c,yht({options:a.settings,overrides:r})),i++;break}case"asyncapi":{let c=wGy({document:a.value,taskContext:e,options:yht({options:a.settings,overrides:r}),source:o,asyncApiOptions:pfI({options:a.settings}),namespace:a.namespace});c.servers!=null&&(n.websocketServers=[...n.websocketServers,...c.servers.map(f=>({...f,audiences:void 0,description:void 0}))]),c.channels!=null&&(n.channels={...n.channels,...c.channels}),c.groupedSchemas!=null&&(n.groupedSchemas=hzu(n.groupedSchemas,c.groupedSchemas)),c.basePath!=null&&(n.basePath=c.basePath),i++;break}default:ku(a)}}catch(o){e.logger.debug(`Skipping parsing document ${a.type==="openapi"?a.value.info?.title:a.source?.file}`),o instanceof Error&&e.logger.debug(o.message,o.stack?`
2678
2678
  `+o.stack:"")}return n}function pfI({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??VHy.naming}}function yzu(e){let t=String(e.description||e.name||e["x-fern-server-name"]||"default").trim(),r=t.toUpperCase();return r==="PRODUCTION"||r==="PRD"||r==="PROD"?"PRD":r==="SANDBOX"||r==="SBX"?"SBX":r==="STAGING"||r==="STG"?"STG":r==="PERFORMANCE"||r==="PRF"||r==="PERF"?"PRF":r==="E2E"||r==="E_2_E"?"E2E":r==="QAL"||r==="QUALITY"?"QAL":t}function _fI(e){try{let n=new URL(e).hostname.split("."),i=new Set(["api","www","service","services","example","com","org","net","io"]);for(let o of n){let c=o.split("-")[0];if(c&&!i.has(c.toLowerCase())&&c.length>2)return c.toLowerCase()}let a=n[0]?.split("-")[0];return a?a.toLowerCase():"api"}catch{let t=e.match(/https?:\/\/([^./-]+)/);return t&&t[1]?t[1].toLowerCase():"api"}}function hfI(e,t){if(e.length===0||t.length===0||e.length!==t.length)return!1;let r=new Map;for(let a of e){let o=yzu(a);r.set(o,a.url)}let n=!0,i=!0;for(let a of t){let o=yzu(a),c=r.get(o);c?c===a.url&&(i=!1):n=!1}return n&&i}function SJy(e){if(e.length===0||!e[0])return"api";let t=e[0].url;return _fI(t)}function yfI(e,t,r){if(!(r?.groupMultiApiEnvironments===!0))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:hzu(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}};if(hfI(e.servers,t.servers)){let a=[],o=[],c=SJy(e.servers),f=SJy(t.servers),u=new Map;for(let m of e.servers){let A=yzu(m);u.has(A)||u.set(A,{});let P=u.get(A);P&&(P[c]={url:m.url,audiences:m.audiences})}for(let m of t.servers){let A=yzu(m);u.has(A)||u.set(A,{});let P=u.get(A);P&&(P[f]={url:m.url,audiences:m.audiences})}for(let[m,A]of u.entries()){let P={type:"grouped",name:m,description:`${m} environment`,urls:A};a.push(P)}let s=e.endpoints.map(m=>({...m,type:"multi-api",apiName:c,servers:[{name:c,url:void 0,audiences:void 0}]})),l=t.endpoints.map(m=>({...m,type:"multi-api",apiName:f,servers:[{name:f,url:void 0,audiences:void 0}]}));return o=[...s,...l],{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:a.map(m=>(m.type==="single",m)),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:o.map(m=>{if(m.type==="multi-api"){let{type:C,apiName:I,servers:T,...z}=m;return{...z,__apiName:I,servers:T}}let{type:A,...P}=m;return P}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:hzu(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}}}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:hzu(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 hzu(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,n]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...n}:e.namespacedSchemas[r]=n;return e}var xrv=$i(c8u(),1),l8u={config:new xrv.Config({apis:{},styleguide:{plugins:[jNf],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function fio(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 wes(e){return e.swagger!=null}function Z4f(e){return e.openapi!=null}function jes({options:e,overrides:t}={}){return{...yht({options:e,overrides:t}),...ZZo({options:e,overrides:t})}}function B7i(e,t={}){return{...Object.fromEntries(xk(e.namedDefinitionFiles).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...xk(e.importedDefinitions).reduce((r,[n,i])=>({...r,...uLo(B7i(i.definition,{defaultURL:i.url}),(a,o)=>RX(n,Sw.of(o)))}),{})}}function Ees(e,t={}){return{...Object.fromEntries(xk(e.packageMarkers).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...xk(e.importedDefinitions).reduce((r,[n,i])=>({...r,...uLo(Ees(i.definition,{defaultURL:i.url}),(a,o)=>RX(n,Sw.of(o)))}),{})}}function HPi(e){return{...Ees(e),...B7i(e)}}function Cxe(e,t){return HPi(e.definition)[t]?.contents}function Pee(e,t){for(let[r,n]of xk(HPi(e.definition)))t(r,n.contents,{isPackageMarker:Dia(r)===mF,defaultUrl:n.defaultUrl})}function Pfa(e,t){for(let[r,n]of xk(Ees(e.definition)))t(r,n.contents)}function jht({breadcrumbs:e=[],title:t,subtitle:r}){let n=[];return e.length>0&&n.push(Mf.blue(e.join(" -> "))),n.push(t),r!=null&&n.push(Mf.dim(r)),n.join(`
2679
2679
  `)}var zrv={None:"none",Header:"header"};var T8u={};yf(T8u,{ConjureAliasDeclaration:()=>v8u,ConjureArgument:()=>I8u,ConjureArgumentWithParamType:()=>C8u,ConjureAuthDefinition:()=>hio,ConjureAuthDefinitionType:()=>S8u,ConjureDefinitions:()=>j8u,ConjureEndpointDefinition:()=>M8u,ConjureEnumDeclaration:()=>P8u,ConjureEnumVariant:()=>A8u,ConjureEnumWithDocs:()=>O8u,ConjureObjectDeclaration:()=>m8u,ConjureParamType:()=>D8u,ConjurePrimitive:()=>y8u,ConjureService:()=>B8u,ConjureServiceName:()=>h8u,ConjureType:()=>R7i,ConjureTypeDeclaration:()=>w8u,ConjureTypeReference:()=>N7i,ConjureTypeWithDocs:()=>b8u,ConjureTypes:()=>E8u,ConjureUnionDeclaration:()=>g8u,DefinitionFile:()=>pnv,WithDocs:()=>IVr,commons:()=>n6f,conjure:()=>i6f,services:()=>a6f,types:()=>o6f});var n6f={};yf(n6f,{WithDocs:()=>IVr});var rm={};yf(rm,{JsonError:()=>dio,ParseError:()=>pio,any:()=>env,bigint:()=>Lrv,boolean:()=>tnv,booleanLiteral:()=>krv,date:()=>Urv,discriminant:()=>lnv,enum_:()=>d8u,getObjectLikeUtils:()=>Pqr,getObjectUtils:()=>wfa,getSchemaUtils:()=>EQ,isProperty:()=>q7i,lazy:()=>Vrv,lazyObject:()=>Yrv,list:()=>_8u,number:()=>rnv,object:()=>p8u,objectWithoutOptionalProperties:()=>$rv,optional:()=>k4f,property:()=>Hrv,record:()=>onv,set:()=>snv,string:()=>nnv,stringLiteral:()=>Zrv,transform:()=>e6f,undiscriminatedUnion:()=>cnv,union:()=>dnv,unknown:()=>inv,withParsedProperties:()=>r6f});var xq={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 J7(e,t){return`Expected ${t}. Received ${iTI(e)}.`}function iTI(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 lde(e){return{...e,json:Qrv(e.json),parse:Qrv(e.parse)}}function Qrv(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
2680
2680
  `)),{ok:!0,value:t}):n}}function f8u(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var dio=class e extends Error{errors;constructor(t){super(t.map(f8u).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var pio=class e extends Error{errors;constructor(t){super(t.map(f8u).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function EQ(e){return{optional:()=>k4f(e),transform:t=>e6f(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new pio(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new dio(n.errors)}}}function k4f(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>xq.OPTIONAL};return{...t,...EQ(t)}}function e6f(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(n,i)=>{let a=t.untransform(n);return e.json(a,i)},getType:()=>e.getType()};return{...r,...EQ(r)}}function Lrv(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:J7(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:J7(t,"bigint")}]},getType:()=>xq.BIGINT};return{...lde(e),...EQ(e)}}var aTI=/^([+-]?\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 Urv(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:J7(t,"string")}]}:aTI.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:J7(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:J7(t,"Date object")}]},getType:()=>xq.DATE};return{...lde(e),...EQ(e)}}function EPe(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...lde(r),...EQ(r)}}}function d8u(e){let t=new Set(e);return EPe(xq.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:J7(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:J7(n,"enum")}]}:{ok:!0,value:n})()}function Vrv(e){let t=t6f(e);return{...t,...EQ(t)}}function t6f(e){return{parse:(t,r)=>_io(e).parse(t,r),json:(t,r)=>_io(e).json(t,r),getType:()=>_io(e).getType()}}function _io(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Ses(e){return Object.entries(e)}function Des(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function T7i(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 Ces(e){return Object.keys(e)}function Wrv(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function Pqr(e){return{withParsedProperties:t=>r6f(e,t)}}function r6f(e,t){let r={parse:(n,i)=>{let a=e.parse(n,i);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[f,u])=>({...c,[f]:typeof u=="function"?u(a.value):u}),{});return{ok:!0,value:{...a.value,...o}}},json:(n,i)=>{if(!T7i(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:J7(n,"object")}]};let a=new Set(Object.keys(t)),o=Des(n,Object.keys(n).filter(c=>!a.has(c)));return e.json(o,i)},getType:()=>e.getType()};return{...r,...EQ(r),...Pqr(r)}}function Hrv(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function q7i(e){return e.isProperty}function p8u(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>q7i(n)?n.rawKey:r),_getParsedProperties:()=>Ces(e),parse:(r,n)=>{let i={},a=[];for(let[o,c]of Ses(e)){let f=q7i(c)?c.rawKey:o,u=q7i(c)?c.valueSchema:c,s={rawKey:f,parsedKey:o,valueSchema:u};i[f]=s,Krv(u)&&a.push(f)}return Grv({value:r,requiredKeys:a,getProperty:o=>{let c=i[o];if(c!=null)return{transformedKey:c.parsedKey,transform:f=>c.valueSchema.parse(f,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},json:(r,n)=>{let i=[];for(let[a,o]of Ses(e)){let c=q7i(o)?o.valueSchema:o;Krv(c)&&i.push(a)}return Grv({value:r,requiredKeys:i,getProperty:a=>{let o=e[a];if(o!=null)return q7i(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:n?.unrecognizedObjectKeys,skipValidation:n?.skipValidation,breadcrumbsPrefix:n?.breadcrumbsPrefix,omitUndefined:n?.omitUndefined})},getType:()=>xq.OBJECT};return{...lde(t),...EQ(t),...Pqr(t),...wfa(t)}}function Grv({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!T7i(e))return{ok:!1,errors:[{path:a,message:J7(e,"object")}]};let o=new Set(t),c=[],f={};for(let[u,s]of Object.entries(e)){let l=r(u);if(l!=null){o.delete(u);let m=l.transform(s);m.ok?f[l.transformedKey]=m.value:(f[u]=s,c.push(...m.errors))}else switch(n){case"fail":c.push({path:[...a,u],message:`Unexpected key "${u}"`});break;case"strip":break;case"passthrough":f[u]=s;break}}return c.push(...t.filter(u=>o.has(u)).map(u=>({path:a,message:`Missing required key "${u}"`}))),c.length===0||i?{ok:!0,value:f}:{ok:!1,errors:c}}function wfa(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>Jrv({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>Jrv({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>xq.OBJECT};return{...r,...EQ(r),...Pqr(r),...wfa(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,n)=>{let i=e.parse(r,{...n,unrecognizedObjectKeys:"passthrough"});return i.ok?{ok:!0,value:{...r,...i.value}}:i},json:(r,n)=>{let i=e.json(r,{...n,unrecognizedObjectKeys:"passthrough"});return i.ok?{ok:!0,value:{...r,...i.value}}:i},getType:()=>xq.OBJECT};return{...t,...EQ(t),...Pqr(t),...wfa(t)}}}}function Jrv({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,o]=Wrv(Ces(t),u=>i.has(u)),c=r(Des(t,o)),f=n(Des(t,a));return c.ok&&f.ok?{ok:!0,value:{...c.value,...f.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...f.ok?[]:f.errors]}}function Krv(e){return!oTI(e)}function oTI(e){switch(e.getType()){case xq.ANY:case xq.UNKNOWN:case xq.OPTIONAL:return!0;default:return!1}}function $rv(e){return p8u(e)}function Yrv(e){let t={...t6f(e),_getRawProperties:()=>_io(e)._getRawProperties(),_getParsedProperties:()=>_io(e)._getParsedProperties()};return{...t,...EQ(t),...Pqr(t),...wfa(t)}}function _8u(e){let t={parse:(r,n)=>Xrv(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>Xrv(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>xq.LIST};return{...lde(t),...EQ(t)}}function Xrv(e,t){return Array.isArray(e)?e.map((n,i)=>t(n,i)).reduce((n,i)=>{if(n.ok&&i.ok)return{ok:!0,value:[...n.value,i.value]};let a=[];return n.ok||a.push(...n.errors),i.ok||a.push(...i.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:J7(e,"list"),path:[]}]}}function Zrv(e){return EPe(xq.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:J7(r,`"${e}"`)}]})()}function krv(e){return EPe(xq.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:J7(r,`${e.toString()}`)}]})()}var env=EPe(xq.ANY,e=>({ok:!0,value:e}));var tnv=EPe(xq.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:J7(e,"boolean")}]});var rnv=EPe(xq.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:J7(e,"number")}]});var nnv=EPe(xq.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:J7(e,"string")}]});var inv=EPe(xq.UNKNOWN,e=>({ok:!0,value:e}));function onv(e,t){let r={parse:(n,i)=>anv({value:n,isKeyNumeric:e.getType()===xq.NUMBER,transformKey:a=>e.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>anv({value:n,isKeyNumeric:e.getType()===xq.NUMBER,transformKey:a=>e.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>xq.RECORD};return{...lde(r),...EQ(r)}}function anv({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return T7i(e)?Ses(e).reduce((a,[o,c])=>{if(c==null)return a;let f=a,u=o;if(t){let A=o.length>0?Number(o):NaN;isNaN(A)||(u=A)}let s=r(u),l=n(c,u);if(f.ok&&s.ok&&l.ok)return{ok:!0,value:{...f.value,[s.value]:l.value}};let m=[];return f.ok||m.push(...f.errors),s.ok||m.push(...s.errors),l.ok||m.push(...l.errors),{ok:!1,errors:m}},{ok:!0,value:{}}):{ok:!1,errors:[{path:i,message:J7(e,"object")}]}}function snv(e){let t=_8u(e),r={parse:(n,i)=>{let a=t.parse(n,i);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:J7(n,"Set")}]},getType:()=>xq.SET};return{...lde(r),...EQ(r)}}function cnv(e){let t={parse:(r,n)=>unv((i,a)=>i.parse(r,a),e,n),json:(r,n)=>unv((i,a)=>i.json(r,a),e,n),getType:()=>xq.UNDISCRIMINATED_UNION};return{...lde(t),...EQ(t)}}function unv(e,t,r){let n=[];for(let[i,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)n.push({path:c.path,message:`[Variant ${i}] ${c.message}`})}return{ok:!1,errors:n}}function lnv(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function dnv(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=d8u(Ces(t)),a={parse:(o,c)=>fnv({value:o,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:f=>i.parse(f,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,u)=>u.parse(f,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>fnv({value:o,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:f=>i.json(f,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,u)=>u.json(f,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>xq.UNION};return{...lde(a),...EQ(a),...Pqr(a)}}function fnv({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!T7i(e))return{ok:!1,errors:[{path:c,message:J7(e,"object")}]};let{[t]:f,...u}=e;if(f==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let s=n(f);if(!s.ok)return{ok:!1,errors:s.errors};let l=i(s.value);if(l==null)return a?{ok:!0,value:{[r]:s.value,...u}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let m=o(u,l);return m.ok?{ok:!0,value:{[r]:f,...m.value}}:m}var IVr=rm.objectWithoutOptionalProperties({docs:rm.string().optional()});var i6f={};yf(i6f,{ConjureServiceName:()=>h8u,DefinitionFile:()=>pnv});var h8u=rm.string();var y8u=rm.enum_(["rid","string","safelong","integer","double","boolean"]);var R7i=rm.undiscriminatedUnion([y8u,rm.string()]);var v8u=rm.objectWithoutOptionalProperties({alias:R7i,docs:rm.string().optional()});var b8u=rm.objectWithoutOptionalProperties({type:R7i,docs:rm.string().optional()});var N7i=rm.undiscriminatedUnion([R7i,b8u]);var g8u=rm.objectWithoutOptionalProperties({union:rm.record(rm.string(),N7i)});var m8u=rm.objectWithoutOptionalProperties({fields:rm.record(rm.string(),N7i)});var O8u=rm.objectWithoutOptionalProperties({value:rm.string()}).extend(IVr);var A8u=rm.undiscriminatedUnion([rm.string(),O8u]);var P8u=rm.objectWithoutOptionalProperties({values:rm.list(A8u)});var w8u=rm.undiscriminatedUnion([v8u,g8u,m8u,P8u]);var j8u=rm.objectWithoutOptionalProperties({objects:rm.record(rm.string(),w8u).optional()});var E8u=rm.objectWithoutOptionalProperties({conjureImports:rm.property("conjure-imports",rm.record(rm.string(),rm.string()).optional()),definitions:j8u.optional()});var S8u=rm.enum_(["none","header"]);var hio=rm.undiscriminatedUnion([S8u,rm.string()]);var D8u=rm.enum_(["path","query","body"]);var C8u=rm.objectWithoutOptionalProperties({paramType:rm.property("param-type",D8u),type:rm.string()}).extend(IVr);var I8u=rm.undiscriminatedUnion([rm.string(),C8u]);var M8u=rm.objectWithoutOptionalProperties({http:rm.string(),auth:hio.optional(),args:rm.record(rm.string(),I8u).optional(),returns:N7i.optional()}).extend(IVr);var B8u=rm.objectWithoutOptionalProperties({name:rm.string().optional(),package:rm.string().optional(),basePath:rm.property("base-path",rm.string().optional()),defaultAuth:rm.property("default-auth",hio.optional()),endpoints:rm.record(rm.string(),M8u).optional()}).extend(IVr);var pnv=rm.objectWithoutOptionalProperties({types:E8u.optional(),services:rm.record(h8u,B8u).optional()});var a6f={};yf(a6f,{ConjureArgument:()=>I8u,ConjureArgumentWithParamType:()=>C8u,ConjureAuthDefinition:()=>hio,ConjureAuthDefinitionType:()=>S8u,ConjureEndpointDefinition:()=>M8u,ConjureParamType:()=>D8u,ConjureService:()=>B8u});var o6f={};yf(o6f,{ConjureAliasDeclaration:()=>v8u,ConjureDefinitions:()=>j8u,ConjureEnumDeclaration:()=>P8u,ConjureEnumVariant:()=>A8u,ConjureEnumWithDocs:()=>O8u,ConjureObjectDeclaration:()=>m8u,ConjurePrimitive:()=>y8u,ConjureType:()=>R7i,ConjureTypeDeclaration:()=>w8u,ConjureTypeReference:()=>N7i,ConjureTypeWithDocs:()=>b8u,ConjureTypes:()=>E8u,ConjureUnionDeclaration:()=>g8u});var _nv=require("fs/promises");async function hnv(e,t){let r=[];for(let n of await nve(e,t))r.push(await sTI({relativeFilepath:m3(e,n),absoluteFilepath:n}));return r}async function sTI({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,_nv.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string