fern-api 0.83.1 → 0.83.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -2158,7 +2158,7 @@ ${HGh.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&xXl(th
|
|
|
2158
2158
|
`+DYi.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?DYi.default.cyan(eJh(t,this.opt.mask)):DYi.default.italic(DYi.default.dim("[hidden]")):this.opt.mask?eJh(t,this.opt.mask):DYi.default.italic(DYi.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 Wfu=aa(ise(),1);var eKh=aa(bZl(),1),Ufu=require("child_process"),_Qa=require("fs"),Lfu=aa(require("path"),1),tKh=aa(require("os"),1),rKh=require("crypto"),rkl=aa(ZJh(),1);var Ffu=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var szo=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var zfu=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var Qfu=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function Vfu(e="",t,r){let n=new nkl(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 kJh(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function zhD(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 nkl=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=zhD(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??tKh.default.tmpdir(),r=(0,rKh.randomUUID)(),n=kJh(this.fileOptions.prefix),i=kJh(this.fileOptions.postfix),a=`${n}${r}${i}`,o=Lfu.default.resolve(t,a),c=Lfu.default.resolve(t)+Lfu.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,_Qa.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new Ffu(t)}}readTemporaryFile(){try{let t=(0,_Qa.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,eKh.detect)(t)??"utf8";rkl.default.encodingExists(r)||(r="utf8"),this.text=rkl.default.decode(t,r)}}catch(t){throw new zfu(t)}}removeTemporaryFile(){try{(0,_Qa.unlinkSync)(this.tempFile)}catch(t){throw new Qfu(t)}}launchEditor(){try{let t=(0,Ufu.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new szo(t)}}launchEditorAsync(t){try{(0,Ufu.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new szo(r)}}};var nKh=aa(Vtt(),1);var uzo=class extends ase{_run(t){this.done=t,this.editorResult=new nKh.Subject;let r=Ive(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"?Wfu.default.dim("Received"):Wfu.default.dim("Press <enter> to launch your preferred editor."),t&&(r=Wfu.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),Vfu(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 uKh=require("stream");var oKh=aa(require("readline"),1),sKh=aa(aKh(),1),BYi=class{constructor(t){this.rl||=oKh.default.createInterface(LhD(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 LhD(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 sKh.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var czo=class extends BYi{constructor(t={}){super(t),this.log=new uKh.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return G2o(this.rl,this.bottomBar.split(`
|
|
2159
2159
|
`).length),this}updateBottomBar(t){return G2o(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+`
|
|
2160
2160
|
`}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&&dfu(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var dz=aa(Vtt(),1),fKh=aa(p2o(),1);var Hfu=aa(Vtt(),1),cKh=aa(p2o(),1),Gfu=function(e,t,r){return typeof e[t]!="function"?(0,Hfu.of)(e):(0,Hfu.from)((0,cKh.default)(e[t])(r).then(n=>(e[t]=n,e)))};var lKh={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}},hQa=class extends BYi{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,dz.from)(t):(0,dz.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,dz.from)(Object.entries(t).map(([i,a])=>({name:i,...a}))):n=(0,dz.from)([t]),this.process=n.pipe((0,dz.concatMap)(this.processQuestion.bind(this)),(0,dz.publish)()),this.process.connect(),this.process.pipe((0,dz.reduce)((i,a)=>(lKh.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,dz.defer)(()=>(0,dz.of)(t).pipe((0,dz.concatMap)(this.setDefaultType.bind(this)),(0,dz.concatMap)(this.filterIfRunnable.bind(this)),(0,dz.concatMap)(()=>Gfu(t,"message",this.answers)),(0,dz.concatMap)(()=>Gfu(t,"default",this.answers)),(0,dz.concatMap)(()=>Gfu(t,"choices",this.answers)),(0,dz.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,dz.defer)(()=>(0,dz.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,dz.defer)(()=>(0,dz.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&lKh.get(this.answers,t.name)!==void 0)return dz.EMPTY;if(t.when===!1)return dz.EMPTY;if(typeof t.when!="function")return(0,dz.of)(t);let{answers:r}=this;return(0,dz.defer)(()=>(0,dz.from)((0,fKh.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,dz.filter)(n=>n!=null)))}};function dKh(e){let t=function(r,n){let i;try{i=new hQa(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",K2o),this.registerPrompt("input",SYi),this.registerPrompt("number",$2o),this.registerPrompt("confirm",Y2o),this.registerPrompt("rawlist",X2o),this.registerPrompt("expand",Z2o),this.registerPrompt("checkbox",k2o),this.registerPrompt("password",ezo),this.registerPrompt("editor",uzo)},t.restoreDefaultPrompts(),t}var akl=dKh();function VhD(e,t){akl.registerPrompt(e,t)}function WhD(){akl.restoreDefaultPrompts()}var HhD={prompt:akl,ui:{BottomBar:czo,Prompt:hQa},createPromptModule:dKh,registerPrompt:VhD,restoreDefaultPrompts:WhD,Separator:sxe},Jfu=HhD;var DQa=require("path"),Z$h=require("fs"),k$h=require("readline"),P$h="posthog-node";function BbD(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[ydu.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 ydu=class{constructor(t,r,n,i){this.name=P$h,this.name=P$h,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(BbD(t,{organization:r,projectId:c,prefix:n,severityAllowList:i}))}}};ydu.POSTHOG_ID_TAG="posthog_distinct_id";var fdu="0123456789abcdef",vdu=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+=fdu.charAt(this.bytes[r]>>>4),t+=fdu.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+=fdu.charAt(this.bytes[r]>>>4),t+=fdu.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}},Jkl=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??TbD()}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 vdu.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,vdu.ofInner(t)}},TbD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),w$h,Kkl=()=>qbD().toString(),qbD=()=>(w$h||(w$h=new Jkl)).generate();function RbD(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 NbD(e,t){global.process.on("uncaughtException",RbD(e,t))}function xbD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var ddu,j$h,pdu;function FbD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return pdu&&r.length===j$h||(j$h=r.length,pdu=r.reduce((n,i)=>{ddu||(ddu={});let a=ddu[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,ddu[i]=[u,s];break}}}return n},{})),pdu}function zbD(e){return typeof Event<"u"&&eYh(e,Event)}function QbD(e){return tYh(e,"Object")}function ref(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return eYh(e,Error)}}function eYh(e,t){try{return e instanceof t}catch{return!1}}function LbD(e){return tYh(e,"ErrorEvent")}function tYh(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function UbD(e,t,r,n){let a=n&&n.mechanism||{handled:!0,type:"generic"},o=rYh(a,r,n);return{$exception_list:await Promise.all(o.map(async u=>{let s=await $bD(e,t,u);return s.value=s.value||"",s.type=s.type||"Error",s.mechanism=a,s}))}}function rYh(e,t,r){let n=VbD(e,t,r);return n.cause?[n,...rYh(e,n.cause,r)]:[n]}function VbD(e,t,r){if(ref(t))return t;if(e.synthetic=!0,QbD(t)){let i=WbD(t);if(i)return i;let a=HbD(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 WbD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(ref(r))return r}}function HbD(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=JbD(e);if(LbD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=GbD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function GbD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function JbD(e,t=40){let r=Object.keys(KbD(e));r.sort();let n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return E$h(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:E$h(a,t)}return""}function E$h(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function KbD(e){return ref(e)?{message:e.message,name:e.name,stack:e.stack,...S$h(e)}:zbD(e)?{type:e.type,target:D$h(e.target),currentTarget:D$h(e.currentTarget),...S$h(e)}:e}function S$h(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 D$h(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function $bD(e,t,r){let n={type:r.name||r.constructor.name,value:r.message},i=YbD(e,r);for(let a of t)i=await a(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function YbD(e,t){return XbD(e(t.stack||"",1),e)}function XbD(e,t){let r=FbD(t);return e.forEach(n=>{n.filename&&(n.chunk_id=r[n.filename])}),e}var ZbD=2e3,jQa=class e{static async captureException(t,r,n,i,a){let o={...a};i||(o.$process_person_profile=!1);let c=await UbD(this.stackParser,this.frameModifiers,r,n);t.capture({event:"$exception",distinctId:i||Kkl(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(NbD(this.onException.bind(this),this.onFatalError.bind(this)),xbD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(ZbD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function kbD(e=process.argv[1]?(0,DQa.dirname)(process.argv[1]):process.cwd(),t=DQa.sep==="\\"){let r=t?C$h(e):e;return n=>{if(!n)return;let i=t?C$h(n):n,{dir:a,base:o,ext:c}=DQa.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 C$h(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var bdu=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)}}},hdu=new bdu(25),nYh=new bdu(20),nef=7,egD=1e3,tgD=1e4;async function rgD(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"||ogD(o)||sgD(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(nYh.get(i))continue;let a=t[i];if(!a)continue;a.sort((f,u)=>f-u);let o=cgD(a);if(o.every(f=>ugD(i,f)))continue;let c=lgD(hdu,i,{});n.push(ngD(i,o,c))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&igD(e,hdu),hdu.reduce(),e}function ngD(e,t,r){return new Promise(n=>{let i=(0,Z$h.createReadStream)(e),a=(0,k$h.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(){nYh.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]=fgD(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 igD(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;agD(r.lineno,r,n)}}function agD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=iYh(e);i<e;i++){let a=r[i];if(a===void 0){I$h(t);return}t.pre_context.push(a)}if(r[e]===void 0){I$h(t);return}t.context_line=r[e];let n=aYh(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 I$h(e){delete e.pre_context,delete e.context_line,delete e.post_context}function ogD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function sgD(e){return e.lineno!==void 0&&e.lineno>tgD||e.colno!==void 0&&e.colno>egD}function ugD(e,t){let r=hdu.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 cgD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=M$h(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+nef:(i.push(n),n=M$h(a)),t++}return i}function M$h(e){return[iYh(e),aYh(e)]}function iYh(e){return Math.max(1,e-nef)}function aYh(e){return e+nef}function lgD(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function fgD(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 dgD="4.18.0",dxe;(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"})(dxe||(dxe={}));var B$h;(function(e){e.Left="left",e.Right="right",e.Center="center"})(B$h||(B$h={}));var T$h;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(T$h||(T$h={}));var q$h;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(q$h||(q$h={}));var R$h;(function(e){e.Html="html",e.Text="text"})(R$h||(R$h={}));var N$h;(function(e){e.Number="number",e.Emoji="emoji"})(N$h||(N$h={}));var x$h;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(x$h||(x$h={}));var F$h;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(F$h||(F$h={}));var z$h;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(z$h||(z$h={}));var Q$h;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(Q$h||(Q$h={}));var pgD=e=>{if("flags"in e){let t=hgD(e.flags),r=ygD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,a])=>[i,oYh(a)])),n=Object.fromEntries(Object.entries(t).map(([i,a])=>[i,_gD(i,a,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function _gD(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 hgD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,ief(r)]).filter(([,t])=>t!==void 0)),ygD=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?oYh(n):void 0]}))},ief=e=>e===void 0?void 0:e.variant??e.enabled,oYh=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},vgD=1,bgD=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"]),ggD="utf8";function mgD(e,t){if(!e||typeof e!="string"||OgD(e))throw new Error(t)}function OgD(e){return e.trim().length===0}function AgD(e){return e?.replace(/\/+$/,"")}async function PgD(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 L$h(){return new Date().getTime()}function Hkl(){return new Date().toISOString()}function gdu(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function wgD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function jgD(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 EgD(e,t=0,r){let n=jgD(e);return r?.has(n)?!1:parseInt(n,16)/4294967295<t}function U$h(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var gzo=String.fromCharCode,V$h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_du={};function SgD(e,t){if(!_du[e]){_du[e]={};for(let r=0;r<e.length;r++)_du[e][e.charAt(r)]=r}return _du[e][t]}var PQa={compressToBase64:function(e){if(e==null)return"";let t=PQa._compress(e,6,function(r){return V$h.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:PQa._decompress(e.length,32,function(t){return SgD(V$h,e.charAt(t))})},compress:function(e){return PQa._compress(e,16,function(t){return gzo(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,M;for(M=0;M<e.length;M+=1)if(f=e.charAt(M),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:PQa._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,M;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;M=gzo(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;M=gzo(m);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){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(M=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++]=gzo(m),M=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++]=gzo(m),M=c-1,o--;break;case 2:return i.join("")}if(o==0&&(o=Math.pow(2,f),f++),n[M])u=n[M];else if(M===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++)}}},$kl=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)}},EQa=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()}},mzo=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function W$h(e){if(e instanceof EQa){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 Gkl(e){return typeof e=="object"&&(e instanceof EQa||e instanceof mzo)}function H$h(e){return typeof e=="object"&&e instanceof EQa&&e.status===413}var Ykl;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Ykl||(Ykl={}));var Xkl=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new $kl,this._isInitialized=!1,mgD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=AgD(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:Gkl},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(dxe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(dxe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(dxe.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=Kkl();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=EgD(this.apiKey,vgD,bgD)?`${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=>pgD(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=ief(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(Ykl.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(dxe.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(dxe.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(dxe.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(dxe.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(dxe.Queue,a),this._events.emit(t,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=gdu(()=>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:Hkl()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${L$h()}&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(PQa.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:Hkl(),uuid:n?.uuid?n.uuid:Kkl()};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 W$h(t)})}async flush(){let t=U$h([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),U$h([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(dxe.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(dxe.Queue)||[]).slice(i.length);this.setPersistedProperty(dxe.Queue,A),t=A},c={api_key:this.apiKey,batch:a,sent_at:Hkl()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${L$h()}&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(PQa.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:m=>H$h(m)?!1:Gkl(m)};try{await this.fetchWithRetry(u,s,l)}catch(m){if(H$h(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 mzo||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,ggD)}catch{c=new TextEncoder().encode(o).length}return await PgD(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(s){throw new mzo(s)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new EQa(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(dxe.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!Gkl(i))throw i;await W$h(i)}};return Promise.race([new Promise((i,a)=>{gdu(()=>{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}},Zkl=wgD();if(!Zkl){let e=A$h();Zkl=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 sYh=Zkl,mdu=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()}},uYh=new mdu(async()=>{try{return await import("crypto")}catch{return}});async function DgD(){return await uYh.getValue()}var CgD=new mdu(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await uYh.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function IgD(){return await CgD.getValue()}async function MgD(e){let t=await DgD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await IgD();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 BgD=60*1e3,TgD=1152921504606847e3,qgD=["is_not"],wQa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},ose=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},kkl=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||sYh,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 ose?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 ose||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 ose("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 ose("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 ose)o=!0;else throw s}if(c!==void 0)return c;if(o)throw new ose("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=lYh(c,i,this.cohorts,this.debugMode):u=cYh(c,i,o),!u)return!1}if(a==null)return!0}return!(a!=null&&await G$h(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await G$h(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(BgD,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 wQa(`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 wQa(`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 wQa(`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 wQa&&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=gdu(()=>{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=gdu(()=>{a.abort()},this.timeout),n.signal=a.signal}try{return this.fetch(r,n)}finally{clearTimeout(i)}}};async function G$h(e,t,r=""){let n=await MgD(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/TgD}function cYh(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 ose("Operator is_not_set is not supported")}else throw new ose(`Property ${n} not found in propertyValues`);let o=t[n];if(o==null&&!qgD.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 J$h(String(i))&&String(o).match(String(i))!==null;case"not_regex":return J$h(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=RgD(String(i));if(u==null&&(u=K$h(i)),u==null)throw new ose(`Invalid date: ${i}`);let s=K$h(o);return["is_date_before"].includes(a)?s<u:s>u}default:throw new ose(`Unknown operator: ${a}`)}}function lYh(e,t,r,n=!1){let i=String(e.value);if(!(i in r))throw new ose("can't match cohort without a given cohort property value");let a=r[i];return fYh(a,t,r,n)}function fYh(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=fYh(c,t,r,n);if(i==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof ose)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new ose("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=lYh(c,t,r,n):f=cYh(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 ose)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new ose("can't match cohort without a given cohort property value");return i==="AND"}}function J$h(e){try{return new RegExp(e),!0}catch{return!1}}function K$h(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 ose(`${e} is in an invalid date format`)}else throw new ose(`The date provided ${e} must be a string, number, or date object`)}function RgD(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 eef=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},NgD=100,$$h=30*1e3,xgD=50*1e3,tef=class extends Xkl{constructor(t,r={}){if(super(t,r),this._memoryStorage=new eef,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,NgD):$$h,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 kkl({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 jQa(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||xgD}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):sYh(t,r)}getLibraryVersion(){return dgD}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[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!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[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!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=$$h){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 M=await super.getFeatureFlagDetailStateless(t,r,i,f,u,a);if(M===void 0)return;P=M.response,l=ief(P),A=M?.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");jQa.captureException(this,t,{syntheticException:i},r,n)}},Y$h=/\(error: (.*)\)/,dYh=50,pYh="?";function FgD(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||pYh,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:X$h(i[3]),colno:X$h(i[4]),in_app:zgD(s||"",l),platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function zgD(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 X$h(e){return parseInt(e||"",10)||void 0}function QgD(e){return[90,FgD(e)]}function LgD(e){let r=[QgD(e)].sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0)=>{let a=[],o=n.split(`
|
|
2161
|
-
`);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let u=Y$h.test(f)?f.replace(Y$h,"$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>=dYh)break}}return UgD(a)}}function UgD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,dYh).map(r=>({...r,filename:r.filename||VgD(t).filename,function:r.function||pYh}))}function VgD(e){return e[e.length-1]||{}}jQa.stackParser=LgD(kbD());jQa.frameModifiers=[rgD];var SQa=class extends tef{getLibraryId(){return"posthog-node"}};var Odu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new SQa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.83.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Ozo=class{async sendEvent(){}async identify(){}async flush(){}};var CQa=require("fs/promises"),vYh=require("os"),bYh=require("path");var _Yh=aa(require("crypto")),Pdu=new Uint8Array(256),Adu=Pdu.length;function aef(){return Adu>Pdu.length-16&&(_Yh.default.randomFillSync(Pdu),Adu=0),Pdu.slice(Adu,Adu+=16)}var Bve=[];for(let e=0;e<256;++e)Bve.push((e+256).toString(16).slice(1));function hYh(e,t=0){return Bve[e[t+0]]+Bve[e[t+1]]+Bve[e[t+2]]+Bve[e[t+3]]+"-"+Bve[e[t+4]]+Bve[e[t+5]]+"-"+Bve[e[t+6]]+Bve[e[t+7]]+"-"+Bve[e[t+8]]+Bve[e[t+9]]+"-"+Bve[e[t+10]]+Bve[e[t+11]]+Bve[e[t+12]]+Bve[e[t+13]]+Bve[e[t+14]]+Bve[e[t+15]]}var yYh=aa(require("crypto")),oef={randomUUID:yYh.default.randomUUID};function WgD(e,t,r){if(oef.randomUUID&&!t&&!e)return oef.randomUUID();e=e||{};let n=e.random||(e.rng||aef)();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 hYh(n)}var Ept=WgD;var HgD="id",GgD=".fern",Azo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new SQa(r),this.userId=t==null?void 0:mGl(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.83.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Kl(Q_.of((0,vYh.homedir)()),hu.of(GgD),hu.of(HgD));await qv(t)||(await(0,CQa.mkdir)((0,bYh.dirname)(t),{recursive:!0}),await(0,CQa.writeFile)(t,Ept())),this.persistedDistinctId=(await(0,CQa.readFile)(t)).toString()}return this.persistedDistinctId}};var sef;async function IQa(){return sef==null&&(sef=await JgD()),sef}async function JgD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Ozo;let r=await Bau();return r!=null?new Azo({token:r,posthogApiKey:e}):await I8a()!=null?new Odu({posthogApiKey:e}):new Azo({token:void 0,posthogApiKey:e})}catch{return new Ozo}}function Pzo(e,t){return function(){return e.apply(t,arguments)}}var{toString:KgD}=Object.prototype,{getPrototypeOf:cef}=Object,{iterator:jdu,toStringTag:mYh}=Symbol,Edu=(e=>t=>{let r=KgD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),TIr=e=>(e=e.toLowerCase(),t=>Edu(t)===e),Sdu=e=>t=>typeof t===e,{isArray:BQa}=Array,MQa=Sdu("undefined");function wzo(e){return e!==null&&!MQa(e)&&e.constructor!==null&&!MQa(e.constructor)&&pxe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var OYh=TIr("ArrayBuffer");function $gD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&OYh(e.buffer),t}var YgD=Sdu("string"),pxe=Sdu("function"),AYh=Sdu("number"),jzo=e=>e!==null&&typeof e=="object",XgD=e=>e===!0||e===!1,wdu=e=>{if(Edu(e)!=="object")return!1;let t=cef(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(mYh in e)&&!(jdu in e)},ZgD=e=>{if(!jzo(e)||wzo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},kgD=TIr("Date"),e0D=TIr("File"),t0D=TIr("Blob"),r0D=TIr("FileList"),n0D=e=>jzo(e)&&pxe(e.pipe),i0D=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||pxe(e.append)&&((t=Edu(e))==="formdata"||t==="object"&&pxe(e.toString)&&e.toString()==="[object FormData]"))},a0D=TIr("URLSearchParams"),[o0D,s0D,u0D,c0D]=["ReadableStream","Request","Response","Headers"].map(TIr),l0D=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ezo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),BQa(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(wzo(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 PYh(e,t){if(wzo(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 FYi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,wYh=e=>!MQa(e)&&e!==FYi;function uef(){let{caseless:e,skipUndefined:t}=wYh(this)&&this||{},r={},n=(i,a)=>{let o=e&&PYh(r,a)||a;wdu(r[o])&&wdu(i)?r[o]=uef(r[o],i):wdu(i)?r[o]=uef({},i):BQa(i)?r[o]=i.slice():(!t||!MQa(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&Ezo(arguments[i],n);return r}var f0D=(e,t,r,{allOwnKeys:n}={})=>(Ezo(t,(i,a)=>{r&&pxe(i)?e[a]=Pzo(i,r):e[a]=i},{allOwnKeys:n}),e),d0D=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),p0D=(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)},_0D=(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&&cef(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},h0D=(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},y0D=e=>{if(!e)return null;if(BQa(e))return e;let t=e.length;if(!AYh(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},v0D=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&cef(Uint8Array)),b0D=(e,t)=>{let n=(e&&e[jdu]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},g0D=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},m0D=TIr("HTMLFormElement"),O0D=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),gYh=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),A0D=TIr("RegExp"),jYh=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};Ezo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},P0D=e=>{jYh(e,(t,r)=>{if(pxe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(pxe(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+"'")})}})},w0D=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return BQa(e)?n(e):n(String(e).split(t)),r},j0D=()=>{},E0D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function S0D(e){return!!(e&&pxe(e.append)&&e[mYh]==="FormData"&&e[jdu])}var D0D=e=>{let t=new Array(10),r=(n,i)=>{if(jzo(n)){if(t.indexOf(n)>=0)return;if(wzo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=BQa(n)?[]:{};return Ezo(n,(o,c)=>{let f=r(o,i+1);!MQa(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},C0D=TIr("AsyncFunction"),I0D=e=>e&&(jzo(e)||pxe(e))&&pxe(e.then)&&pxe(e.catch),EYh=((e,t)=>e?setImmediate:t?((r,n)=>(FYi.addEventListener("message",({source:i,data:a})=>{i===FYi&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),FYi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",pxe(FYi.postMessage)),M0D=typeof queueMicrotask<"u"?queueMicrotask.bind(FYi):typeof process<"u"&&process.nextTick||EYh,B0D=e=>e!=null&&pxe(e[jdu]),$f={isArray:BQa,isArrayBuffer:OYh,isBuffer:wzo,isFormData:i0D,isArrayBufferView:$gD,isString:YgD,isNumber:AYh,isBoolean:XgD,isObject:jzo,isPlainObject:wdu,isEmptyObject:ZgD,isReadableStream:o0D,isRequest:s0D,isResponse:u0D,isHeaders:c0D,isUndefined:MQa,isDate:kgD,isFile:e0D,isBlob:t0D,isRegExp:A0D,isFunction:pxe,isStream:n0D,isURLSearchParams:a0D,isTypedArray:v0D,isFileList:r0D,forEach:Ezo,merge:uef,extend:f0D,trim:l0D,stripBOM:d0D,inherits:p0D,toFlatObject:_0D,kindOf:Edu,kindOfTest:TIr,endsWith:h0D,toArray:y0D,forEachEntry:b0D,matchAll:g0D,isHTMLForm:m0D,hasOwnProperty:gYh,hasOwnProp:gYh,reduceDescriptors:jYh,freezeMethods:P0D,toObjectSet:w0D,toCamelCase:O0D,noop:j0D,toFiniteNumber:E0D,findKey:PYh,global:FYi,isContextDefined:wYh,isSpecCompliantForm:S0D,toJSONObject:D0D,isAsyncFn:C0D,isThenable:I0D,setImmediate:EYh,asap:M0D,isIterable:B0D};function TQa(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)}$f.inherits(TQa,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:$f.toJSONObject(this.config),code:this.code,status:this.status}}});var SYh=TQa.prototype,DYh={};["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=>{DYh[e]={value:e}});Object.defineProperties(TQa,DYh);Object.defineProperty(SYh,"isAxiosError",{value:!0});TQa.from=(e,t,r,n,i,a)=>{let o=Object.create(SYh);$f.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 TQa.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 _m=TQa;var CYh=aa(Yfu(),1),Ddu=CYh.default;function lef(e){return $f.isPlainObject(e)||$f.isArray(e)}function MYh(e){return $f.endsWith(e,"[]")?e.slice(0,-2):e}function IYh(e,t,r){return e?e.concat(t).map(function(i,a){return i=MYh(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function T0D(e){return $f.isArray(e)&&!e.some(lef)}var q0D=$f.toFlatObject($f,{},null,function(t){return/^is[A-Z]/.test(t)});function R0D(e,t,r){if(!$f.isObject(e))throw new TypeError("target must be an object");t=t||new(Ddu||FormData),r=$f.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!$f.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||s,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&$f.isSpecCompliantForm(t);if(!$f.isFunction(i))throw new TypeError("visitor must be a function");function u(P){if(P===null)return"";if($f.isDate(P))return P.toISOString();if($f.isBoolean(P))return P.toString();if(!f&&$f.isBlob(P))throw new _m("Blob is not supported. Use a Buffer instead.");return $f.isArrayBuffer(P)||$f.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function s(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if($f.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if($f.isArray(P)&&T0D(P)||($f.isFileList(P)||$f.endsWith(C,"[]"))&&(T=$f.toArray(P)))return C=MYh(C),T.forEach(function(U,R){!($f.isUndefined(U)||U===null)&&t.append(o===!0?IYh([C],R,a):o===null?C:C+"[]",u(U))}),!1}return lef(P)?!0:(t.append(IYh(M,C,a),u(P)),!1)}let l=[],m=Object.assign(q0D,{defaultVisitor:s,convertValue:u,isVisitable:lef});function A(P,C){if(!$f.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),$f.forEach(P,function(T,z){(!($f.isUndefined(T)||T===null)&&i.call(t,T,$f.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!$f.isObject(e))throw new TypeError("data must be an object");return A(e),t}var WIi=R0D;function BYh(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function TYh(e,t){this._pairs=[],e&&WIi(e,this,t)}var qYh=TYh.prototype;qYh.append=function(t,r){this._pairs.push([t,r])};qYh.toString=function(t){let r=t?function(n){return t.call(this,n,BYh)}:BYh;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var RYh=TYh;function N0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function zYi(e,t,r){if(!t)return e;let n=r&&r.encode||N0D;$f.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=$f.isURLSearchParams(t)?t.toString():new RYh(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var fef=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){$f.forEach(this.handlers,function(n){n!==null&&t(n)})}},def=fef;var qQa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var zYh=aa(require("crypto"),1);var NYh=aa(require("url"),1),xYh=NYh.default.URLSearchParams;var pef="abcdefghijklmnopqrstuvwxyz",FYh="0123456789",QYh={DIGIT:FYh,ALPHA:pef,ALPHA_DIGIT:pef+pef.toUpperCase()+FYh},x0D=(e=16,t=QYh.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);zYh.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},LYh={isNode:!0,classes:{URLSearchParams:xYh,FormData:Ddu,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:QYh,generateString:x0D,protocols:["http","https","file","data"]};var yef={};lf(yef,{hasBrowserEnv:()=>hef,hasStandardBrowserEnv:()=>F0D,hasStandardBrowserWebWorkerEnv:()=>z0D,navigator:()=>_ef,origin:()=>Q0D});var hef=typeof window<"u"&&typeof document<"u",_ef=typeof navigator=="object"&&navigator||void 0,F0D=hef&&(!_ef||["ReactNative","NativeScript","NS"].indexOf(_ef.product)<0),z0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Q0D=hef&&window.location.href||"http://localhost";var p4={...yef,...LYh};function vef(e,t){return WIi(e,new p4.classes.URLSearchParams,{visitor:function(r,n,i,a){return p4.isNode&&$f.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function L0D(e){return $f.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function U0D(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 V0D(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&&$f.isArray(i)?i.length:o,f?($f.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!$f.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&$f.isArray(i[o])&&(i[o]=U0D(i[o])),!c)}if($f.isFormData(e)&&$f.isFunction(e.entries)){let r={};return $f.forEachEntry(e,(n,i)=>{t(L0D(n),i,r,0)}),r}return null}var Cdu=V0D;function W0D(e,t,r){if($f.isString(e))try{return(t||JSON.parse)(e),$f.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var bef={transitional:qQa,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=$f.isObject(t);if(a&&$f.isHTMLForm(t)&&(t=new FormData(t)),$f.isFormData(t))return i?JSON.stringify(Cdu(t)):t;if($f.isArrayBuffer(t)||$f.isBuffer(t)||$f.isStream(t)||$f.isFile(t)||$f.isBlob(t)||$f.isReadableStream(t))return t;if($f.isArrayBufferView(t))return t.buffer;if($f.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 vef(t,this.formSerializer).toString();if((c=$f.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return WIi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),W0D(t)):t}],transformResponse:[function(t){let r=this.transitional||bef.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if($f.isResponse(t)||$f.isReadableStream(t))return t;if(t&&$f.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"?_m.from(c,_m.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:p4.classes.FormData,Blob:p4.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$f.forEach(["delete","get","head","post","put","patch"],e=>{bef.headers[e]={}});var RQa=bef;var H0D=$f.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"]),UYh=e=>{let t={},r,n,i;return e&&e.split(`
|
|
2161
|
+
`);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let u=Y$h.test(f)?f.replace(Y$h,"$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>=dYh)break}}return UgD(a)}}function UgD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,dYh).map(r=>({...r,filename:r.filename||VgD(t).filename,function:r.function||pYh}))}function VgD(e){return e[e.length-1]||{}}jQa.stackParser=LgD(kbD());jQa.frameModifiers=[rgD];var SQa=class extends tef{getLibraryId(){return"posthog-node"}};var Odu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new SQa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.83.2",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Ozo=class{async sendEvent(){}async identify(){}async flush(){}};var CQa=require("fs/promises"),vYh=require("os"),bYh=require("path");var _Yh=aa(require("crypto")),Pdu=new Uint8Array(256),Adu=Pdu.length;function aef(){return Adu>Pdu.length-16&&(_Yh.default.randomFillSync(Pdu),Adu=0),Pdu.slice(Adu,Adu+=16)}var Bve=[];for(let e=0;e<256;++e)Bve.push((e+256).toString(16).slice(1));function hYh(e,t=0){return Bve[e[t+0]]+Bve[e[t+1]]+Bve[e[t+2]]+Bve[e[t+3]]+"-"+Bve[e[t+4]]+Bve[e[t+5]]+"-"+Bve[e[t+6]]+Bve[e[t+7]]+"-"+Bve[e[t+8]]+Bve[e[t+9]]+"-"+Bve[e[t+10]]+Bve[e[t+11]]+Bve[e[t+12]]+Bve[e[t+13]]+Bve[e[t+14]]+Bve[e[t+15]]}var yYh=aa(require("crypto")),oef={randomUUID:yYh.default.randomUUID};function WgD(e,t,r){if(oef.randomUUID&&!t&&!e)return oef.randomUUID();e=e||{};let n=e.random||(e.rng||aef)();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 hYh(n)}var Ept=WgD;var HgD="id",GgD=".fern",Azo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new SQa(r),this.userId=t==null?void 0:mGl(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.83.2",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Kl(Q_.of((0,vYh.homedir)()),hu.of(GgD),hu.of(HgD));await qv(t)||(await(0,CQa.mkdir)((0,bYh.dirname)(t),{recursive:!0}),await(0,CQa.writeFile)(t,Ept())),this.persistedDistinctId=(await(0,CQa.readFile)(t)).toString()}return this.persistedDistinctId}};var sef;async function IQa(){return sef==null&&(sef=await JgD()),sef}async function JgD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Ozo;let r=await Bau();return r!=null?new Azo({token:r,posthogApiKey:e}):await I8a()!=null?new Odu({posthogApiKey:e}):new Azo({token:void 0,posthogApiKey:e})}catch{return new Ozo}}function Pzo(e,t){return function(){return e.apply(t,arguments)}}var{toString:KgD}=Object.prototype,{getPrototypeOf:cef}=Object,{iterator:jdu,toStringTag:mYh}=Symbol,Edu=(e=>t=>{let r=KgD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),TIr=e=>(e=e.toLowerCase(),t=>Edu(t)===e),Sdu=e=>t=>typeof t===e,{isArray:BQa}=Array,MQa=Sdu("undefined");function wzo(e){return e!==null&&!MQa(e)&&e.constructor!==null&&!MQa(e.constructor)&&pxe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var OYh=TIr("ArrayBuffer");function $gD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&OYh(e.buffer),t}var YgD=Sdu("string"),pxe=Sdu("function"),AYh=Sdu("number"),jzo=e=>e!==null&&typeof e=="object",XgD=e=>e===!0||e===!1,wdu=e=>{if(Edu(e)!=="object")return!1;let t=cef(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(mYh in e)&&!(jdu in e)},ZgD=e=>{if(!jzo(e)||wzo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},kgD=TIr("Date"),e0D=TIr("File"),t0D=TIr("Blob"),r0D=TIr("FileList"),n0D=e=>jzo(e)&&pxe(e.pipe),i0D=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||pxe(e.append)&&((t=Edu(e))==="formdata"||t==="object"&&pxe(e.toString)&&e.toString()==="[object FormData]"))},a0D=TIr("URLSearchParams"),[o0D,s0D,u0D,c0D]=["ReadableStream","Request","Response","Headers"].map(TIr),l0D=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ezo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),BQa(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(wzo(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 PYh(e,t){if(wzo(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 FYi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,wYh=e=>!MQa(e)&&e!==FYi;function uef(){let{caseless:e,skipUndefined:t}=wYh(this)&&this||{},r={},n=(i,a)=>{let o=e&&PYh(r,a)||a;wdu(r[o])&&wdu(i)?r[o]=uef(r[o],i):wdu(i)?r[o]=uef({},i):BQa(i)?r[o]=i.slice():(!t||!MQa(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&Ezo(arguments[i],n);return r}var f0D=(e,t,r,{allOwnKeys:n}={})=>(Ezo(t,(i,a)=>{r&&pxe(i)?e[a]=Pzo(i,r):e[a]=i},{allOwnKeys:n}),e),d0D=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),p0D=(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)},_0D=(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&&cef(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},h0D=(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},y0D=e=>{if(!e)return null;if(BQa(e))return e;let t=e.length;if(!AYh(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},v0D=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&cef(Uint8Array)),b0D=(e,t)=>{let n=(e&&e[jdu]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},g0D=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},m0D=TIr("HTMLFormElement"),O0D=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),gYh=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),A0D=TIr("RegExp"),jYh=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};Ezo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},P0D=e=>{jYh(e,(t,r)=>{if(pxe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(pxe(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+"'")})}})},w0D=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return BQa(e)?n(e):n(String(e).split(t)),r},j0D=()=>{},E0D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function S0D(e){return!!(e&&pxe(e.append)&&e[mYh]==="FormData"&&e[jdu])}var D0D=e=>{let t=new Array(10),r=(n,i)=>{if(jzo(n)){if(t.indexOf(n)>=0)return;if(wzo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=BQa(n)?[]:{};return Ezo(n,(o,c)=>{let f=r(o,i+1);!MQa(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},C0D=TIr("AsyncFunction"),I0D=e=>e&&(jzo(e)||pxe(e))&&pxe(e.then)&&pxe(e.catch),EYh=((e,t)=>e?setImmediate:t?((r,n)=>(FYi.addEventListener("message",({source:i,data:a})=>{i===FYi&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),FYi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",pxe(FYi.postMessage)),M0D=typeof queueMicrotask<"u"?queueMicrotask.bind(FYi):typeof process<"u"&&process.nextTick||EYh,B0D=e=>e!=null&&pxe(e[jdu]),$f={isArray:BQa,isArrayBuffer:OYh,isBuffer:wzo,isFormData:i0D,isArrayBufferView:$gD,isString:YgD,isNumber:AYh,isBoolean:XgD,isObject:jzo,isPlainObject:wdu,isEmptyObject:ZgD,isReadableStream:o0D,isRequest:s0D,isResponse:u0D,isHeaders:c0D,isUndefined:MQa,isDate:kgD,isFile:e0D,isBlob:t0D,isRegExp:A0D,isFunction:pxe,isStream:n0D,isURLSearchParams:a0D,isTypedArray:v0D,isFileList:r0D,forEach:Ezo,merge:uef,extend:f0D,trim:l0D,stripBOM:d0D,inherits:p0D,toFlatObject:_0D,kindOf:Edu,kindOfTest:TIr,endsWith:h0D,toArray:y0D,forEachEntry:b0D,matchAll:g0D,isHTMLForm:m0D,hasOwnProperty:gYh,hasOwnProp:gYh,reduceDescriptors:jYh,freezeMethods:P0D,toObjectSet:w0D,toCamelCase:O0D,noop:j0D,toFiniteNumber:E0D,findKey:PYh,global:FYi,isContextDefined:wYh,isSpecCompliantForm:S0D,toJSONObject:D0D,isAsyncFn:C0D,isThenable:I0D,setImmediate:EYh,asap:M0D,isIterable:B0D};function TQa(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)}$f.inherits(TQa,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:$f.toJSONObject(this.config),code:this.code,status:this.status}}});var SYh=TQa.prototype,DYh={};["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=>{DYh[e]={value:e}});Object.defineProperties(TQa,DYh);Object.defineProperty(SYh,"isAxiosError",{value:!0});TQa.from=(e,t,r,n,i,a)=>{let o=Object.create(SYh);$f.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 TQa.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 _m=TQa;var CYh=aa(Yfu(),1),Ddu=CYh.default;function lef(e){return $f.isPlainObject(e)||$f.isArray(e)}function MYh(e){return $f.endsWith(e,"[]")?e.slice(0,-2):e}function IYh(e,t,r){return e?e.concat(t).map(function(i,a){return i=MYh(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function T0D(e){return $f.isArray(e)&&!e.some(lef)}var q0D=$f.toFlatObject($f,{},null,function(t){return/^is[A-Z]/.test(t)});function R0D(e,t,r){if(!$f.isObject(e))throw new TypeError("target must be an object");t=t||new(Ddu||FormData),r=$f.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!$f.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||s,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&$f.isSpecCompliantForm(t);if(!$f.isFunction(i))throw new TypeError("visitor must be a function");function u(P){if(P===null)return"";if($f.isDate(P))return P.toISOString();if($f.isBoolean(P))return P.toString();if(!f&&$f.isBlob(P))throw new _m("Blob is not supported. Use a Buffer instead.");return $f.isArrayBuffer(P)||$f.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function s(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if($f.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if($f.isArray(P)&&T0D(P)||($f.isFileList(P)||$f.endsWith(C,"[]"))&&(T=$f.toArray(P)))return C=MYh(C),T.forEach(function(U,R){!($f.isUndefined(U)||U===null)&&t.append(o===!0?IYh([C],R,a):o===null?C:C+"[]",u(U))}),!1}return lef(P)?!0:(t.append(IYh(M,C,a),u(P)),!1)}let l=[],m=Object.assign(q0D,{defaultVisitor:s,convertValue:u,isVisitable:lef});function A(P,C){if(!$f.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),$f.forEach(P,function(T,z){(!($f.isUndefined(T)||T===null)&&i.call(t,T,$f.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!$f.isObject(e))throw new TypeError("data must be an object");return A(e),t}var WIi=R0D;function BYh(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function TYh(e,t){this._pairs=[],e&&WIi(e,this,t)}var qYh=TYh.prototype;qYh.append=function(t,r){this._pairs.push([t,r])};qYh.toString=function(t){let r=t?function(n){return t.call(this,n,BYh)}:BYh;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var RYh=TYh;function N0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function zYi(e,t,r){if(!t)return e;let n=r&&r.encode||N0D;$f.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=$f.isURLSearchParams(t)?t.toString():new RYh(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var fef=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){$f.forEach(this.handlers,function(n){n!==null&&t(n)})}},def=fef;var qQa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var zYh=aa(require("crypto"),1);var NYh=aa(require("url"),1),xYh=NYh.default.URLSearchParams;var pef="abcdefghijklmnopqrstuvwxyz",FYh="0123456789",QYh={DIGIT:FYh,ALPHA:pef,ALPHA_DIGIT:pef+pef.toUpperCase()+FYh},x0D=(e=16,t=QYh.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);zYh.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},LYh={isNode:!0,classes:{URLSearchParams:xYh,FormData:Ddu,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:QYh,generateString:x0D,protocols:["http","https","file","data"]};var yef={};lf(yef,{hasBrowserEnv:()=>hef,hasStandardBrowserEnv:()=>F0D,hasStandardBrowserWebWorkerEnv:()=>z0D,navigator:()=>_ef,origin:()=>Q0D});var hef=typeof window<"u"&&typeof document<"u",_ef=typeof navigator=="object"&&navigator||void 0,F0D=hef&&(!_ef||["ReactNative","NativeScript","NS"].indexOf(_ef.product)<0),z0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Q0D=hef&&window.location.href||"http://localhost";var p4={...yef,...LYh};function vef(e,t){return WIi(e,new p4.classes.URLSearchParams,{visitor:function(r,n,i,a){return p4.isNode&&$f.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function L0D(e){return $f.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function U0D(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 V0D(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&&$f.isArray(i)?i.length:o,f?($f.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!$f.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&$f.isArray(i[o])&&(i[o]=U0D(i[o])),!c)}if($f.isFormData(e)&&$f.isFunction(e.entries)){let r={};return $f.forEachEntry(e,(n,i)=>{t(L0D(n),i,r,0)}),r}return null}var Cdu=V0D;function W0D(e,t,r){if($f.isString(e))try{return(t||JSON.parse)(e),$f.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var bef={transitional:qQa,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=$f.isObject(t);if(a&&$f.isHTMLForm(t)&&(t=new FormData(t)),$f.isFormData(t))return i?JSON.stringify(Cdu(t)):t;if($f.isArrayBuffer(t)||$f.isBuffer(t)||$f.isStream(t)||$f.isFile(t)||$f.isBlob(t)||$f.isReadableStream(t))return t;if($f.isArrayBufferView(t))return t.buffer;if($f.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 vef(t,this.formSerializer).toString();if((c=$f.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return WIi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),W0D(t)):t}],transformResponse:[function(t){let r=this.transitional||bef.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if($f.isResponse(t)||$f.isReadableStream(t))return t;if(t&&$f.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"?_m.from(c,_m.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:p4.classes.FormData,Blob:p4.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$f.forEach(["delete","get","head","post","put","patch"],e=>{bef.headers[e]={}});var RQa=bef;var H0D=$f.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"]),UYh=e=>{let t={},r,n,i;return e&&e.split(`
|
|
2162
2162
|
`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||t[r]&&H0D[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var VYh=Symbol("internals");function Szo(e){return e&&String(e).trim().toLowerCase()}function Idu(e){return e===!1||e==null?e:$f.isArray(e)?e.map(Idu):String(e)}function G0D(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 J0D=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function gef(e,t,r,n,i){if($f.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!$f.isString(t)){if($f.isString(n))return t.indexOf(n)!==-1;if($f.isRegExp(n))return n.test(t)}}function K0D(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function $0D(e,t){let r=$f.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 NQa=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(c,f,u){let s=Szo(f);if(!s)throw new Error("header name must be a non-empty string");let l=$f.findKey(i,s);(!l||i[l]===void 0||u===!0||u===void 0&&i[l]!==!1)&&(i[l||f]=Idu(c))}let o=(c,f)=>$f.forEach(c,(u,s)=>a(u,s,f));if($f.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if($f.isString(t)&&(t=t.trim())&&!J0D(t))o(UYh(t),r);else if($f.isObject(t)&&$f.isIterable(t)){let c={},f,u;for(let s of t){if(!$f.isArray(s))throw TypeError("Object iterator must return a key-value pair");c[u=s[0]]=(f=c[u])?$f.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=Szo(t),t){let n=$f.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return G0D(i);if($f.isFunction(r))return r.call(this,i,n);if($f.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Szo(t),t){let n=$f.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||gef(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(o){if(o=Szo(o),o){let c=$f.findKey(n,o);c&&(!r||gef(n,n[c],c,r))&&(delete n[c],i=!0)}}return $f.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||gef(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return $f.forEach(this,(i,a)=>{let o=$f.findKey(n,a);if(o){r[o]=Idu(i),delete r[a];return}let c=t?K0D(a):String(a).trim();c!==a&&delete r[a],r[c]=Idu(i),n[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return $f.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&$f.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(`
|
|
2163
2163
|
`)}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[VYh]=this[VYh]={accessors:{}}).accessors,i=this.prototype;function a(o){let c=Szo(o);n[c]||($0D(i,o),n[c]=!0)}return $f.isArray(t)?t.forEach(a):a(t),this}};NQa.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);$f.reduceDescriptors(NQa.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});$f.freezeMethods(NQa);var CK=NQa;function Dzo(e,t){let r=this||RQa,n=t||r,i=CK.from(n.headers),a=n.data;return $f.forEach(e,function(c){a=c.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function Czo(e){return!!(e&&e.__CANCEL__)}function WYh(e,t,r){_m.call(this,e??"canceled",_m.ERR_CANCELED,t,r),this.name="CanceledError"}$f.inherits(WYh,_m,{__CANCEL__:!0});var Htt=WYh;function G5r(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new _m("Request failed with status code "+r.status,[_m.ERR_BAD_REQUEST,_m.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function mef(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Oef(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function QYi(e,t,r){let n=!mef(t);return e&&(n||r==!1)?Oef(e,t):t}var oXh=aa(Xfu(),1),sXh=aa(require("http"),1),uXh=aa(require("https"),1),cXh=aa(require("util"),1),lXh=aa(Akl(),1),Yfi=aa(require("zlib"),1);var LYi="1.12.2";function Izo(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var Y0D=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Aef(e,t,r){let n=r&&r.Blob||p4.classes.Blob,i=Izo(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=Y0D.exec(e);if(!a)throw new _m("Invalid URL",_m.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 _m("Blob is not supported",_m.ERR_NOT_SUPPORT);return new n([u],{type:o})}return u}throw new _m("Unsupported protocol "+i,_m.ERR_NOT_SUPPORT)}var VYi=aa(require("stream"),1);var HYh=aa(require("stream"),1);var Pef=Symbol("internals"),wef=class extends HYh.default.Transform{constructor(t){t=$f.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!$f.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[Pef]={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[Pef];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[Pef],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),M=null,T=o,z,U=0;if(a){let R=Date.now();(!i.ts||(U=R-i.ts)>=c)&&(i.ts=R,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&&(M=A.subarray(T),A=A.subarray(0,T)),l(A,M?()=>{process.nextTick(P,null,M)}:P)};m(t,function A(P,C){if(P)return n(P);C?m(C,A):n(null)})}},jef=wef;var fXh=require("events");var JYh=aa(require("util"),1),KYh=require("stream");var{asyncIterator:GYh}=Symbol,X0D=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[GYh]?yield*e[GYh]():yield e},Mdu=X0D;var Z0D=p4.ALPHABET.ALPHA_DIGIT+"-_",Mzo=typeof TextEncoder=="function"?new TextEncoder:new JYh.default.TextEncoder,UYi=`\r
|
|
2164
2164
|
`,k0D=Mzo.encode(UYi),emD=2,Eef=class{constructor(t,r){let{escapeName:n}=this.constructor,i=$f.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${UYi}`;i?r=Mzo.encode(String(r).replace(/\r?\n|\r\n?/g,UYi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${UYi}`,this.headers=Mzo.encode(a+UYi),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+emD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;$f.isTypedArray(t)?yield t:yield*Mdu(t),yield k0D}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},tmD=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+p4.generateString(i,Z0D)}=r||{};if(!$f.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=Mzo.encode("--"+a+UYi),c=Mzo.encode("--"+a+"--"+UYi),f=c.byteLength,u=Array.from(e.entries()).map(([l,m])=>{let A=new Eef(l,m);return f+=A.size,A});f+=o.byteLength*u.length,f=$f.toFiniteNumber(f);let s={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(s["Content-Length"]=f),t&&t(s),KYh.Readable.from((async function*(){for(let l of u)yield o,yield*l.encode();yield c})())},$Yh=tmD;var YYh=aa(require("stream"),1),Sef=class extends YYh.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)}},XYh=Sef;var rmD=(e,t)=>$f.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,ZYh=rmD;function nmD(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 kYh=nmD;function imD(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 eXh=imD;var $fi=(e,t,r=3)=>{let n=0,i=kYh(50,250);return eXh(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)},xQa=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},FQa=e=>(...t)=>$f.asap(()=>e(...t));function Def(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 tXh={flush:Yfi.default.constants.Z_SYNC_FLUSH,finishFlush:Yfi.default.constants.Z_SYNC_FLUSH},amD={flush:Yfi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Yfi.default.constants.BROTLI_OPERATION_FLUSH},rXh=$f.isFunction(Yfi.default.createBrotliDecompress),{http:omD,https:smD}=lXh.default,umD=/https:?/,nXh=p4.protocols.map(e=>e+":"),iXh=(e,[t,r])=>(e.on("end",r).on("error",r),t);function cmD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function dXh(e,t,r){let n=t;if(!n&&n!==!1){let i=oXh.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){dXh(a,t,a.href)}}var lmD=typeof process<"u"&&$f.kindOf(process)==="process",fmD=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)}),dmD=({address:e,family:t})=>{if(!$f.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},aXh=(e,t)=>dmD($f.isObject(e)?e:{address:e,family:t}),pXh=lmD&&function(t){return fmD(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=ZYh(c,St=>$f.isArray(St)?St:[St]);c=(St,_t,qe)=>{Se(St,_t,(De,Qt,Xe)=>{if(De)return qe(De);let Xt=$f.isArray(Qt)?Qt.map(Mt=>aXh(Mt)):[aXh(Qt,Xe)];_t.all?qe(De,Xt):qe(De,Xt[0].address,Xt[0].family)})}}let C=new fXh.EventEmitter,M=()=>{t.cancelToken&&t.cancelToken.unsubscribe(T),t.signal&&t.signal.removeEventListener("abort",T),C.removeAllListeners()};a((Se,St)=>{m=!0,St&&(A=!0,M())});function T(Se){C.emit("abort",!Se||Se.type?new Htt(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=QYi(t.baseURL,t.url,t.allowAbsoluteUrls),U=new URL(z,p4.hasBrowserEnv?p4.origin:void 0),R=U.protocol||nXh[0];if(R==="data:"){if(t.maxContentLength>-1){let St=String(t.url||z||"");if(Def(St)>t.maxContentLength)return i(new _m("maxContentLength size of "+t.maxContentLength+" exceeded",_m.ERR_BAD_RESPONSE,t))}let Se;if(l!=="GET")return G5r(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=Aef(t.url,u==="blob",{Blob:t.env&&t.env.Blob})}catch(St){throw _m.from(St,_m.ERR_BAD_REQUEST,t)}return u==="text"?(Se=Se.toString(s),(!s||s==="utf8")&&(Se=$f.stripBOM(Se))):u==="stream"&&(Se=VYi.default.Readable.from(Se)),G5r(n,i,{data:Se,status:200,statusText:"OK",headers:new CK,config:t})}if(nXh.indexOf(R)===-1)return i(new _m("Unsupported protocol "+R,_m.ERR_BAD_REQUEST,t));let V=CK.from(t.headers).normalize();V.set("User-Agent","axios/"+LYi,!1);let{onUploadProgress:$,onDownloadProgress:re}=t,Y=t.maxRate,te,ne;if($f.isSpecCompliantForm(o)){let Se=V.getContentType(/boundary=([-_\w\d]{10,70})/i);o=$Yh(o,St=>{V.set(St)},{tag:`axios-${LYi}-boundary`,boundary:Se&&Se[1]||void 0})}else if($f.isFormData(o)&&$f.isFunction(o.getHeaders)){if(V.set(o.getHeaders()),!V.hasContentLength())try{let Se=await cXh.default.promisify(o.getLength).call(o);Number.isFinite(Se)&&Se>=0&&V.setContentLength(Se)}catch{}}else if($f.isBlob(o)||$f.isFile(o))o.size&&V.setContentType(o.type||"application/octet-stream"),V.setContentLength(o.size||0),o=VYi.default.Readable.from(Mdu(o));else if(o&&!$f.isStream(o)){if(!Buffer.isBuffer(o))if($f.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if($f.isString(o))o=Buffer.from(o,"utf-8");else return i(new _m("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",_m.ERR_BAD_REQUEST,t));if(V.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return i(new _m("Request body larger than maxBodyLength limit",_m.ERR_BAD_REQUEST,t))}let Oe=$f.toFiniteNumber(V.getContentLength());$f.isArray(Y)?(te=Y[0],ne=Y[1]):te=ne=Y,o&&($||te)&&($f.isStream(o)||(o=VYi.default.Readable.from(o,{objectMode:!1})),o=VYi.default.pipeline([o,new jef({maxRate:$f.toFiniteNumber(te)})],$f.noop),$&&o.on("progress",iXh(o,xQa(Oe,$fi(FQa($),!1,3)))));let ge;if(t.auth){let Se=t.auth.username||"",St=t.auth.password||"";ge=Se+":"+St}if(!ge&&U.username){let Se=U.username,St=U.password;ge=Se+":"+St}ge&&V.delete("authorization");let ve;try{ve=zYi(U.pathname+U.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Se){let St=new Error(Se.message);return St.config=t,St.url=t.url,St.exists=!0,i(St)}V.set("Accept-Encoding","gzip, compress, deflate"+(rXh?", br":""),!1);let be={path:ve,method:l,headers:V.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:ge,protocol:R,family:f,beforeRedirect:cmD,beforeRedirects:{}};!$f.isUndefined(c)&&(be.lookup=c),t.socketPath?be.socketPath=t.socketPath:(be.hostname=U.hostname.startsWith("[")?U.hostname.slice(1,-1):U.hostname,be.port=U.port,dXh(be,t.proxy,R+"//"+U.hostname+(U.port?":"+U.port:"")+be.path));let Me,Be=umD.test(be.protocol);if(be.agent=Be?t.httpsAgent:t.httpAgent,t.transport?Me=t.transport:t.maxRedirects===0?Me=Be?uXh.default:sXh.default:(t.maxRedirects&&(be.maxRedirects=t.maxRedirects),t.beforeRedirect&&(be.beforeRedirects.config=t.beforeRedirect),Me=Be?smD:omD),t.maxBodyLength>-1?be.maxBodyLength=t.maxBodyLength:be.maxBodyLength=1/0,t.insecureHTTPParser&&(be.insecureHTTPParser=t.insecureHTTPParser),P=Me.request(be,function(St){if(P.destroyed)return;let _t=[St],qe=+St.headers["content-length"];if(re||ne){let Mt=new jef({maxRate:$f.toFiniteNumber(ne)});re&&Mt.on("progress",iXh(Mt,xQa(qe,$fi(FQa(re),!0,3)))),_t.push(Mt)}let De=St,Qt=St.req||P;if(t.decompress!==!1&&St.headers["content-encoding"])switch((l==="HEAD"||St.statusCode===204)&&delete St.headers["content-encoding"],(St.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":_t.push(Yfi.default.createUnzip(tXh)),delete St.headers["content-encoding"];break;case"deflate":_t.push(new XYh),_t.push(Yfi.default.createUnzip(tXh)),delete St.headers["content-encoding"];break;case"br":rXh&&(_t.push(Yfi.default.createBrotliDecompress(amD)),delete St.headers["content-encoding"])}De=_t.length>1?VYi.default.pipeline(_t,$f.noop):_t[0];let Xe=VYi.default.finished(De,()=>{Xe(),M()}),Xt={status:St.statusCode,statusText:St.statusMessage,headers:new CK(St.headers),config:t,request:Qt};if(u==="stream")Xt.data=De,G5r(n,i,Xt);else{let Mt=[],Ke=0;De.on("data",function(ur){Mt.push(ur),Ke+=ur.length,t.maxContentLength>-1&&Ke>t.maxContentLength&&(A=!0,De.destroy(),i(new _m("maxContentLength size of "+t.maxContentLength+" exceeded",_m.ERR_BAD_RESPONSE,t,Qt)))}),De.on("aborted",function(){if(A)return;let ur=new _m("stream has been aborted",_m.ERR_BAD_RESPONSE,t,Qt);De.destroy(ur),i(ur)}),De.on("error",function(ur){P.destroyed||i(_m.from(ur,null,t,Qt))}),De.on("end",function(){try{let ur=Mt.length===1?Mt[0]:Buffer.concat(Mt);u!=="arraybuffer"&&(ur=ur.toString(s),(!s||s==="utf8")&&(ur=$f.stripBOM(ur))),Xt.data=ur}catch(ur){return i(_m.from(ur,null,t,Xt.request,Xt))}G5r(n,i,Xt)})}C.once("abort",Mt=>{De.destroyed||(De.emit("error",Mt),De.destroy())})}),C.once("abort",Se=>{i(Se),P.destroy(Se)}),P.on("error",function(St){i(_m.from(St,null,t,P))}),P.on("socket",function(St){St.setKeepAlive(!0,1e3*60)}),t.timeout){let Se=parseInt(t.timeout,10);if(Number.isNaN(Se)){i(new _m("error trying to parse `config.timeout` to int",_m.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(Se,function(){if(m)return;let _t=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",qe=t.transitional||qQa;t.timeoutErrorMessage&&(_t=t.timeoutErrorMessage),i(new _m(_t,qe.clarifyTimeoutError?_m.ETIMEDOUT:_m.ECONNABORTED,t,P)),T()})}if($f.isStream(o)){let Se=!1,St=!1;o.on("end",()=>{Se=!0}),o.once("error",_t=>{St=!0,P.destroy(_t)}),o.on("close",()=>{!Se&&!St&&T(new Htt("Request stream has been aborted",t,P))}),o.pipe(P)}else P.end(o)})};var _Xh=p4.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,p4.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(p4.origin),p4.navigator&&/(msie|trident)/i.test(p4.navigator.userAgent)):()=>!0;var hXh=p4.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let o=[e+"="+encodeURIComponent(t)];$f.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),$f.isString(n)&&o.push("path="+n),$f.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 yXh=e=>e instanceof CK?{...e}:e;function qIr(e,t){t=t||{};let r={};function n(u,s,l,m){return $f.isPlainObject(u)&&$f.isPlainObject(s)?$f.merge.call({caseless:m},u,s):$f.isPlainObject(s)?$f.merge({},s):$f.isArray(s)?s.slice():s}function i(u,s,l,m){if($f.isUndefined(s)){if(!$f.isUndefined(u))return n(void 0,u,l,m)}else return n(u,s,l,m)}function a(u,s){if(!$f.isUndefined(s))return n(void 0,s)}function o(u,s){if($f.isUndefined(s)){if(!$f.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(yXh(u),yXh(s),l,!0)};return $f.forEach(Object.keys({...e,...t}),function(s){let l=f[s]||i,m=l(e[s],t[s],s);$f.isUndefined(m)&&l!==c||(r[s]=m)}),r}var Bdu=e=>{let t=qIr({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=CK.from(o),t.url=zYi(QYi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),$f.isFormData(r)){if(p4.hasStandardBrowserEnv||p4.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if($f.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(p4.hasStandardBrowserEnv&&(n&&$f.isFunction(n)&&(n=n(t)),n||n!==!1&&_Xh(t.url))){let f=i&&a&&hXh.read(a);f&&o.set(i,f)}return t};var pmD=typeof XMLHttpRequest<"u",vXh=pmD&&function(e){return new Promise(function(r,n){let i=Bdu(e),a=i.data,o=CK.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 M=new XMLHttpRequest;M.open(i.method.toUpperCase(),i.url,!0),M.timeout=i.timeout;function T(){if(!M)return;let U=CK.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),V={data:!c||c==="text"||c==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:U,config:e,request:M};G5r(function(re){r(re),C()},function(re){n(re),C()},V),M=null}"onloadend"in M?M.onloadend=T:M.onreadystatechange=function(){!M||M.readyState!==4||M.status===0&&!(M.responseURL&&M.responseURL.indexOf("file:")===0)||setTimeout(T)},M.onabort=function(){M&&(n(new _m("Request aborted",_m.ECONNABORTED,e,M)),M=null)},M.onerror=function(R){let V=R&&R.message?R.message:"Network Error",$=new _m(V,_m.ERR_NETWORK,e,M);$.event=R||null,n($),M=null},M.ontimeout=function(){let R=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",V=i.transitional||qQa;i.timeoutErrorMessage&&(R=i.timeoutErrorMessage),n(new _m(R,V.clarifyTimeoutError?_m.ETIMEDOUT:_m.ECONNABORTED,e,M)),M=null},a===void 0&&o.setContentType(null),"setRequestHeader"in M&&$f.forEach(o.toJSON(),function(R,V){M.setRequestHeader(V,R)}),$f.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),c&&c!=="json"&&(M.responseType=i.responseType),u&&([m,P]=$fi(u,!0),M.addEventListener("progress",m)),f&&M.upload&&([l,A]=$fi(f),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",A)),(i.cancelToken||i.signal)&&(s=U=>{M&&(n(!U||U.type?new Htt(null,e,M):U),M.abort(),M=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));let z=Izo(i.url);if(z&&p4.protocols.indexOf(z)===-1){n(new _m("Unsupported protocol "+z+":",_m.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var _mD=(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 _m?s:new Htt(s instanceof Error?s.message:s))}},o=t&&setTimeout(()=>{o=null,a(new _m(`timeout ${t} of ms exceeded`,_m.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=()=>$f.asap(c),f}},bXh=_mD;var hmD=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},ymD=async function*(e,t){for await(let r of vmD(e))yield*hmD(r,t)},vmD=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()}},Cef=(e,t,r,n)=>{let i=ymD(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 gXh=64*1024,{isFunction:Tdu}=$f,bmD=(({Request:e,Response:t})=>({Request:e,Response:t}))($f.global),{ReadableStream:mXh,TextEncoder:OXh}=$f.global,AXh=(e,...t)=>{try{return!!e(...t)}catch{return!1}},gmD=e=>{e=$f.merge.call({skipUndefined:!0},bmD,e);let{fetch:t,Request:r,Response:n}=e,i=t?Tdu(t):typeof fetch=="function",a=Tdu(r),o=Tdu(n);if(!i)return!1;let c=i&&Tdu(mXh),f=i&&(typeof OXh=="function"?(P=>C=>P.encode(C))(new OXh):async P=>new Uint8Array(await new r(P).arrayBuffer())),u=a&&c&&AXh(()=>{let P=!1,C=new r(p4.origin,{body:new mXh,method:"POST",get duplex(){return P=!0,"half"}}).headers.has("Content-Type");return P&&!C}),s=o&&c&&AXh(()=>$f.isReadableStream(new n("").body)),l={stream:s&&(P=>P.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(P=>{!l[P]&&(l[P]=(C,M)=>{let T=C&&C[P];if(T)return T.call(C);throw new _m(`Response type '${P}' is not supported`,_m.ERR_NOT_SUPPORT,M)})});let m=async P=>{if(P==null)return 0;if($f.isBlob(P))return P.size;if($f.isSpecCompliantForm(P))return(await new r(p4.origin,{method:"POST",body:P}).arrayBuffer()).byteLength;if($f.isArrayBufferView(P)||$f.isArrayBuffer(P))return P.byteLength;if($f.isURLSearchParams(P)&&(P=P+""),$f.isString(P))return(await f(P)).byteLength},A=async(P,C)=>{let M=$f.toFiniteNumber(P.getContentLength());return M??m(C)};return async P=>{let{url:C,method:M,data:T,signal:z,cancelToken:U,timeout:R,onDownloadProgress:V,onUploadProgress:$,responseType:re,headers:Y,withCredentials:te="same-origin",fetchOptions:ne}=Bdu(P),Oe=t||fetch;re=re?(re+"").toLowerCase():"text";let ge=bXh([z,U&&U.toAbortSignal()],R),ve=null,be=ge&&ge.unsubscribe&&(()=>{ge.unsubscribe()}),Me;try{if($&&u&&M!=="get"&&M!=="head"&&(Me=await A(Y,T))!==0){let De=new r(C,{method:"POST",body:T,duplex:"half"}),Qt;if($f.isFormData(T)&&(Qt=De.headers.get("content-type"))&&Y.setContentType(Qt),De.body){let[Xe,Xt]=xQa(Me,$fi(FQa($)));T=Cef(De.body,gXh,Xe,Xt)}}$f.isString(te)||(te=te?"include":"omit");let Be=a&&"credentials"in r.prototype,Se={...ne,signal:ge,method:M.toUpperCase(),headers:Y.normalize().toJSON(),body:T,duplex:"half",credentials:Be?te:void 0};ve=a&&new r(C,Se);let St=await(a?Oe(ve,ne):Oe(C,Se)),_t=s&&(re==="stream"||re==="response");if(s&&(V||_t&&be)){let De={};["status","statusText","headers"].forEach(Mt=>{De[Mt]=St[Mt]});let Qt=$f.toFiniteNumber(St.headers.get("content-length")),[Xe,Xt]=V&&xQa(Qt,$fi(FQa(V),!0))||[];St=new n(Cef(St.body,gXh,Xe,()=>{Xt&&Xt(),be&&be()}),De)}re=re||"text";let qe=await l[$f.findKey(l,re)||"text"](St,P);return!_t&&be&&be(),await new Promise((De,Qt)=>{G5r(De,Qt,{data:qe,headers:CK.from(St.headers),status:St.status,statusText:St.statusText,config:P,request:ve})})}catch(Be){throw be&&be(),Be&&Be.name==="TypeError"&&/Load failed|fetch/i.test(Be.message)?Object.assign(new _m("Network Error",_m.ERR_NETWORK,P,ve),{cause:Be.cause||Be}):_m.from(Be,Be&&Be.code,P,ve)}}},mmD=new Map,Ief=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=mmD;for(;c--;)f=a[c],u=s.get(f),u===void 0&&s.set(f,u=c?new Map:gmD(t)),s=u;return u},LeU=Ief();var Mef={http:pXh,xhr:vXh,fetch:{get:Ief}};$f.forEach(Mef,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var PXh=e=>`- ${e}`,AmD=e=>$f.isFunction(e)||e===null||e===!1,qdu={getAdapter:(e,t)=>{e=$f.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,!AmD(n)&&(i=Mef[(c=String(n)).toLowerCase()],i===void 0))throw new _m(`Unknown adapter '${c}'`);if(i&&($f.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 :
|
|
@@ -2357,7 +2357,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2357
2357
|
1. you did not perform an installation for Firefox before running the script (e.g. \`npx puppeteer browsers install firefox\`) or
|
|
2358
2358
|
2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
|
|
2359
2359
|
For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n}};var Fgy=aa(require("fs"),1);var vJD={force:!0,recursive:!0,maxRetries:5};async function h0u(e){await Fgy.default.promises.rm(e,vJD)}var y0u=class extends L9a{constructor(t){super(t,"chrome")}launch(t={}){return this.puppeteer.configuration.logLevel==="warn"&&process.platform==="darwin"&&process.arch==="x64"&&Ugy.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(`
|
|
2360
|
-
`)),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?(ry(!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,Lgy.mkdtemp)(this.getProfilePath())}`),s=f.length-1);let l=f[s].split("=",2)[1];ry(typeof l=="string","`--user-data-dir` is malformed");let m=c;return m||(ry(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 h0u(t)}catch(n){throw vv(n),n}}defaultArgs(t={}){let r=zgy("--disable-features",t.args);t.args&&r.length>0&&Qgy(t.args,"--disable-features");let i=["Translate","AcceptCHFrame","MediaRouter","OptimizationHints",...process.env.PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES==="true"?[]:["ProcessPerSiteUpToMainFrameThreshold","IsolateSandboxedIframes"],...r].filter(A=>A!==""),a=zgy("--enable-features",t.args);t.args&&a.length>0&&Qgy(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=${Vgy.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?f0u({browser:kj.CHROME,channel:bJD(t)}):this.resolveExecutablePath(void 0,r)}};function bJD(e){switch(e){case"chrome":return JF.STABLE;case"chrome-dev":return JF.DEV;case"chrome-beta":return JF.BETA;case"chrome-canary":return JF.CANARY}}function zgy(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 Qgy(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 Wgy=aa(require("fs"),1),U9a=require("fs/promises"),Hgy=aa(require("os"),1),Idf=aa(require("path"),1);FC();h7();var v0u=class e extends L9a{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&&ry(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,U9a.mkdtemp)(this.getProfilePath()),f.push("--profile"),f.push(u);await gdf(kj.FIREFOX,{path:u,preferences:e.getPreferences(o)});let m;return this.puppeteer._isPuppeteerCore||i?(ry(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 h0u(t)}catch(n){throw vv(n),n}else try{let n=".puppeteer",i=["prefs.js","user.js"],a=await Promise.allSettled(i.map(async o=>{let c=Idf.default.join(t,o+n);if(Wgy.default.existsSync(c)){let f=Idf.default.join(t,o);await(0,U9a.unlink)(f),await(0,U9a.rename)(c,f)}}));for(let o of a)if(o.status==="rejected")throw o.reason}catch(n){vv(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(Hgy.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 V9a=class extends _bu{#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=ZUa.firefox;break;default:this.configuration.defaultBrowser="chrome",this.defaultBrowserRevision=ZUa.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=ZUa.chrome;break;case"firefox":this.defaultBrowserRevision=ZUa.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 y0u(this);case"firefox":return new v0u(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=YIr();if(!t)throw new Error("The current platform is not supported.");let r=this.configuration.cacheDirectory,n=await Cdf({cacheDir:r}),i=[{product:"chrome",browser:kj.CHROME,currentBuildId:""},{product:"firefox",browser:kj.FIREFOX,currentBuildId:""}];for(let c of i){let f=this.configuration?.[c.product]?.version??ZUa[c.product];c.currentBuildId=await a0u(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 Ddf({browser:c.browser,platform:t,cacheDir:r,buildId:c.buildId}))}};var b0u=require("child_process"),Kgy=aa(require("fs"),1),$gy=aa(require("os"),1),Ygy=require("path"),Xgy=require("stream"),Zgy=aa(jk(),1);Vpt();mxe();FC();Bk();_7();var gJD=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},Ggy=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 M=(0,r[A])(c==="accessor"?{get:s.get,set:s.set}:s[f],P);if(c==="accessor"){if(M===void 0)continue;if(M===null||typeof M!="object")throw new TypeError("Object expected");(l=o(M.get))&&(s.get=l),(l=o(M.set))&&(s.set=l),(l=o(M.init))&&i.unshift(l)}else(l=o(M))&&(c==="field"?i.unshift(l):s[f]=l)}u&&Object.defineProperty(u,n.name,s),m=!0},mJD=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})},OJD=30,Jgy=30,AJD=(0,Zgy.default)("puppeteer:ffmpeg"),kgy=(()=>{let e=Xgy.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;Ggy(this,n={value:mJD(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),Ggy(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=gJD(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:M,quality:T,colors:z,path:U,overwrite:R}={}){super({allowHalfOpen:!1}),u??="ffmpeg",A??="webm",P??=Jgy,C||=-1,M??=-1,T??=OJD,z??=256,R??=!0,this.#i=P;let{error:V}=(0,b0u.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,M,T,z),Y=re.indexOf("-vf");Y!==-1&&$.push(re.splice(Y,2).at(-1)??""),U&&Kgy.default.mkdirSync((0,Ygy.dirname)(U),{recursive:R}),this.#t=(0,b0u.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()],[R?"-y":"-n"],"pipe:1"].flat(),{stdio:["pipe","pipe","pipe"]}),this.#t.stdout.pipe(this),this.#t.stderr.on("data",ne=>{AJD(ne.toString("utf8"))}),this.#e=o;let{client:te}=this.#e.mainFrame();te.once(Gx.Disconnected,()=>{this.stop().catch(vv)}),this.#n=Kcy(HF(te,"Page.screencastFrame").pipe(BXi(ne=>{te.send("Page.screencastFrameAck",{sessionId:ne.sessionId})}),ert(ne=>ne.metadata.timestamp!==void 0),p7(ne=>({buffer:Buffer.from(ne.data,"base64"),timestamp:ne.metadata.timestamp})),kcy(2,1),ely(([{timestamp:ne,buffer:Oe},{timestamp:ge}])=>XC(Array(Math.round(P*Math.max(ge-ne,0))).fill(Oe))),p7(ne=>(this.#o(ne),[ne,performance.now()])),ohu(zLa(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($gy.default.cpus().length/2,8)}`]];switch(o){case"webm":return[...m,["-f","webm"]].flat();case"gif":return c=Jgy===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(vv),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=[o4o()],i=[o4o()],Ik)](){await this.stop()}}})();var e0y=aa(require("fs"),1),t0y=aa(require("path"),1);gdi();NDe.value={fs:e0y.default,path:t0y.default,ScreenRecorder:kgy};var wJD=new V9a({isPuppeteerCore:!0}),{connect:gQU,defaultArgs:mQU,executablePath:OQU,launch:AQU}=wJD;var YOy=require("os"),XOy=require("path"),ZOy=aa($Oy(),1);function Xpf(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 vXD(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}function bXD(e){if(e&&!vXD(e))throw new Error(`Unsupported browser ${e}`);switch(e){case"firefox":return"firefox";default:return"chrome"}}function gXD(e){switch(e){case"silent":return"silent";case"error":return"error";default:return"warn"}}function Ypf(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=Xpf(`PUPPETEER_${i}_SKIP_DOWNLOAD`)??Xpf(`PUPPETEER_SKIP_${i}_DOWNLOAD`)??t[e]?.skipDownload??r.skipDownload,n}var kOy=()=>{let e=(0,ZOy.cosmiconfigSync)("puppeteer",{searchStrategy:"global"}).search(),t=e?e.config:{};return t.logLevel=gXD(process.env.PUPPETEER_LOGLEVEL??t.logLevel),t.defaultBrowser=bXD(process.env.PUPPETEER_BROWSER??t.defaultBrowser),t.executablePath=process.env.PUPPETEER_EXECUTABLE_PATH??t.executablePath,t.executablePath&&(t.skipDownload=!0),t.skipDownload=Xpf("PUPPETEER_SKIP_DOWNLOAD")??t.skipDownload,t.chrome=Ypf("chrome",t),t["chrome-headless-shell"]=Ypf("chrome-headless-shell",t),t.firefox=Ypf("firefox",t,{skipDownload:!0}),t.cacheDirectory=process.env.PUPPETEER_CACHE_DIR??t.cacheDirectory??(0,XOy.join)((0,YOy.homedir)(),".cache","puppeteer"),t.temporaryDirectory=process.env.PUPPETEER_TMP_DIR??t.temporaryDirectory,t.experiments??={},t};var mXD=kOy(),OXD=new V9a({isPuppeteerCore:!1,configuration:mXD}),{connect:eUU,defaultArgs:tUU,executablePath:rUU,launch:eAy,trimCache:nUU}=OXD;var AXD="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",PXD={"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 W7o(e,t=3,r=1e3,n=2){try{return await e()}catch(i){if(t>0)return await new Promise(a=>setTimeout(a,r)),W7o(e,t-1,r*n,n);throw i}}async function tAy(){try{return await eAy({headless:!0,args:["--ignore-certificate-errors"]})}catch{throw new Error("Could not create a Puppeteer instance")}}async function wXD(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(PXD),await r.setUserAgent(AXD),await r.setJavaScriptEnabled(!0),await W7o(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let n=await W7o(()=>r.content());return await r.close(),n}catch{throw new Error("Failed to download page from Puppeteer")}}async function jXD(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 Zpf({url:e,browser:t}){try{let r;if(t?r=await wXD(t,e):r=await W7o(()=>jXD(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function rAy(e){try{let t=await W7o(()=>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 EXD=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function nAy(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,tVa.join)(process.cwd(),"fern");try{let r=await SXD(e,(0,tVa.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function SXD(e,t){let r=CXD(e),n=(0,tVa.join)(t,r);if(!DXD(r))throw new Error(`${r} - file extension not supported`);if((0,z0u.existsSync)(n))return n;try{(0,z0u.mkdirSync)((0,tVa.dirname)(n),{recursive:!0})}catch{throw new Error(`${n} - failed to create directory`)}try{let i=await rAy(e);return ouy(n,i),n}catch{throw new Error(`${n}: failed to download file from source`)}}function DXD(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&&!EXD.includes(n))}function CXD(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 IXD(e){let t=[];return Dv(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 iAy(e,t){let r=xLa(e),n=IXD(r);if(n!=null){let i=await Promise.all(n.map(async a=>{let o=await nAy(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 aAy=28;async function oAy(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 iAy(a,r)))}let n=[...new Set(r).values()];if(n.length!==0){if(n.length===1&&n[0]!=null){let i=hu.of(aAe(n[0]));return{light:i,dark:i,height:aAy}}if(n[0]!=null&&n[1]!=null){let i=hu.of(aAe(n[0])),a=hu.of(aAe(n[1]));return{light:i,dark:a,height:aAy}}}}var Q0u=class extends YYi{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:Yzo});let n=await this.getHastForUrl(this.url),i=bcy(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=Kl(this.absolutePathToFernDirectory,hu.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 tAy(),o=await oAy(this.url,a);o!=null&&r.setLogo({logo:o});let c=await Uny(n);r.setTitle({title:c});let f=await Fny(n);if(f!=null){let s=await this.getAndCreateAssetsDirectory(),l=await fetch(f);if(l.ok){let m=Buffer.from(await l.arrayBuffer()),A=Kl(s,hu.of("favicon"));await(0,nBi.writeFile)(A,new Uint8Array(m)),r.setFavicon({favicon:JRe(this.absolutePathToFernDirectory,A)})}}let u=await mcy(n);r.setColors({colors:u}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Kl(this.absolutePathToFernDirectory,hu.of("assets"));return await(0,nBi.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=hcy(i);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let o=ycy(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 Zpf({url:t});return xLa(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,nBi.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 Zpf({url:o}),f=await _cy({logger:this.logger,html:c,url:o});if(f.success&&f.data){let u=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:i,page:a.slug});await(0,nBi.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=Kl(i,hu.of(l)),C=xg(P);await(0,nBi.mkdir)(C,{recursive:!0}),await(0,nBi.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:JRe(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 Kl(t,hu.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Kl(t,hu.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 sAy=require("fs/promises");async function kpf({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:n,organization:i}){let a=new XYi;a.setInstance({companyName:i}),await new Q0u({url:e,context:r,builder:a,absolutePathToFernDirectory:Kl(Q_.of(process.cwd()),hu.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,sAy.writeFile)(Kl(Q_.of(t),hu.of(Kye),hu.of(URe)),JSON.stringify({version:n,organization:i},void 0,4))}var e_f=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:n})=>{if(!e||!YJi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let i=Q_.of(D9());await kpf({readmeUrl:e,outputPath:i,taskContext:r,versionOfCli:n,organization:t})};var uAy="0.0.0";var cAy={[IP.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,bU(e)])),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.GenerationLanguage.SWIFT]:new Set([])};var BXD=["go","ruby"];function VDe({generationLanguage:e,keywords:t,smartCasing:r}){let n={generateName:(i,a)=>{let o=l=>({unsafeName:l,safeName:TXD({name:l,keywords:qXD({generationLanguage:e,keywords:t})})}),c=hA(i),f=bU(c),u=hJi(i),s=fJi(c);return r&&(!xXD(s)&&(e==null||BXD.includes(e))&&(c=s.map((l,m)=>{if(m>0){let A=L0u(l);if(A!=null)return A;if(U0u(l))return l.toUpperCase()}return l}).join(""),f=bU(s.map((l,m)=>{let A=L0u(l);return A??(U0u(l)?l.toUpperCase():m===0?bU(l):l)}).join(""))),u=i.split(" ").map(l=>l.split(/(\d+)/).map(hJi).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 TXD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":NXD(e)?"_"+e:e}function qXD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return cAy[e]}var RXD=/^[0-9]/;function NXD(e){return RXD.test(e)}function xXD(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=L0u(n)!=null||U0u(n),a=L0u(t)!=null||U0u(t);return i&&a})}function L0u(e){return zXD.get(e.toUpperCase())}function U0u(e){return FXD.has(e.toUpperCase())}var FXD=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"]),zXD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function t_f({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:EAe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return A$i(e.auth,{single:n=>{let i=lAy({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:EAe.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:EAe.Any,schemes:n.map(i=>lAy({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function lAy({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 VFo(c,{header:f=>o4.header({key:a,docs:o,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:vh.primitive({v1:MP.String,v2:Gg.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>fAy({key:a,casingsGenerator:r,docs:o,rawScheme:f}),tokenBearer:f=>V0u({key:a,casingsGenerator:r,docs:o,rawScheme:f}),inferredBearer(f){return V0u({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:f=>V0u({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return V0u({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return fAy({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function V0u({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return o4.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function fAy({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return o4.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 pX(e){let t=LXD(e),{value:r,done:n}=r_f(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...QXD(t)]}}function*QXD(e){let t;do{let{value:r}=r_f(e,"}"),n=r_f(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*LXD(e){for(let t of e)yield t}function r_f(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 H7o({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:r8r(n,{singleBaseUrl:()=>SG.singleBaseUrl(UXD({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>SG.multipleBaseUrls(VXD({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,a])=>[i,r8r(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function UXD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>r8r(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:dAy(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function VXD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>r8r(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:fg(a.urls,o=>dAy(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function dAy(e){return e.endsWith("/")?e.slice(0,-1):e}function G7o(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 NQr({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 pAy({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return xQr({containerType:t});switch(t.type){case"list":{let o=q8({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:wM.literal({literal:t.literal._visit({boolean:o=>s0.boolean(o),string:o=>s0.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 xQr({containerType:t});let o=q8({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return xQr({containerType:t});let o=q8({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=q8({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=q8({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),c=q8({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:fc(t)}}function xQr({containerType:e}){switch(e.type){case"list":return{type:"success",example:wM.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:wM.literal({literal:e.literal._visit({boolean:t=>s0.boolean(t),string:t=>s0.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:wM.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:wM.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:wM.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:wM.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:fc(e)}}function hAy({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return KXD({fieldName:e,default_:WXD(t.v2),validation:HXD(t.v2)});case"BASE_64":return{type:"success",example:s0.base64(rP.BASE64),jsonExample:rP.BASE64};case"BOOLEAN":return{type:"success",example:s0.boolean(rP.BOOLEAN),jsonExample:rP.BOOLEAN};case"DATE":return{type:"success",example:s0.date(rP.DATE),jsonExample:rP.DATE};case"DATE_TIME":return{type:"success",example:s0.datetime({datetime:new Date(rP.DATE_TIME),raw:rP.DATE_TIME}),jsonExample:rP.DATE_TIME};case"DOUBLE":return $XD({fieldName:e,validation:GXD(t.v2)});case"FLOAT":return{type:"success",example:s0.float(rP.FLOAT),jsonExample:rP.FLOAT};case"INTEGER":return YXD({fieldName:e,validation:JXD(t.v2)});case"UINT_64":return{type:"success",example:s0.uint64(rP.INT64),jsonExample:rP.INT64};case"UINT":return{type:"success",example:s0.uint(rP.UINT),jsonExample:rP.UINT};case"BIG_INTEGER":return{type:"success",example:s0.bigInteger(rP.INT64.toString()),jsonExample:`${rP.INT64}`};case"LONG":return{type:"success",example:s0.long(rP.INT64),jsonExample:rP.INT64};case"UUID":return{type:"success",example:s0.uuid(rP.UUID),jsonExample:rP.UUID};default:fc(t.v1)}}function WXD(e){if(e?.type==="string")return e.default}function HXD(e){if(e?.type==="string")return e.validation}function GXD(e){if(e?.type==="double")return e.validation}function JXD(e){if(e?.type==="integer")return e.validation}function _Ay(e){if(e<=rP.SAMPLE_STRINGS.length){let t=rP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return rP.SAMPLE_STRINGS[rP.SAMPLE_STRINGS.length-1]+".".repeat(e-rP.SAMPLE_STRINGS.length)}function KXD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:s0.string({original:t}),jsonExample:t};if(r){let i=r.minLength,a=r.maxLength;if(i){let o=_Ay(i);return{type:"success",example:s0.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=_Ay(a);return{type:"success",example:s0.string({original:o}),jsonExample:o}}}let n=e??rP.STRING;return{type:"success",example:s0.string({original:n}),jsonExample:n}}function $XD({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:s0.double(r),jsonExample:r};if(n)return{type:"success",example:s0.double(n),jsonExample:n}}return{type:"success",example:s0.double(rP.DOUBLE),jsonExample:rP.DOUBLE}}function YXD({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:s0.integer(r),jsonExample:r};if(n)return{type:"success",example:s0.integer(n),jsonExample:n}}return{type:"success",example:s0.integer(rP.INT),jsonExample:rP.INT}}function rVa({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=q8({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:MR.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:MR.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=rVa({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=XXD({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:MR.object({properties:[...c,...u.properties]}),jsonExample:Object.assign({},o,s)}}case"undiscriminatedUnion":{let o=0;for(let c of r.shape.members){let f=q8({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:MR.undiscriminatedUnion({index:o,singleUnionType:u}),jsonExample:s}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let u=q8({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});u.type==="success"&&(c[f.name.wireValue]=u.jsonExample)}for(let f of r.shape.types){let u=f.shape._visit({noProperties:()=>({type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.noProperties()}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,...c}}),samePropertiesAsObject:s=>{let l=t[s.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${s.typeId}`};let m=rVa({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(m==null)return{type:"failure",message:"Failed to generate example for type reference"};if(m.type==="failure")return m;let{example:A,jsonExample:P}=m;return{type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.samePropertiesAsObject({typeId:l.name.typeId,object:A.type==="object"?A:{properties:[]}})}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,...typeof P=="object"?P:{},...c}}},singleProperty:s=>{let l=q8({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:s.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:m,jsonExample:A}=l;return{type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.singleProperty(m)}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,[s.name.wireValue]:A,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(u.type!=="failure")return u}}}return{type:"failure",message:"Failed to generate example for type reference"}}function XXD({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=q8({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:o});if(s.type==="failure"&&!NQr({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:MR.object({properties:f}),jsonExample:c}}function q8({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=rVa({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:BP.named({shape:f,typeName:o.name})},jsonExample:u}}case"container":{let o=pAy({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure"){let{example:u,jsonExample:s}=xQr({containerType:t.container});return{type:"success",example:{jsonExample:s,shape:BP.container(u)},jsonExample:s}}let{example:c,jsonExample:f}=o;return{type:"success",example:{jsonExample:f,shape:BP.container(c)},jsonExample:f}}case"primitive":{let{jsonExample:o,example:c}=hAy({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:BP.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:BP.unknown(o)},jsonExample:o}}}}function EZi(e,t){let r=[];for(let n of e){let i=q8({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 nVa(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&NQr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=q8({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 W0u(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&NQr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=q8({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?Zoe.exploded():Zoe.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var n_f=vh.primitive({v1:MP.String,v2:Gg.string({default:void 0,validation:void 0})});function iVa({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:rQ.ok(jU.body(void 0)),docs:void 0},c=EZi(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let f=EZi(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;o.servicePathParameters=f.example;let u=EZi(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;o.rootPathParameters=u.example;let s=W0u(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(s.type==="failure")return s;o.queryParameters=s.example;let l=nVa(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let m=nVa(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 M=n[C.typeId];if(M==null)throw new Error(`Failed to find extended type declaration with id ${C.typeId}`);let T=rVa({typeDeclaration:M,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 M=q8({fieldName:C.name.wireValue,typeReference:C.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(M.type==="failure"&&!NQr({typeDeclarations:n,typeReference:C.valueType}))return{type:"failure",message:`Failed to generate required property ${C.name.wireValue} b/c ${M.message}`};if(M.type==="failure")continue;let{example:T,jsonExample:z}=M;P.push({name:C.name,originalTypeDeclaration:void 0,value:T}),A[C.name.wireValue]=z}o.request=CAe.inlinedRequestBody({jsonExample:A,properties:P});break}case"reference":{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.request=CAe.reference(P);break}default:fc(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=q8({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=rQ.ok(jU.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=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1});break;default:fc(t.response.body.nonStreamResponse)}if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.body({...P,jsonExample:C}));break}case"streaming":{let A;switch(t.response.body.value.type){case"sse":{if(A=q8({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=rQ.ok(jU.sse([{data:{...P,jsonExample:C},event:""}]));break}case"json":{if(A=q8({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=rQ.ok(jU.stream([{...P,jsonExample:C}]));break}case"text":{if(A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.stream([{...P,jsonExample:C}]));break}default:fc(t.response.body.value)}break}case"text":{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.body({...P,jsonExample:C}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:fc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=rQ.error({body:void 0,error:a.declaration.name});else{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.response=rQ.error({body:P,error:a.declaration.name})}try{return{type:"success",example:{id:G7o(o),url:ZXD(t,o),...o},jsonExample:void 0}}catch(A){return{type:"failure",message:`Parse failure with exceptions ${A}`}}}function ZXD(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 i_f({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=EZi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(a.type==="failure")return a;i.pathParameters.push(...a.example);let o=EZi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let c=W0u(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(c.type==="failure")return c;i.queryParameters=c.example;let f=nVa(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;i.headers.push(...f.example);let u=nVa(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=yAy({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=yAy({message:A,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:A.type,body:P})}return{type:"success",example:{...i,url:kXD(t,i)},jsonExample:void 0}}function yAy({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=q8({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return Ttt.reference(n.example)}function kXD(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 aVa(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function iBi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function vAy({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}=aVa(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}=aVa(o.v2Examples);if(c!==void 0)i.queryParameters[o.name.name.originalName]=c;else if(f!==void 0){if(r&&NQr({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}=aVa(o.v2Examples);if(c!==void 0)i.headers[o.name.wireValue]=c;else if(f!==void 0){if(r&&NQr({typeReference:o.valueType,typeDeclarations:n}))continue;i.headers[o.name.wireValue]=f}}return i}function bAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:a}=vAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},f={endpoint:{method:e.method,path:eZD(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}=iBi(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}=iBi(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}=iBi(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:fc(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:f}}function eZD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:a}=aVa(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 H0u({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:bne.json(J7o(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}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?J7o(s):s;n[u]={...a,body:bne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?J7o(s):s;i[u]={...a,body:bne.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:f}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?J7o(s):s;n[u]={...a,body:bne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?J7o(s):s;i[u]={...a,body:bne.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:f}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c))n[u]={...a,body:bne.stream([s])};for(let[u,s]of Object.entries(f))i[u]={...a,body:bne.stream([s])}}break}case"streamParameter":break;default:fc(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:a}}function J7o(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var oVa=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},tZD=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function G0u({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,tZD({exampleStore:i,key:e,example:o}),!0}return!1}function gAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let n={},i={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:f}=bAy({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=rZD({endpoint:e,userRequestExamples:o,baseRequestExample:f,firstUserRequestName:u,firstUserRequestExample:s,firstAutoRequestName:l,firstAutoRequestExample:m,userResults:n,autoResults:i,exampleStore:a});if(nZD({endpoint:e,userRequestExamples:o,requestExamplesUsed:A,userResults:n,exampleStore:a}),Object.keys(n).length===0&&Object.keys(i).length===0){let{baseExample:P}=H0u({endpoint:e}),C=oVa(l??"base","base",void 0);G0u({key:C,displayName:l??"base",request:m??f,response:P,exampleStore:a,userOrAutoStore:i})}return{userFullExamples:n,autoFullExamples:i}}function rZD({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:M}=H0u({endpoint:e,responseObject:m}),T=Object.keys(C)[0],z=Object.values(C)[0];for(let[U,R]of Object.entries(P)){let V,$;t[U]?($=t[U],l.add(U),V=oVa(U,U,m?.statusCode)):o&&a?($=o,V=oVa(a,U,m?.statusCode)):($=r,V=oVa("base",U,m?.statusCode)),G0u({key:V,displayName:U,request:$,response:R,exampleStore:u,userOrAutoStore:c})&&(A=!0)}if(!A){let U=hA(`${e.name.originalName}_example`);n&&i&&l.add(n);let R=oVa(n??a??"base",T??"base",m?.statusCode);G0u({key:R,displayName:n??a??U,request:i??o??r,response:z??M,exampleStore:u,userOrAutoStore:f})&&(A=!0)}}return l}function nZD({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=H0u({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=oVa(A,u??s??"base",f?f.statusCode:l?l.statusCode:c.statusCode);G0u({key:C,displayName:A,request:P,response:f??l??c,exampleStore:i,userOrAutoStore:n})}}function K7o({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=iVa({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=iVa({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=i_f({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 a_f({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}=gAy({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=i_f({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 OAy({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:TK({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?gk.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=TK({filteredIr:e,exampleTypeReference:r});return n!==void 0?gk.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function TK({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:BP.container(wM.list({...n,list:n.list.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:BP.container(wM.set({...n,set:n.set.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?TK({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:BP.container(wM.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?TK({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:BP.container(wM.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:BP.container(wM.map({...n,map:n.map.map(i=>{let a=TK({filteredIr:e,exampleTypeReference:i.key}),o=TK({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=TK({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:BP.named({...r,shape:MR.enum(n)})}),object:n=>({...t,shape:BP.named({...r,shape:MR.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:TK({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=OAy({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=TK({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function o_f({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function iZD({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function mAy({filteredIr:e,headers:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function aZD({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=TK({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=TK({filteredIr:e,exampleTypeReference:r});return n!==void 0?CAe.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function oZD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>rQ.ok(jU.body(n!=null?TK({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>rQ.ok(jU.stream(n.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(Tw))),sse:n=>rQ.ok(jU.sse(n.map(({event:i,data:a})=>{let o=TK({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:i,data:o}:void 0}).filter(Tw))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>rQ.error({error:r,body:n!=null?TK({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function s_f({filteredIr:e,example:t}){return{...t,rootPathParameters:o_f({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:o_f({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:o_f({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:mAy({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:mAy({filteredIr:e,headers:t.endpointHeaders}),queryParameters:iZD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?aZD({filteredIr:e,requestBody:t.request}):void 0,response:oZD({filteredIr:e,response:t.response})}}function AAy({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:MR.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:MR.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:TK({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=OAy({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:MR.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=TK({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:MR.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function u_f(e,t){if(t==null)return e;let r=_Ji(e.types,c=>t.hasType(c)),n=Object.fromEntries(Object.entries(r).map(([c,f])=>{let u=[];if(f.userProvidedExamples=f.userProvidedExamples.map(s=>AAy({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:pE.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:_Ji(e.errors,c=>t.hasError(c)),services:fg(_Ji(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:s_f({filteredIr:t,example:u.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?s_f({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:sZD(e.serviceTypeReferenceInfo,t)}}function sZD(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 SZi(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 urt(e){return e.allParts.map(t=>t.originalName).join("/")}var EM={generateTypeId:e=>`type_${urt(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${urt(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${urt(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${urt(e)}`,generateSubpackageId:e=>`subpackage_${urt(e)}`,generateEndpointId:(e,t)=>{let r=urt(e.fernFilepath),n=t.name.originalName;return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${urt(e)}`,generateWebhookId:(e,t)=>`webhooks_${urt(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${urt(e)}`};function sVa(e){return e.type!=null}var J0u=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=EM.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=EM.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=EM.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 DZi=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=uZD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let o=EM.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=EM.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=EM.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&QG(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=EM.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,f=new Set;for(let u of[...t.headers,...r.headers])QG(u.valueType,o,f);for(let u of[...t.pathParameters,...r.pathParameters])QG(u.valueType,o,f);for(let u of r.queryParameters)QG(u.valueType,o,f);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=SZi(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:u}}r.requestBody!=null&&s4._visit(r.requestBody,{inlinedRequestBody:u=>{for(let s of u.extends)K0u(s,o,f);for(let s of u.properties)QG(s.valueType,o,f);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&PU(n.request.body)){let s=SZi(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:s}}},reference:({requestBodyType:u})=>{QG(u,o,f)},fileUpload:({properties:u})=>{for(let s of u)gne._visit(s,{file:Wc,bodyProperty:({valueType:l})=>{QG(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&&IR._visit(r.response.body,{fileDownload:Wc,json:u=>{QG(u.responseBodyType,o,f)},streaming:u=>{u._visit({sse:s=>QG(s.payload,o,f),json:s=>QG(s.payload,o,f),text:Wc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:s=>QG(s.payload,o,f),json:s=>QG(s.payload,o,f),text:Wc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&QG(u.nonStreamResponse.value.responseBodyType,o,f)},text:Wc,bytes:Wc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{c.add(EM.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=EM.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&&yve._visit(r.payload,{inlinedPayload:c=>{for(let f of c.extends)K0u(f,a,o);for(let f of c.properties)QG(f.valueType,a,o);if(n?.payload!=null&&typeof n.payload=="object"&&!sVa(n.payload)){let f=SZi(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:f}}},reference:({payloadType:c})=>{QG(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)gfe._visit(c.body,{reference:({bodyType:f})=>{QG(f,a,o)},inlinedBody:f=>{for(let u of f.extends)K0u(u,a,o);for(let u of f.properties)QG(u.valueType,a,o)},_other:()=>{}});for(let c of n.queryParameters)QG(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 J0u({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:fc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(EM.generateSubpackageId(n))}}};function uZD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:fc(e)}}function QG(e,t,r){vh._visit(e,{container:n=>{cZD(n,t,r)},named:n=>{K0u(n,t,r)},primitive:Wc,unknown:Wc,_other:Wc})}function K0u(e,t,r){t.add(EM.generateTypeId(e)),r.add(e.fernFilepath)}function cZD(e,t,r){pw._visit(e,{list:n=>{QG(n,t,r)},map:n=>{QG(n.keyType,t,r),QG(n.valueType,t,r)},optional:n=>{QG(n,t,r)},nullable:n=>{QG(n,t,r)},set:n=>{QG(n,t,r)},literal:Wc,_other:Wc})}var lZD=[Gd.AvailabilityStatus.GeneralAvailability];function Vdi(e){return e!==void 0&&!lZD.includes(e.status)}var c_f=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},$7o=class{errors;constructor(){this.errors=new c_f}async check({from:t,to:r}){let n=this.checkBreaking({from:t,to:r});return{bump:n.isBreaking?"major":"minor",isBreaking:n.isBreaking,errors:n.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let 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(Vdi(i.availability))continue;let a=r[n];if(!a){this.errors.add(`Type "${n}" was removed.`);continue}if(Vdi(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(Vdi(i.availability)||(i.endpoints?.every(o=>Vdi(o.availability))??!1))continue;let a=r[n];if(!a){this.errors.add(`Service "${n}" was removed.`);continue}if(Vdi(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(Vdi(c.availability))continue;let f=a[o];if(!f){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(Vdi(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:fc(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:fc(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:fc(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return Vdi(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:fc(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:fc(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:fc(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:fc(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:fc(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:fc(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>i.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function CZi(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:a}=dZD(e.environments,t.environments,r),{services:o,websocketChannels:c}=pZD(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:fZD(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??[]]}}function fZD(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 dZD(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=PAy(e),i=PAy(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:SG.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}=_ZD(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:SG.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(M=>[M.id,M.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}=hZD(f,u,r);return{environments:{defaultEnvironment:a,environments:SG.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}=yZD(o,c,r);return{environments:{defaultEnvironment:a,environments:SG.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 pZD(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 _ZD(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=l_f(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u});return{deconflictedEnvironments2:SG.singleBaseUrl({environments:c}),changedBaseUrlIds2:n}}function hZD(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=l_f(f.id,i);return n[f.id]=u,{...f,id:u,name:r.generateName(u)}}return f});return{deconflictedEnvironments1:SG.singleBaseUrl({environments:o}),changedBaseUrlIds1:n}}function yZD(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=l_f(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:SG.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:n}}function PAy(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 l_f(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}var $m=class e{breadcrumbs=[];context;static STRING=Gd.TypeReference.primitive({v1:"STRING",v2:Gd.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Gd.TypeReference.container(Gd.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var jAy=require("fs/promises");var f_f=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}}},wAy=f_f;var Wdi;(function(e){e.WARNING="warning",e.ERROR="error"})(Wdi||(Wdi={}));var aBi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new d_f({logger:t,relativePathToFile:hu.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||Wdi.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===Wdi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Wdi.WARNING&&!t))switch(r.level){case Wdi.ERROR:if(this.logger.log(j1.Error,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(j1.Error,` - at location (${i})`)}break}}},d_f=class{logger;relativePathToFile;map=new wAy;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,jAy.readFile)(this.relativePathToFile,"utf-8");Fg.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(j1.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 Rk=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=VDe({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=hA(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:Wdi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[o]}return i==null?(n||this.errorCollector.collect({level:Wdi.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=Fg.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 J7r.ReadOnly;if(i)return J7r.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 xve.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 xve.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:vne.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return vh.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)}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 kD=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 xve={};lf(xve,{AudienceExtension:()=>$0u,FernAvailabilityExtension:()=>Y0u,FernEnumExtension:()=>X0u,FernIgnoreExtension:()=>IZi,FernOptionalExtension:()=>Z0u,FernTypeExtension:()=>tmu,FernTypeNameExtension:()=>rmu,SdkGroupNameExtension:()=>k0u,SdkMethodNameExtension:()=>emu});var $0u=class extends kD{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 Y0u=class extends kD{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 vne.InDevelopment;case"PRE_RELEASE":case"BETA":return vne.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return vne.GeneralAvailability;case"DEPRECATED":return vne.Deprecated;default:return}}};var vZD=tl.object({snake:tl.string().optional(),camel:tl.string().optional(),screamingSnake:tl.string().optional(),pascal:tl.string().optional()}),bZD=tl.object({description:tl.string().optional(),name:tl.string().optional(),casing:vZD.optional()}),EAy=tl.record(bZD);var X0u=class extends kD{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=EAy.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 IZi=class extends kD{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 Z0u=class extends kD{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 k0u=class extends kD{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 emu=class extends kD{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 tmu=class extends kD{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 rmu=class extends kD{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 XIr=class extends $m{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new DZi(n),this.ir={auth:{docs:void 0,requirement:Gd.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:Gd.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IZi({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 IZi({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=a_f({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let i=K7o({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=>hA(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=hA(i?.join(".")),o=hA(r),c=this.context.namespace?`${hA(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:pX(""),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=>hA(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 c6={};lf(c6,{AbstractConverters:()=>__f,ExampleConverter:()=>o_t,SchemaConverters:()=>p_f,ServersConverter:()=>crt});var __f={};lf(__f,{AbstractMediaTypeObjectConverter:()=>omu,AbstractParameterConverter:()=>smu});var o_t=class e extends $m{MAX_DEPTH=12;EXAMPLE_STRING=rP.STRING;EXAMPLE_NUMBER=rP.DOUBLE;EXAMPLE_BOOLEAN=rP.BOOLEAN;EXAMPLE_INTEGER=rP.INT;EXAMPLE_DATE=rP.DATE;EXAMPLE_DATE_TIME=rP.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??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((o,c)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${c}]`],context:this.context,schema:{...t,...o,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.filter(o=>o.isValid),i=n.length>0,a;return i?a=n.find(c=>!c.coerced)?.validExample??n[0]?.validExample:a=r[0]?.validExample,{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(o=>o.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((o,c)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${c}]`],context:this.context,schema:o,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.filter(o=>o.isValid),i=n.length>0,a;return i?a=n.find(c=>!c.coerced)?.validExample??n[0]?.validExample:a=r[0]?.validExample,{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(o=>o.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var p_f={};lf(p_f,{ArraySchemaConverter:()=>dVa,EnumSchemaConverter:()=>uVa,ObjectSchemaConverter:()=>cVa,OneOfSchemaConverter:()=>lVa,PrimitiveSchemaConverter:()=>fVa,SchemaConverter:()=>oBi,SchemaOrReferenceConverter:()=>sPe});function SAy(e){return Ok({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return vh.primitive({v1:"BASE_64",v2:Gg.base64({})});case"BOOLEAN":return vh.primitive({v1:"BOOLEAN",v2:Gg.boolean({default:void 0})});case"DATE":return vh.primitive({v1:"DATE",v2:Gg.date({})});case"DATE_TIME":return vh.primitive({v1:"DATE_TIME",v2:Gg.dateTime({})});case"FLOAT":return vh.primitive({v1:"FLOAT",v2:Gg.float({})});case"DOUBLE":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:void 0,validation:void 0})});case"UINT":return vh.primitive({v1:"UINT",v2:Gg.uint({})});case"UINT_64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({})});case"INTEGER":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:void 0,validation:void 0})});case"LONG":return vh.primitive({v1:"LONG",v2:Gg.long({default:void 0})});case"STRING":return vh.primitive({v1:"STRING",v2:Gg.string({default:void 0,validation:void 0})});case"UUID":return vh.primitive({v1:"UUID",v2:Gg.uuid({})});case"BIG_INTEGER":return vh.primitive({v1:"BIG_INTEGER",v2:Gg.bigInteger({default:void 0})});default:return}},unknown:()=>vh.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return vh.container(pw.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return vh.container(pw.list(t))},optional:t=>{if(t!=null)return vh.container(pw.optional(t))},nullable:t=>{if(t!=null)return vh.container(pw.nullable(t))},set:t=>{if(t!=null)return vh.container(pw.set(t))},literal:t=>vh.container(pw.literal(t._visit({string:r=>bfe.string(r),boolean:r=>bfe.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var uVa=class extends $m{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:pE.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r})}}};var nmu=class extends $m{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=vh.container(pw.map({keyType:$m.STRING,valueType:vh.unknown()}));return{type:pE.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new sPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=vh.container(pw.map({keyType:$m.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:pE.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};function Y7o({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=gZD(r,s,n)??n.convertBreadcrumbsToName(l),A="nullable"in s?s.nullable:!1,C=new sPe({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(M=>{f.add(M)});for(let M of C.schema?.audiences??[])c[M]==null&&(c[M]=new Set),c[M].add(u)}}for(let u of Object.keys(o))f.add(u);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:f}}function gZD(e,t,r){return r.isReferenceObject(t)?void 0:new xve.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var cVa=class extends $m{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:pE.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:a}=Y7o({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(R=>!this.schema.required?.includes(R))){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:M,referencedTypes:T,propertiesByAudience:z}=Y7o({properties:P.properties??{},required:[...this.schema.required??[],...P.required??[]],breadcrumbs:A,context:this.context,errorCollector:this.context.errorCollector});r.push(...C),u={...u,...M},s={...s,...z},T.forEach(U=>{c.add(U)})}for(let l of Object.keys(u))c.add(l);return{type:pE.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(Tw),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 imu=class extends kD{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 amu;(function(e){function t(u,s){if(u.title)return u.title;if(u.description){let l=n(u.description);if(l)return l}if(u.type==="object"&&u.properties&&Object.keys(u.properties).length>0){let l=a(u,s);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(u){return u&&(u.includes("_")?u.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(""):u.charAt(0).toUpperCase()+u.slice(1))}e.convertToPascalCase=r;function n(u){let s=u?.split(".")[0]?.trim();if(!s)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),m=s.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(C=>C.length>0).filter(C=>!l.has(C.toLowerCase())).slice(0,4);if(m.length===0)return;let P=i(m).map(C=>C.charAt(0).toUpperCase()+C.slice(1).toLowerCase()).join("");return P.length>0?P:void 0}e.cleanDescriptionForDisplayName=n;function i(u){if(u.length<=2)return u;let s=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),m=[],A=[];return u.forEach(P=>{let C=P.toLowerCase();s.has(C)?A.push(P):l.has(C)&&m.length>0?m.splice(1,0,P):m.push(P)}),m.push(...A),m}e.reorderWordsForBetterSemantics=i;function a(u,s){let l=u.properties;if(!l)return;let m=Object.keys(l);if(m.length===0)return;let A=o(u,s);if(A.length>0){let M=c(A).slice(0,1).map(T=>f(T));if(M.length>0)return M.join("")}let P=c(m);if(P.length>0)return P.slice(0,1).map(M=>f(M)).join("")}e.generateNameFromObjectProperties=a;function o(u,s){let l=u.properties;if(!l)return[];let m=new Set(Object.keys(l)),A=new Set;return s.forEach(P=>{if(P!==u&&P.type==="object"&&P.properties){let C=P.properties;C&&Object.keys(C).forEach(M=>{A.add(M)})}}),Array.from(m).filter(P=>!A.has(P))}e.findUniqueProperties=o;function c(u){let s=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],m=["name","id","value","data","info"];return u.map(P=>{let C=P.toLowerCase(),M=0;for(let T of s)C===T?M+=15:C.includes(T)&&(M+=10);for(let T of l)C===T?M+=8:C.includes(T)&&(M+=5);for(let T of m)C===T?M+=3:C.includes(T)&&(M+=2);return M+=Math.max(0,5-P.length),{prop:P,score:M}}).sort((P,C)=>P.score!==C.score?C.score-P.score:P.prop.localeCompare(C.prop)).map(P=>P.prop)}e.getMostSignificantProperties=c;function f(u){return u.includes("_")?u.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(""):u.charAt(0).toUpperCase()+u.slice(1)}e.capitalizePropertyName=f})(amu||(amu={}));var lVa=class extends $m{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 imu({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 sPe({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:vfe.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}=Y7o({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:pE.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.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=amu.generateDisplayNameForInlinedObject({...o,typeName:f},i),l=new oBi({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:vh.container(pw.map({keyType:$m.STRING,valueType:vh.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:pE.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 sPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:pE.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 vh.container(pw.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 fVa=class extends $m{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 vh.container(pw.literal(bfe.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return vh.primitive({v1:MP.Date,v2:Gg.date({})});if(this.schema.format==="date-time")return vh.primitive({v1:MP.DateTime,v2:Gg.dateTime({})})}return vh.primitive({v1:"STRING",v2:Gg.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return vh.primitive({v1:"FLOAT",v2:Gg.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return vh.primitive({v1:"LONG",v2:Gg.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return vh.primitive({v1:"UINT",v2:Gg.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return vh.primitive({v1:"FLOAT",v2:Gg.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return vh.primitive({v1:"LONG",v2:Gg.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return vh.primitive({v1:"UINT",v2:Gg.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return vh.primitive({v1:"INTEGER",v2:Gg.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?vh.container(pw.literal(bfe.boolean(t))):vh.primitive({v1:"BOOLEAN",v2:Gg.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 mZD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],oBi=class e extends $m{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 xve.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new uVa({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=K2a(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 fVa({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new dVa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.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 lVa({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 nmu({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 cVa({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:pE.alias({aliasOf:vh.unknown(),resolvedType:vh.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new xve.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=SAy(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.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=[...mZD,...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 o_t({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 sPe=class extends $m{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 oBi({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 vh.container(pw.optional(t))}wrapInNullable(t){return vh.container(pw.nullable(t))}};var dVa=class e extends $m{static LIST_UNKNOWN=vh.container(pw.list(vh.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 sPe({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:vh.container(pw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var omu=class extends $m{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 sPe({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 sPe({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=hA(`${[...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 o_t({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 smu=class extends $m{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??$m.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??$m.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??$m.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 o_t({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 umu=class extends kD{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 DAy="Base",crt=class e extends $m{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:SG.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(Tw);return{value:{defaultEnvironment:t[0]?.id,environments:SG.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new umu({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(Tw)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?DAy:e.getServerExtensionName({server:this.servers[0],context:this.context})??DAy}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var X7o={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"},OZD=new Set(Object.values(X7o));var pVa=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
|
|
2360
|
+
`)),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?(ry(!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,Lgy.mkdtemp)(this.getProfilePath())}`),s=f.length-1);let l=f[s].split("=",2)[1];ry(typeof l=="string","`--user-data-dir` is malformed");let m=c;return m||(ry(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 h0u(t)}catch(n){throw vv(n),n}}defaultArgs(t={}){let r=zgy("--disable-features",t.args);t.args&&r.length>0&&Qgy(t.args,"--disable-features");let i=["Translate","AcceptCHFrame","MediaRouter","OptimizationHints",...process.env.PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES==="true"?[]:["ProcessPerSiteUpToMainFrameThreshold","IsolateSandboxedIframes"],...r].filter(A=>A!==""),a=zgy("--enable-features",t.args);t.args&&a.length>0&&Qgy(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=${Vgy.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?f0u({browser:kj.CHROME,channel:bJD(t)}):this.resolveExecutablePath(void 0,r)}};function bJD(e){switch(e){case"chrome":return JF.STABLE;case"chrome-dev":return JF.DEV;case"chrome-beta":return JF.BETA;case"chrome-canary":return JF.CANARY}}function zgy(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 Qgy(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 Wgy=aa(require("fs"),1),U9a=require("fs/promises"),Hgy=aa(require("os"),1),Idf=aa(require("path"),1);FC();h7();var v0u=class e extends L9a{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&&ry(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,U9a.mkdtemp)(this.getProfilePath()),f.push("--profile"),f.push(u);await gdf(kj.FIREFOX,{path:u,preferences:e.getPreferences(o)});let m;return this.puppeteer._isPuppeteerCore||i?(ry(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 h0u(t)}catch(n){throw vv(n),n}else try{let n=".puppeteer",i=["prefs.js","user.js"],a=await Promise.allSettled(i.map(async o=>{let c=Idf.default.join(t,o+n);if(Wgy.default.existsSync(c)){let f=Idf.default.join(t,o);await(0,U9a.unlink)(f),await(0,U9a.rename)(c,f)}}));for(let o of a)if(o.status==="rejected")throw o.reason}catch(n){vv(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(Hgy.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 V9a=class extends _bu{#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=ZUa.firefox;break;default:this.configuration.defaultBrowser="chrome",this.defaultBrowserRevision=ZUa.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=ZUa.chrome;break;case"firefox":this.defaultBrowserRevision=ZUa.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 y0u(this);case"firefox":return new v0u(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=YIr();if(!t)throw new Error("The current platform is not supported.");let r=this.configuration.cacheDirectory,n=await Cdf({cacheDir:r}),i=[{product:"chrome",browser:kj.CHROME,currentBuildId:""},{product:"firefox",browser:kj.FIREFOX,currentBuildId:""}];for(let c of i){let f=this.configuration?.[c.product]?.version??ZUa[c.product];c.currentBuildId=await a0u(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 Ddf({browser:c.browser,platform:t,cacheDir:r,buildId:c.buildId}))}};var b0u=require("child_process"),Kgy=aa(require("fs"),1),$gy=aa(require("os"),1),Ygy=require("path"),Xgy=require("stream"),Zgy=aa(jk(),1);Vpt();mxe();FC();Bk();_7();var gJD=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},Ggy=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 M=(0,r[A])(c==="accessor"?{get:s.get,set:s.set}:s[f],P);if(c==="accessor"){if(M===void 0)continue;if(M===null||typeof M!="object")throw new TypeError("Object expected");(l=o(M.get))&&(s.get=l),(l=o(M.set))&&(s.set=l),(l=o(M.init))&&i.unshift(l)}else(l=o(M))&&(c==="field"?i.unshift(l):s[f]=l)}u&&Object.defineProperty(u,n.name,s),m=!0},mJD=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})},OJD=30,Jgy=30,AJD=(0,Zgy.default)("puppeteer:ffmpeg"),kgy=(()=>{let e=Xgy.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;Ggy(this,n={value:mJD(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),Ggy(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=gJD(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:M,quality:T,colors:z,path:U,overwrite:R}={}){super({allowHalfOpen:!1}),u??="ffmpeg",A??="webm",P??=Jgy,C||=-1,M??=-1,T??=OJD,z??=256,R??=!0,this.#i=P;let{error:V}=(0,b0u.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,M,T,z),Y=re.indexOf("-vf");Y!==-1&&$.push(re.splice(Y,2).at(-1)??""),U&&Kgy.default.mkdirSync((0,Ygy.dirname)(U),{recursive:R}),this.#t=(0,b0u.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()],[R?"-y":"-n"],"pipe:1"].flat(),{stdio:["pipe","pipe","pipe"]}),this.#t.stdout.pipe(this),this.#t.stderr.on("data",ne=>{AJD(ne.toString("utf8"))}),this.#e=o;let{client:te}=this.#e.mainFrame();te.once(Gx.Disconnected,()=>{this.stop().catch(vv)}),this.#n=Kcy(HF(te,"Page.screencastFrame").pipe(BXi(ne=>{te.send("Page.screencastFrameAck",{sessionId:ne.sessionId})}),ert(ne=>ne.metadata.timestamp!==void 0),p7(ne=>({buffer:Buffer.from(ne.data,"base64"),timestamp:ne.metadata.timestamp})),kcy(2,1),ely(([{timestamp:ne,buffer:Oe},{timestamp:ge}])=>XC(Array(Math.round(P*Math.max(ge-ne,0))).fill(Oe))),p7(ne=>(this.#o(ne),[ne,performance.now()])),ohu(zLa(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($gy.default.cpus().length/2,8)}`]];switch(o){case"webm":return[...m,["-f","webm"]].flat();case"gif":return c=Jgy===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(vv),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=[o4o()],i=[o4o()],Ik)](){await this.stop()}}})();var e0y=aa(require("fs"),1),t0y=aa(require("path"),1);gdi();NDe.value={fs:e0y.default,path:t0y.default,ScreenRecorder:kgy};var wJD=new V9a({isPuppeteerCore:!0}),{connect:gQU,defaultArgs:mQU,executablePath:OQU,launch:AQU}=wJD;var YOy=require("os"),XOy=require("path"),ZOy=aa($Oy(),1);function Xpf(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 vXD(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}function bXD(e){if(e&&!vXD(e))throw new Error(`Unsupported browser ${e}`);switch(e){case"firefox":return"firefox";default:return"chrome"}}function gXD(e){switch(e){case"silent":return"silent";case"error":return"error";default:return"warn"}}function Ypf(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=Xpf(`PUPPETEER_${i}_SKIP_DOWNLOAD`)??Xpf(`PUPPETEER_SKIP_${i}_DOWNLOAD`)??t[e]?.skipDownload??r.skipDownload,n}var kOy=()=>{let e=(0,ZOy.cosmiconfigSync)("puppeteer",{searchStrategy:"global"}).search(),t=e?e.config:{};return t.logLevel=gXD(process.env.PUPPETEER_LOGLEVEL??t.logLevel),t.defaultBrowser=bXD(process.env.PUPPETEER_BROWSER??t.defaultBrowser),t.executablePath=process.env.PUPPETEER_EXECUTABLE_PATH??t.executablePath,t.executablePath&&(t.skipDownload=!0),t.skipDownload=Xpf("PUPPETEER_SKIP_DOWNLOAD")??t.skipDownload,t.chrome=Ypf("chrome",t),t["chrome-headless-shell"]=Ypf("chrome-headless-shell",t),t.firefox=Ypf("firefox",t,{skipDownload:!0}),t.cacheDirectory=process.env.PUPPETEER_CACHE_DIR??t.cacheDirectory??(0,XOy.join)((0,YOy.homedir)(),".cache","puppeteer"),t.temporaryDirectory=process.env.PUPPETEER_TMP_DIR??t.temporaryDirectory,t.experiments??={},t};var mXD=kOy(),OXD=new V9a({isPuppeteerCore:!1,configuration:mXD}),{connect:eUU,defaultArgs:tUU,executablePath:rUU,launch:eAy,trimCache:nUU}=OXD;var AXD="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",PXD={"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 W7o(e,t=3,r=1e3,n=2){try{return await e()}catch(i){if(t>0)return await new Promise(a=>setTimeout(a,r)),W7o(e,t-1,r*n,n);throw i}}async function tAy(){try{return await eAy({headless:!0,args:["--ignore-certificate-errors"]})}catch{throw new Error("Could not create a Puppeteer instance")}}async function wXD(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(PXD),await r.setUserAgent(AXD),await r.setJavaScriptEnabled(!0),await W7o(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let n=await W7o(()=>r.content());return await r.close(),n}catch{throw new Error("Failed to download page from Puppeteer")}}async function jXD(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 Zpf({url:e,browser:t}){try{let r;if(t?r=await wXD(t,e):r=await W7o(()=>jXD(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function rAy(e){try{let t=await W7o(()=>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 EXD=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function nAy(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,tVa.join)(process.cwd(),"fern");try{let r=await SXD(e,(0,tVa.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function SXD(e,t){let r=CXD(e),n=(0,tVa.join)(t,r);if(!DXD(r))throw new Error(`${r} - file extension not supported`);if((0,z0u.existsSync)(n))return n;try{(0,z0u.mkdirSync)((0,tVa.dirname)(n),{recursive:!0})}catch{throw new Error(`${n} - failed to create directory`)}try{let i=await rAy(e);return ouy(n,i),n}catch{throw new Error(`${n}: failed to download file from source`)}}function DXD(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&&!EXD.includes(n))}function CXD(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 IXD(e){let t=[];return Dv(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 iAy(e,t){let r=xLa(e),n=IXD(r);if(n!=null){let i=await Promise.all(n.map(async a=>{let o=await nAy(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 aAy=28;async function oAy(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 iAy(a,r)))}let n=[...new Set(r).values()];if(n.length!==0){if(n.length===1&&n[0]!=null){let i=hu.of(aAe(n[0]));return{light:i,dark:i,height:aAy}}if(n[0]!=null&&n[1]!=null){let i=hu.of(aAe(n[0])),a=hu.of(aAe(n[1]));return{light:i,dark:a,height:aAy}}}}var Q0u=class extends YYi{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:Yzo});let n=await this.getHastForUrl(this.url),i=bcy(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=Kl(this.absolutePathToFernDirectory,hu.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 tAy(),o=await oAy(this.url,a);o!=null&&r.setLogo({logo:o});let c=await Uny(n);r.setTitle({title:c});let f=await Fny(n);if(f!=null){let s=await this.getAndCreateAssetsDirectory(),l=await fetch(f);if(l.ok){let m=Buffer.from(await l.arrayBuffer()),A=Kl(s,hu.of("favicon"));await(0,nBi.writeFile)(A,new Uint8Array(m)),r.setFavicon({favicon:JRe(this.absolutePathToFernDirectory,A)})}}let u=await mcy(n);r.setColors({colors:u}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Kl(this.absolutePathToFernDirectory,hu.of("assets"));return await(0,nBi.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=hcy(i);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let o=ycy(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 Zpf({url:t});return xLa(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,nBi.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 Zpf({url:o}),f=await _cy({logger:this.logger,html:c,url:o});if(f.success&&f.data){let u=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:i,page:a.slug});await(0,nBi.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=Kl(i,hu.of(l)),C=xg(P);await(0,nBi.mkdir)(C,{recursive:!0}),await(0,nBi.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:JRe(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 Kl(t,hu.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Kl(t,hu.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 sAy=require("fs/promises");async function kpf({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:n,organization:i}){let a=new XYi;a.setInstance({companyName:i}),await new Q0u({url:e,context:r,builder:a,absolutePathToFernDirectory:Kl(Q_.of(process.cwd()),hu.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,sAy.writeFile)(Kl(Q_.of(t),hu.of(Kye),hu.of(URe)),JSON.stringify({version:n,organization:i},void 0,4))}var e_f=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:n})=>{if(!e||!YJi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let i=Q_.of(D9());await kpf({readmeUrl:e,outputPath:i,taskContext:r,versionOfCli:n,organization:t})};var uAy="0.0.0";var cAy={[IP.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,bU(e)])),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.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"]),[IP.GenerationLanguage.SWIFT]:new Set([])};var BXD=["go","ruby"];function VDe({generationLanguage:e,keywords:t,smartCasing:r}){let n={generateName:(i,a)=>{let o=l=>({unsafeName:l,safeName:TXD({name:l,keywords:qXD({generationLanguage:e,keywords:t})})}),c=hA(i),f=bU(c),u=hJi(i),s=fJi(c);return r&&(!xXD(s)&&(e==null||BXD.includes(e))&&(c=s.map((l,m)=>{if(m>0){let A=L0u(l);if(A!=null)return A;if(U0u(l))return l.toUpperCase()}return l}).join(""),f=bU(s.map((l,m)=>{let A=L0u(l);return A??(U0u(l)?l.toUpperCase():m===0?bU(l):l)}).join(""))),u=i.split(" ").map(l=>l.split(/(\d+)/).map(hJi).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 TXD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":NXD(e)?"_"+e:e}function qXD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return cAy[e]}var RXD=/^[0-9]/;function NXD(e){return RXD.test(e)}function xXD(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=L0u(n)!=null||U0u(n),a=L0u(t)!=null||U0u(t);return i&&a})}function L0u(e){return zXD.get(e.toUpperCase())}function U0u(e){return FXD.has(e.toUpperCase())}var FXD=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"]),zXD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function t_f({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:EAe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return A$i(e.auth,{single:n=>{let i=lAy({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:EAe.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:EAe.Any,schemes:n.map(i=>lAy({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function lAy({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 VFo(c,{header:f=>o4.header({key:a,docs:o,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:vh.primitive({v1:MP.String,v2:Gg.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>fAy({key:a,casingsGenerator:r,docs:o,rawScheme:f}),tokenBearer:f=>V0u({key:a,casingsGenerator:r,docs:o,rawScheme:f}),inferredBearer(f){return V0u({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:f=>V0u({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return V0u({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return fAy({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function V0u({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return o4.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function fAy({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return o4.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 pX(e){let t=LXD(e),{value:r,done:n}=r_f(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...QXD(t)]}}function*QXD(e){let t;do{let{value:r}=r_f(e,"}"),n=r_f(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*LXD(e){for(let t of e)yield t}function r_f(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 H7o({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:r8r(n,{singleBaseUrl:()=>SG.singleBaseUrl(UXD({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>SG.multipleBaseUrls(VXD({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,a])=>[i,r8r(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function UXD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>r8r(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:dAy(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function VXD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>r8r(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:fg(a.urls,o=>dAy(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function dAy(e){return e.endsWith("/")?e.slice(0,-1):e}function G7o(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 NQr({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 pAy({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return xQr({containerType:t});switch(t.type){case"list":{let o=q8({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:wM.literal({literal:t.literal._visit({boolean:o=>s0.boolean(o),string:o=>s0.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 xQr({containerType:t});let o=q8({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return xQr({containerType:t});let o=q8({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=q8({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=q8({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),c=q8({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?xQr({containerType:t}):{type:"success",example:wM.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:fc(t)}}function xQr({containerType:e}){switch(e.type){case"list":return{type:"success",example:wM.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:wM.literal({literal:e.literal._visit({boolean:t=>s0.boolean(t),string:t=>s0.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:wM.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:wM.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:wM.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:wM.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:fc(e)}}function hAy({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return KXD({fieldName:e,default_:WXD(t.v2),validation:HXD(t.v2)});case"BASE_64":return{type:"success",example:s0.base64(rP.BASE64),jsonExample:rP.BASE64};case"BOOLEAN":return{type:"success",example:s0.boolean(rP.BOOLEAN),jsonExample:rP.BOOLEAN};case"DATE":return{type:"success",example:s0.date(rP.DATE),jsonExample:rP.DATE};case"DATE_TIME":return{type:"success",example:s0.datetime({datetime:new Date(rP.DATE_TIME),raw:rP.DATE_TIME}),jsonExample:rP.DATE_TIME};case"DOUBLE":return $XD({fieldName:e,validation:GXD(t.v2)});case"FLOAT":return{type:"success",example:s0.float(rP.FLOAT),jsonExample:rP.FLOAT};case"INTEGER":return YXD({fieldName:e,validation:JXD(t.v2)});case"UINT_64":return{type:"success",example:s0.uint64(rP.INT64),jsonExample:rP.INT64};case"UINT":return{type:"success",example:s0.uint(rP.UINT),jsonExample:rP.UINT};case"BIG_INTEGER":return{type:"success",example:s0.bigInteger(rP.INT64.toString()),jsonExample:`${rP.INT64}`};case"LONG":return{type:"success",example:s0.long(rP.INT64),jsonExample:rP.INT64};case"UUID":return{type:"success",example:s0.uuid(rP.UUID),jsonExample:rP.UUID};default:fc(t.v1)}}function WXD(e){if(e?.type==="string")return e.default}function HXD(e){if(e?.type==="string")return e.validation}function GXD(e){if(e?.type==="double")return e.validation}function JXD(e){if(e?.type==="integer")return e.validation}function _Ay(e){if(e<=rP.SAMPLE_STRINGS.length){let t=rP.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return rP.SAMPLE_STRINGS[rP.SAMPLE_STRINGS.length-1]+".".repeat(e-rP.SAMPLE_STRINGS.length)}function KXD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:s0.string({original:t}),jsonExample:t};if(r){let i=r.minLength,a=r.maxLength;if(i){let o=_Ay(i);return{type:"success",example:s0.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=_Ay(a);return{type:"success",example:s0.string({original:o}),jsonExample:o}}}let n=e??rP.STRING;return{type:"success",example:s0.string({original:n}),jsonExample:n}}function $XD({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:s0.double(r),jsonExample:r};if(n)return{type:"success",example:s0.double(n),jsonExample:n}}return{type:"success",example:s0.double(rP.DOUBLE),jsonExample:rP.DOUBLE}}function YXD({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:s0.integer(r),jsonExample:r};if(n)return{type:"success",example:s0.integer(n),jsonExample:n}}return{type:"success",example:s0.integer(rP.INT),jsonExample:rP.INT}}function rVa({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=q8({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:MR.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:MR.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=rVa({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=XXD({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:MR.object({properties:[...c,...u.properties]}),jsonExample:Object.assign({},o,s)}}case"undiscriminatedUnion":{let o=0;for(let c of r.shape.members){let f=q8({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:MR.undiscriminatedUnion({index:o,singleUnionType:u}),jsonExample:s}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let u=q8({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});u.type==="success"&&(c[f.name.wireValue]=u.jsonExample)}for(let f of r.shape.types){let u=f.shape._visit({noProperties:()=>({type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.noProperties()}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,...c}}),samePropertiesAsObject:s=>{let l=t[s.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${s.typeId}`};let m=rVa({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(m==null)return{type:"failure",message:"Failed to generate example for type reference"};if(m.type==="failure")return m;let{example:A,jsonExample:P}=m;return{type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.samePropertiesAsObject({typeId:l.name.typeId,object:A.type==="object"?A:{properties:[]}})}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,...typeof P=="object"?P:{},...c}}},singleProperty:s=>{let l=q8({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:s.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:m,jsonExample:A}=l;return{type:"success",example:MR.union({discriminant:o,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:gk.singleProperty(m)}}),jsonExample:{[o.wireValue]:f.discriminantValue.wireValue,[s.name.wireValue]:A,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(u.type!=="failure")return u}}}return{type:"failure",message:"Failed to generate example for type reference"}}function XXD({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=q8({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:o});if(s.type==="failure"&&!NQr({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:MR.object({properties:f}),jsonExample:c}}function q8({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=rVa({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:BP.named({shape:f,typeName:o.name})},jsonExample:u}}case"container":{let o=pAy({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(o.type==="failure"){let{example:u,jsonExample:s}=xQr({containerType:t.container});return{type:"success",example:{jsonExample:s,shape:BP.container(u)},jsonExample:s}}let{example:c,jsonExample:f}=o;return{type:"success",example:{jsonExample:f,shape:BP.container(c)},jsonExample:f}}case"primitive":{let{jsonExample:o,example:c}=hAy({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:BP.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:BP.unknown(o)},jsonExample:o}}}}function EZi(e,t){let r=[];for(let n of e){let i=q8({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 nVa(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&NQr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=q8({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 W0u(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&NQr({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=q8({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?Zoe.exploded():Zoe.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var n_f=vh.primitive({v1:MP.String,v2:Gg.string({default:void 0,validation:void 0})});function iVa({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:rQ.ok(jU.body(void 0)),docs:void 0},c=EZi(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let f=EZi(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;o.servicePathParameters=f.example;let u=EZi(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;o.rootPathParameters=u.example;let s=W0u(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(s.type==="failure")return s;o.queryParameters=s.example;let l=nVa(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let m=nVa(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 M=n[C.typeId];if(M==null)throw new Error(`Failed to find extended type declaration with id ${C.typeId}`);let T=rVa({typeDeclaration:M,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 M=q8({fieldName:C.name.wireValue,typeReference:C.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(M.type==="failure"&&!NQr({typeDeclarations:n,typeReference:C.valueType}))return{type:"failure",message:`Failed to generate required property ${C.name.wireValue} b/c ${M.message}`};if(M.type==="failure")continue;let{example:T,jsonExample:z}=M;P.push({name:C.name,originalTypeDeclaration:void 0,value:T}),A[C.name.wireValue]=z}o.request=CAe.inlinedRequestBody({jsonExample:A,properties:P});break}case"reference":{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.request=CAe.reference(P);break}default:fc(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=q8({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=rQ.ok(jU.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=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1});break;default:fc(t.response.body.nonStreamResponse)}if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.body({...P,jsonExample:C}));break}case"streaming":{let A;switch(t.response.body.value.type){case"sse":{if(A=q8({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=rQ.ok(jU.sse([{data:{...P,jsonExample:C},event:""}]));break}case"json":{if(A=q8({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=rQ.ok(jU.stream([{...P,jsonExample:C}]));break}case"text":{if(A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1}),A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.stream([{...P,jsonExample:C}]));break}default:fc(t.response.body.value)}break}case"text":{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:n_f,skipOptionalProperties:!1});if(A.type==="failure")return A;let{example:P,jsonExample:C}=A;o.response=rQ.ok(jU.body({...P,jsonExample:C}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:fc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=rQ.error({body:void 0,error:a.declaration.name});else{let A=q8({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(A.type==="failure")return A;let{example:P}=A;o.response=rQ.error({body:P,error:a.declaration.name})}try{return{type:"success",example:{id:G7o(o),url:ZXD(t,o),...o},jsonExample:void 0}}catch(A){return{type:"failure",message:`Parse failure with exceptions ${A}`}}}function ZXD(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 i_f({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=EZi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(a.type==="failure")return a;i.pathParameters.push(...a.example);let o=EZi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let c=W0u(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(c.type==="failure")return c;i.queryParameters=c.example;let f=nVa(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;i.headers.push(...f.example);let u=nVa(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=yAy({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=yAy({message:A,typeDeclarations:r,skipOptionalRequestProperties:n});P!=null&&i.messages.push({type:A.type,body:P})}return{type:"success",example:{...i,url:kXD(t,i)},jsonExample:void 0}}function yAy({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=q8({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return Ttt.reference(n.example)}function kXD(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 aVa(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function iBi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function vAy({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}=aVa(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}=aVa(o.v2Examples);if(c!==void 0)i.queryParameters[o.name.name.originalName]=c;else if(f!==void 0){if(r&&NQr({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}=aVa(o.v2Examples);if(c!==void 0)i.headers[o.name.wireValue]=c;else if(f!==void 0){if(r&&NQr({typeReference:o.valueType,typeDeclarations:n}))continue;i.headers[o.name.wireValue]=f}}return i}function bAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:a}=vAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},f={endpoint:{method:e.method,path:eZD(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}=iBi(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}=iBi(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}=iBi(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:fc(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:f}}function eZD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:a}=aVa(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 H0u({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:bne.json(J7o(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}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?J7o(s):s;n[u]={...a,body:bne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?J7o(s):s;i[u]={...a,body:bne.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:f}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c)){let l=e.source?.type==="openrpc"?J7o(s):s;n[u]={...a,body:bne.json(l)}}for(let[u,s]of Object.entries(f)){let l=e.source?.type==="openrpc"?J7o(s):s;i[u]={...a,body:bne.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:f}=iBi(o.v2Examples);for(let[u,s]of Object.entries(c))n[u]={...a,body:bne.stream([s])};for(let[u,s]of Object.entries(f))i[u]={...a,body:bne.stream([s])}}break}case"streamParameter":break;default:fc(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:a}}function J7o(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var oVa=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},tZD=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function G0u({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,tZD({exampleStore:i,key:e,example:o}),!0}return!1}function gAy({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let n={},i={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:f}=bAy({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=rZD({endpoint:e,userRequestExamples:o,baseRequestExample:f,firstUserRequestName:u,firstUserRequestExample:s,firstAutoRequestName:l,firstAutoRequestExample:m,userResults:n,autoResults:i,exampleStore:a});if(nZD({endpoint:e,userRequestExamples:o,requestExamplesUsed:A,userResults:n,exampleStore:a}),Object.keys(n).length===0&&Object.keys(i).length===0){let{baseExample:P}=H0u({endpoint:e}),C=oVa(l??"base","base",void 0);G0u({key:C,displayName:l??"base",request:m??f,response:P,exampleStore:a,userOrAutoStore:i})}return{userFullExamples:n,autoFullExamples:i}}function rZD({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:M}=H0u({endpoint:e,responseObject:m}),T=Object.keys(C)[0],z=Object.values(C)[0];for(let[U,R]of Object.entries(P)){let V,$;t[U]?($=t[U],l.add(U),V=oVa(U,U,m?.statusCode)):o&&a?($=o,V=oVa(a,U,m?.statusCode)):($=r,V=oVa("base",U,m?.statusCode)),G0u({key:V,displayName:U,request:$,response:R,exampleStore:u,userOrAutoStore:c})&&(A=!0)}if(!A){let U=hA(`${e.name.originalName}_example`);n&&i&&l.add(n);let R=oVa(n??a??"base",T??"base",m?.statusCode);G0u({key:R,displayName:n??a??U,request:i??o??r,response:z??M,exampleStore:u,userOrAutoStore:f})&&(A=!0)}}return l}function nZD({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=H0u({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=oVa(A,u??s??"base",f?f.statusCode:l?l.statusCode:c.statusCode);G0u({key:C,displayName:A,request:P,response:f??l??c,exampleStore:i,userOrAutoStore:n})}}function K7o({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=iVa({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=iVa({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=i_f({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 a_f({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}=gAy({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=i_f({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 OAy({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:TK({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?gk.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=TK({filteredIr:e,exampleTypeReference:r});return n!==void 0?gk.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function TK({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:BP.container(wM.list({...n,list:n.list.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:BP.container(wM.set({...n,set:n.set.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?TK({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:BP.container(wM.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?TK({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:BP.container(wM.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:BP.container(wM.map({...n,map:n.map.map(i=>{let a=TK({filteredIr:e,exampleTypeReference:i.key}),o=TK({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=TK({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:BP.named({...r,shape:MR.enum(n)})}),object:n=>({...t,shape:BP.named({...r,shape:MR.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:TK({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=OAy({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=TK({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:BP.named({...r,shape:MR.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function o_f({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function iZD({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function mAy({filteredIr:e,headers:t}){return t.map(r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function aZD({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=TK({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=TK({filteredIr:e,exampleTypeReference:r});return n!==void 0?CAe.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function oZD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>rQ.ok(jU.body(n!=null?TK({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>rQ.ok(jU.stream(n.map(i=>TK({filteredIr:e,exampleTypeReference:i})).filter(Tw))),sse:n=>rQ.ok(jU.sse(n.map(({event:i,data:a})=>{let o=TK({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:i,data:o}:void 0}).filter(Tw))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>rQ.error({error:r,body:n!=null?TK({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function s_f({filteredIr:e,example:t}){return{...t,rootPathParameters:o_f({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:o_f({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:o_f({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:mAy({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:mAy({filteredIr:e,headers:t.endpointHeaders}),queryParameters:iZD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?aZD({filteredIr:e,requestBody:t.request}):void 0,response:oZD({filteredIr:e,response:t.response})}}function AAy({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=TK({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:MR.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:MR.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:TK({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=OAy({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:MR.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=TK({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:MR.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function u_f(e,t){if(t==null)return e;let r=_Ji(e.types,c=>t.hasType(c)),n=Object.fromEntries(Object.entries(r).map(([c,f])=>{let u=[];if(f.userProvidedExamples=f.userProvidedExamples.map(s=>AAy({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:pE.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:_Ji(e.errors,c=>t.hasError(c)),services:fg(_Ji(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:s_f({filteredIr:t,example:u.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?s_f({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:sZD(e.serviceTypeReferenceInfo,t)}}function sZD(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 SZi(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 urt(e){return e.allParts.map(t=>t.originalName).join("/")}var EM={generateTypeId:e=>`type_${urt(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${urt(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${urt(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${urt(e)}`,generateSubpackageId:e=>`subpackage_${urt(e)}`,generateEndpointId:(e,t)=>{let r=urt(e.fernFilepath),n=t.name.originalName;return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${urt(e)}`,generateWebhookId:(e,t)=>`webhooks_${urt(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${urt(e)}`};function sVa(e){return e.type!=null}var J0u=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=EM.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=EM.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=EM.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 DZi=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=uZD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let o=EM.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=EM.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=EM.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&QG(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=EM.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,f=new Set;for(let u of[...t.headers,...r.headers])QG(u.valueType,o,f);for(let u of[...t.pathParameters,...r.pathParameters])QG(u.valueType,o,f);for(let u of r.queryParameters)QG(u.valueType,o,f);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=SZi(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:u}}r.requestBody!=null&&s4._visit(r.requestBody,{inlinedRequestBody:u=>{for(let s of u.extends)K0u(s,o,f);for(let s of u.properties)QG(s.valueType,o,f);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&PU(n.request.body)){let s=SZi(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:s}}},reference:({requestBodyType:u})=>{QG(u,o,f)},fileUpload:({properties:u})=>{for(let s of u)gne._visit(s,{file:Wc,bodyProperty:({valueType:l})=>{QG(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&&IR._visit(r.response.body,{fileDownload:Wc,json:u=>{QG(u.responseBodyType,o,f)},streaming:u=>{u._visit({sse:s=>QG(s.payload,o,f),json:s=>QG(s.payload,o,f),text:Wc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:s=>QG(s.payload,o,f),json:s=>QG(s.payload,o,f),text:Wc,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&QG(u.nonStreamResponse.value.responseBodyType,o,f)},text:Wc,bytes:Wc,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{c.add(EM.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=EM.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&&yve._visit(r.payload,{inlinedPayload:c=>{for(let f of c.extends)K0u(f,a,o);for(let f of c.properties)QG(f.valueType,a,o);if(n?.payload!=null&&typeof n.payload=="object"&&!sVa(n.payload)){let f=SZi(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:f}}},reference:({payloadType:c})=>{QG(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)gfe._visit(c.body,{reference:({bodyType:f})=>{QG(f,a,o)},inlinedBody:f=>{for(let u of f.extends)K0u(u,a,o);for(let u of f.properties)QG(u.valueType,a,o)},_other:()=>{}});for(let c of n.queryParameters)QG(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 J0u({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:fc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(EM.generateSubpackageId(n))}}};function uZD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:fc(e)}}function QG(e,t,r){vh._visit(e,{container:n=>{cZD(n,t,r)},named:n=>{K0u(n,t,r)},primitive:Wc,unknown:Wc,_other:Wc})}function K0u(e,t,r){t.add(EM.generateTypeId(e)),r.add(e.fernFilepath)}function cZD(e,t,r){pw._visit(e,{list:n=>{QG(n,t,r)},map:n=>{QG(n.keyType,t,r),QG(n.valueType,t,r)},optional:n=>{QG(n,t,r)},nullable:n=>{QG(n,t,r)},set:n=>{QG(n,t,r)},literal:Wc,_other:Wc})}var lZD=[Gd.AvailabilityStatus.GeneralAvailability];function Vdi(e){return e!==void 0&&!lZD.includes(e.status)}var c_f=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},$7o=class{errors;constructor(){this.errors=new c_f}async check({from:t,to:r}){let n=this.checkBreaking({from:t,to:r});return{bump:n.isBreaking?"major":"minor",isBreaking:n.isBreaking,errors:n.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let 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(Vdi(i.availability))continue;let a=r[n];if(!a){this.errors.add(`Type "${n}" was removed.`);continue}if(Vdi(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(Vdi(i.availability)||(i.endpoints?.every(o=>Vdi(o.availability))??!1))continue;let a=r[n];if(!a){this.errors.add(`Service "${n}" was removed.`);continue}if(Vdi(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(Vdi(c.availability))continue;let f=a[o];if(!f){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(Vdi(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:fc(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:fc(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:fc(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return Vdi(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:fc(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:fc(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:fc(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:fc(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:fc(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:fc(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>i.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function CZi(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:a}=dZD(e.environments,t.environments,r),{services:o,websocketChannels:c}=pZD(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:fZD(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??[]]}}function fZD(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 dZD(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=PAy(e),i=PAy(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:SG.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}=_ZD(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:SG.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(M=>[M.id,M.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}=hZD(f,u,r);return{environments:{defaultEnvironment:a,environments:SG.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}=yZD(o,c,r);return{environments:{defaultEnvironment:a,environments:SG.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 pZD(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 _ZD(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=l_f(u.id,i);return n[u.id]=s,{...u,id:s,name:r.generateName(s)}}return u});return{deconflictedEnvironments2:SG.singleBaseUrl({environments:c}),changedBaseUrlIds2:n}}function hZD(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=l_f(f.id,i);return n[f.id]=u,{...f,id:u,name:r.generateName(u)}}return f});return{deconflictedEnvironments1:SG.singleBaseUrl({environments:o}),changedBaseUrlIds1:n}}function yZD(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=l_f(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:SG.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:n}}function PAy(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 l_f(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}var $m=class e{breadcrumbs=[];context;static STRING=Gd.TypeReference.primitive({v1:"STRING",v2:Gd.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Gd.TypeReference.container(Gd.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var jAy=require("fs/promises");var f_f=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}}},wAy=f_f;var Wdi;(function(e){e.WARNING="warning",e.ERROR="error"})(Wdi||(Wdi={}));var aBi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new d_f({logger:t,relativePathToFile:hu.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||Wdi.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===Wdi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Wdi.WARNING&&!t))switch(r.level){case Wdi.ERROR:if(this.logger.log(j1.Error,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(j1.Error,` - at location (${i})`)}break}}},d_f=class{logger;relativePathToFile;map=new wAy;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,jAy.readFile)(this.relativePathToFile,"utf-8");Fg.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(j1.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 Rk=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=VDe({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=hA(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:Wdi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[o]}return i==null?(n||this.errorCollector.collect({level:Wdi.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=Fg.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 J7r.ReadOnly;if(i)return J7r.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 xve.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 xve.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:vne.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return vh.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)}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 kD=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 xve={};lf(xve,{AudienceExtension:()=>$0u,FernAvailabilityExtension:()=>Y0u,FernEnumExtension:()=>X0u,FernIgnoreExtension:()=>IZi,FernOptionalExtension:()=>Z0u,FernTypeExtension:()=>tmu,FernTypeNameExtension:()=>rmu,SdkGroupNameExtension:()=>k0u,SdkMethodNameExtension:()=>emu});var $0u=class extends kD{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 Y0u=class extends kD{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 vne.InDevelopment;case"PRE_RELEASE":case"BETA":return vne.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return vne.GeneralAvailability;case"DEPRECATED":return vne.Deprecated;default:return}}};var vZD=tl.object({snake:tl.string().optional(),camel:tl.string().optional(),screamingSnake:tl.string().optional(),pascal:tl.string().optional()}),bZD=tl.object({description:tl.string().optional(),name:tl.string().optional(),casing:vZD.optional()}),EAy=tl.record(bZD);var X0u=class extends kD{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=EAy.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 IZi=class extends kD{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 Z0u=class extends kD{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 k0u=class extends kD{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 emu=class extends kD{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 tmu=class extends kD{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 rmu=class extends kD{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 XIr=class extends $m{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new DZi(n),this.ir={auth:{docs:void 0,requirement:Gd.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:Gd.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IZi({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 IZi({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=a_f({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let i=K7o({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=>hA(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=hA(i?.join(".")),o=hA(r),c=this.context.namespace?`${hA(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:pX(""),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=>hA(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 c6={};lf(c6,{AbstractConverters:()=>__f,ExampleConverter:()=>o_t,SchemaConverters:()=>p_f,ServersConverter:()=>crt});var __f={};lf(__f,{AbstractMediaTypeObjectConverter:()=>omu,AbstractParameterConverter:()=>smu});var o_t=class e extends $m{MAX_DEPTH=12;EXAMPLE_STRING=rP.STRING;EXAMPLE_NUMBER=rP.DOUBLE;EXAMPLE_BOOLEAN=rP.BOOLEAN;EXAMPLE_INTEGER=rP.INT;EXAMPLE_DATE=rP.DATE;EXAMPLE_DATE_TIME=rP.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 p_f={};lf(p_f,{ArraySchemaConverter:()=>dVa,EnumSchemaConverter:()=>uVa,ObjectSchemaConverter:()=>cVa,OneOfSchemaConverter:()=>lVa,PrimitiveSchemaConverter:()=>fVa,SchemaConverter:()=>oBi,SchemaOrReferenceConverter:()=>sPe});function SAy(e){return Ok({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return vh.primitive({v1:"BASE_64",v2:Gg.base64({})});case"BOOLEAN":return vh.primitive({v1:"BOOLEAN",v2:Gg.boolean({default:void 0})});case"DATE":return vh.primitive({v1:"DATE",v2:Gg.date({})});case"DATE_TIME":return vh.primitive({v1:"DATE_TIME",v2:Gg.dateTime({})});case"FLOAT":return vh.primitive({v1:"FLOAT",v2:Gg.float({})});case"DOUBLE":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:void 0,validation:void 0})});case"UINT":return vh.primitive({v1:"UINT",v2:Gg.uint({})});case"UINT_64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({})});case"INTEGER":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:void 0,validation:void 0})});case"LONG":return vh.primitive({v1:"LONG",v2:Gg.long({default:void 0})});case"STRING":return vh.primitive({v1:"STRING",v2:Gg.string({default:void 0,validation:void 0})});case"UUID":return vh.primitive({v1:"UUID",v2:Gg.uuid({})});case"BIG_INTEGER":return vh.primitive({v1:"BIG_INTEGER",v2:Gg.bigInteger({default:void 0})});default:return}},unknown:()=>vh.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return vh.container(pw.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return vh.container(pw.list(t))},optional:t=>{if(t!=null)return vh.container(pw.optional(t))},nullable:t=>{if(t!=null)return vh.container(pw.nullable(t))},set:t=>{if(t!=null)return vh.container(pw.set(t))},literal:t=>vh.container(pw.literal(t._visit({string:r=>bfe.string(r),boolean:r=>bfe.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var uVa=class extends $m{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:pE.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r})}}};var nmu=class extends $m{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=vh.container(pw.map({keyType:$m.STRING,valueType:vh.unknown()}));return{type:pE.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new sPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=vh.container(pw.map({keyType:$m.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:pE.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};function Y7o({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=gZD(r,s,n)??n.convertBreadcrumbsToName(l),A="nullable"in s?s.nullable:!1,C=new sPe({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(M=>{f.add(M)});for(let M of C.schema?.audiences??[])c[M]==null&&(c[M]=new Set),c[M].add(u)}}for(let u of Object.keys(o))f.add(u);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:f}}function gZD(e,t,r){return r.isReferenceObject(t)?void 0:new xve.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var cVa=class extends $m{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:pE.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:a}=Y7o({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(R=>!this.schema.required?.includes(R))){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:M,referencedTypes:T,propertiesByAudience:z}=Y7o({properties:P.properties??{},required:[...this.schema.required??[],...P.required??[]],breadcrumbs:A,context:this.context,errorCollector:this.context.errorCollector});r.push(...C),u={...u,...M},s={...s,...z},T.forEach(U=>{c.add(U)})}for(let l of Object.keys(u))c.add(l);return{type:pE.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(Tw),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 imu=class extends kD{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 amu;(function(e){function t(u,s){if(u.title)return u.title;if(u.description){let l=n(u.description);if(l)return l}if(u.type==="object"&&u.properties&&Object.keys(u.properties).length>0){let l=a(u,s);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(u){return u&&(u.includes("_")?u.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(""):u.charAt(0).toUpperCase()+u.slice(1))}e.convertToPascalCase=r;function n(u){let s=u?.split(".")[0]?.trim();if(!s)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),m=s.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(C=>C.length>0).filter(C=>!l.has(C.toLowerCase())).slice(0,4);if(m.length===0)return;let P=i(m).map(C=>C.charAt(0).toUpperCase()+C.slice(1).toLowerCase()).join("");return P.length>0?P:void 0}e.cleanDescriptionForDisplayName=n;function i(u){if(u.length<=2)return u;let s=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),m=[],A=[];return u.forEach(P=>{let C=P.toLowerCase();s.has(C)?A.push(P):l.has(C)&&m.length>0?m.splice(1,0,P):m.push(P)}),m.push(...A),m}e.reorderWordsForBetterSemantics=i;function a(u,s){let l=u.properties;if(!l)return;let m=Object.keys(l);if(m.length===0)return;let A=o(u,s);if(A.length>0){let M=c(A).slice(0,1).map(T=>f(T));if(M.length>0)return M.join("")}let P=c(m);if(P.length>0)return P.slice(0,1).map(M=>f(M)).join("")}e.generateNameFromObjectProperties=a;function o(u,s){let l=u.properties;if(!l)return[];let m=new Set(Object.keys(l)),A=new Set;return s.forEach(P=>{if(P!==u&&P.type==="object"&&P.properties){let C=P.properties;C&&Object.keys(C).forEach(M=>{A.add(M)})}}),Array.from(m).filter(P=>!A.has(P))}e.findUniqueProperties=o;function c(u){let s=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],m=["name","id","value","data","info"];return u.map(P=>{let C=P.toLowerCase(),M=0;for(let T of s)C===T?M+=15:C.includes(T)&&(M+=10);for(let T of l)C===T?M+=8:C.includes(T)&&(M+=5);for(let T of m)C===T?M+=3:C.includes(T)&&(M+=2);return M+=Math.max(0,5-P.length),{prop:P,score:M}}).sort((P,C)=>P.score!==C.score?C.score-P.score:P.prop.localeCompare(C.prop)).map(P=>P.prop)}e.getMostSignificantProperties=c;function f(u){return u.includes("_")?u.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(""):u.charAt(0).toUpperCase()+u.slice(1)}e.capitalizePropertyName=f})(amu||(amu={}));var lVa=class extends $m{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 imu({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 sPe({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:vfe.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}=Y7o({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:pE.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.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=amu.generateDisplayNameForInlinedObject({...o,typeName:f},i),l=new oBi({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:vh.container(pw.map({keyType:$m.STRING,valueType:vh.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:pE.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 sPe({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:pE.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 vh.container(pw.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 fVa=class extends $m{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 vh.container(pw.literal(bfe.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return vh.primitive({v1:MP.Date,v2:Gg.date({})});if(this.schema.format==="date-time")return vh.primitive({v1:MP.DateTime,v2:Gg.dateTime({})})}return vh.primitive({v1:"STRING",v2:Gg.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return vh.primitive({v1:"FLOAT",v2:Gg.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return vh.primitive({v1:"LONG",v2:Gg.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return vh.primitive({v1:"UINT",v2:Gg.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return vh.primitive({v1:"DOUBLE",v2:Gg.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return vh.primitive({v1:"FLOAT",v2:Gg.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return vh.primitive({v1:"INTEGER",v2:Gg.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return vh.primitive({v1:"LONG",v2:Gg.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return vh.primitive({v1:"UINT",v2:Gg.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return vh.primitive({v1:"UINT_64",v2:Gg.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return vh.primitive({v1:"INTEGER",v2:Gg.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?vh.container(pw.literal(bfe.boolean(t))):vh.primitive({v1:"BOOLEAN",v2:Gg.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 mZD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],oBi=class e extends $m{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 xve.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new uVa({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=K2a(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 fVa({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new dVa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.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 lVa({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 nmu({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 cVa({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:pE.alias({aliasOf:vh.unknown(),resolvedType:vh.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new xve.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=SAy(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pE.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=[...mZD,...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 o_t({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 sPe=class extends $m{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 oBi({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 vh.container(pw.optional(t))}wrapInNullable(t){return vh.container(pw.nullable(t))}};var dVa=class e extends $m{static LIST_UNKNOWN=vh.container(pw.list(vh.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 sPe({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:vh.container(pw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var omu=class extends $m{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 sPe({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 sPe({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=hA(`${[...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 o_t({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 smu=class extends $m{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??$m.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??$m.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??$m.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 o_t({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 umu=class extends kD{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 DAy="Base",crt=class e extends $m{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:SG.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(Tw);return{value:{defaultEnvironment:t[0]?.id,environments:SG.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new umu({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(Tw)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?DAy:e.getServerExtensionName({server:this.servers[0],context:this.context})??DAy}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var X7o={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"},OZD=new Set(Object.values(X7o));var pVa=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
|
|
2361
2361
|
`)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(j1.Trace,...t)}debug(...t){this.write(j1.Debug,...t)}info(...t){this.write(j1.Info,...t)}warn(...t){this.write(j1.Warn,...t)}error(...t){this.write(j1.Error,...t)}log(t,...r){this.write(t,...r)}};function FQr(e){if(e?.deprecated)return{status:vne.Deprecated,message:"DEPRECATED"}}var ZIr={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}},cmu={MESSAGE:4,ENUM:5,SERVICE:6};var lmu=class extends $m{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,ZIr.ENUM.VALUE,n]),availability:void 0}});return{type:pE.enum({default:void 0,values:t})}}};function CAy(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var IAy=new Set([wD.DOUBLE,wD.FLOAT,wD.INT64,wD.UINT64,wD.INT32,wD.FIXED64,wD.FIXED32,wD.BOOL,wD.STRING,wD.BYTES,wD.UINT32,wD.SFIXED32,wD.SFIXED64,wD.SINT32,wD.SINT64]);var fmu=class e extends $m{static LIST_UNKNOWN=vh.container(pw.list(vh.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 sBi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:E2a.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let n=new Set;return{typeReference:vh.container(pw.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var dmu=class extends $m{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 wD.STRING:return vh.primitive({v1:MP.String,v2:Gg.string({default:void 0,validation:void 0})});case wD.DOUBLE:return vh.primitive({v1:MP.Double,v2:Gg.double({default:void 0,validation:void 0})});case wD.FLOAT:return vh.primitive({v1:MP.Float,v2:Gg.float({})});case wD.INT32:return vh.primitive({v1:MP.Integer,v2:Gg.integer({default:void 0,validation:void 0})});case wD.INT64:return vh.primitive({v1:MP.Long,v2:Gg.long({default:void 0})});case wD.UINT32:return vh.primitive({v1:MP.Uint,v2:Gg.uint({default:void 0})});case wD.UINT64:return vh.primitive({v1:MP.Uint64,v2:Gg.uint64({default:void 0})});case wD.BOOL:return vh.primitive({v1:MP.Boolean,v2:Gg.boolean({default:void 0})});default:return vh.unknown()}}};var sBi=class extends $m{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 fmu({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:FQr(this.field.options)}}if(IAy.has(this.field.type)){let n=new dmu({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:FQr(this.field.options)}}if((this.field.type===wD.MESSAGE||this.field.type===wD.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:FQr(this.field.options)}}}wrapInOptional(t){return vh.container(pw.optional(t))}};function MAy({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 sBi({context:r,breadcrumbs:[...t,"fields",u.name],field:u,sourceCodeInfoPath:[...n,ZIr.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,ZIr.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 pmu=class extends $m{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 sBi({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:pE.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{},availability:FQr(this.getProtoAvailabilityOptions())}}getProtoAvailabilityOptions(){return{deprecated:this.oneOfFields.every(t=>t.options?.deprecated)}}};var _mu=class extends $m{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}=MAy({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 uBi({context:this.context,breadcrumbs:this.breadcrumbs,schema:f,sourceCodeInfoPath:[...this.sourceCodeInfoPath,ZIr.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 uBi({context:this.context,breadcrumbs:this.breadcrumbs,schema:f,sourceCodeInfoPath:[...this.sourceCodeInfoPath,ZIr.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 pmu({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:o[c]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,ZIr.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(CAy(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:pE.object({properties:n,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),availability:FQr(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 uBi=class extends $m{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 lmu({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:FQr(this.schema.options)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new _mu({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 _Va=class extends Rk{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:vh.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 h_f(){return{4:{},5:{},6:{}}}function BAy(e){let t=h_f();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 Z7o=class e extends $m{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===E2a.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 wD.DOUBLE:case wD.FLOAT:case wD.INT64:case wD.UINT64:case wD.INT32:case wD.FIXED64:case wD.FIXED32:case wD.UINT32:case wD.SFIXED32:case wD.SFIXED64:case wD.SINT32:case wD.SINT64:return this.convertNumber();case wD.BOOL:return this.convertBoolean();case wD.STRING:return this.convertString(this.EXAMPLE_STRING);case wD.BYTES:return this.convertBytes();case wD.ENUM:return this.convertEnum(t);case wD.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 _Va({...this.context,comments:h_f(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:u,logger:new pVa}):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 hmu=class extends $m{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:wU.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:SAe.proto({methodType:this.getGrpcMethodType()}),audiences:[],retries:void 0}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?iIr.BidirectionalStream:this.operation.clientStreaming?iIr.ClientStream:this.operation.serverStreaming?iIr.ServerStream:iIr.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:s4.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:IR.json(hfe.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var ymu=class extends $m{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 hmu({context:this.context,breadcrumbs:this.breadcrumbs,operation:n,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,ZIr.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 TAy(){return{displayName:void 0,request:{endpoint:{method:H7r.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:Gd.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var vmu=class extends XIr{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 uBi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[cmu.ENUM,t],schemaIndex:t}).convert();i!=null&&this.addTypesToIr({...qAy(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 uBi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[cmu.MESSAGE,t],schemaIndex:t}).convert();i!=null&&this.addTypesToIr({...qAy(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 ymu({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[cmu.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=TAy(),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=bne.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 Z7o({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 Z7o({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=>hA(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 qAy(e,t){return Object.fromEntries(Object.entries(e).map(([r,n])=>[t(r),n]))}function RAy({req:e,options:t}){let r,n=VDe({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let c=new vmu({context:new _Va({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new aBi({logger:{log:(f,...u)=>{}},relativeFilepathToSpec:void 0}),logger:new pVa,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:BAy(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();c!=null&&(r=r===void 0?c:CZi(r,c,n))}let i=G0.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 NAy(e){return{}}var y_f=AZD({name:"protoc-gen-fern",version:`v${String(uAy)}`,run:RAy});function AZD({name:e,version:t,run:r}){return{name:e,version:t,run(n){let i=NAy(n.parameter),a=r({req:n,options:i});return PZD([a],bx_,gx_)}}}function PZD(e,t,r){return SRo(qQs,{supportedFeatures:X5.parse(qRo.PROTO3_OPTIONAL|qRo.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var zAy=aa(require("net"),1),QAy=aa(require("os"),1),bmu=class extends Error{constructor(t){super(`${t} is locked`)}},hVa={old:new Set,young:new Set},wZD=1e3*15;var k7o,jZD=()=>{let e=QAy.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},xAy=e=>new Promise((t,r)=>{let n=zAy.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),FAy=async(e,t)=>{if(e.host||e.port===0)return xAy(e);for(let r of t)try{await xAy({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},EZD=function*(e){e&&(yield*e),yield 0};async function yVa(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)}k7o===void 0&&(k7o=setTimeout(()=>{k7o=void 0,hVa.old=hVa.young,hVa.young=new Set},wZD),k7o.unref&&k7o.unref());let n=jZD();for(let i of EZD(t))try{if(r.has(i))continue;let a=await FAy({...e,port:i},n);for(;hVa.old.has(a)||hVa.young.has(a);){if(i!==0)throw new bmu(i);a=await FAy({...e,port:i},n)}return hVa.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof bmu))throw a}throw new Error("No available ports found")}APy();var Mwy=aa(Iwy(),1),{applyExtends:xkD,cjsPlatformShim:FkD,Parser:zkD,processArgv:QkD,Yargs:Umu}=Mwy.default;Umu.applyExtends=(e,t,r)=>xkD(e,t,r,FkD);Umu.hideBin=QkD.hideBin;Umu.Parser=zkD;var Bwy=Umu;var Twy=require("fs/promises");var qwy=require("path"),Rwy=aa(rDe(),1);async function Nwy({url:e,logger:t}){try{let r=await LkD({url:e,logger:t}),n=await Rwy.default.dir(),i=(0,qwy.join)(n.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",n.path),t.debug("filePath",i),await(0,Twy.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 LkD({url:e,logger:t}){let r=await iX.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:VWs(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)`),VWs(r.data))}var f8o=aa(z6r(),1);function dhf(e,t){if(e=f8o.default.parse(e),t=f8o.default.parse(t),!(f8o.default.compareBuild(e,t)>=0))return f8o.default.diff(e,t)||"build"}var UkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,VkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,WkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,HkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,GkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,JkD=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function VZi(e){let t=e.match(GkD);if(t!=null){let[c,f,u,s,l]=t,m=LG(f),A=LG(u),P=LG(s),C=LG(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(JkD);if(r!=null){let[c,f,u,s,l]=r,m=LG(f),A=LG(u),P=LG(s),C=LG(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(UkD);if(n!=null){let[c,f,u,s,l]=n,m=LG(f),A=LG(u),P=LG(s),C=LG(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(WkD);if(i!=null){let[c,f,u,s,l]=i,m=LG(f),A=LG(u),P=LG(s),C=LG(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(VkD);if(a!=null){let[c,f,u,s,l,m]=a,A=LG(f),P=LG(u),C=LG(s),M=LG(l),T=LG(m);if(A==null||P==null||C==null||M==null||T==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:A,minor:P,patch:C,releaseCandidateIndex:M,commitIndex:T}}let o=e.match(HkD);if(o!=null){let[c,f,u,s]=o,l=LG(f),m=LG(u),A=LG(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 LG(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function Ixe(e,t){if(e===t)return!1;let r=VZi(e),n=VZi(t);if(r.major!==n.major||r.minor!==n.minor||r.patch!==n.patch)return dhf(xwy(r),xwy(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!Ixe(t,e)}function xwy(e){return`${e.major}.${e.minor}.${e.patch}`}var uPe=e=>e.name==="up",hrt=e=>e.name==="down",Fwy=e=>e.name==="space",jVa=e=>e.name==="backspace",dBi=e=>e.name==="tab",Vmu=e=>"1234567890".includes(e.name),Nne=e=>e.name==="enter"||e.name==="return";var Wmu=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},Hmu=class extends Error{name="CancelPromptError";message="Prompt was canceled"},d8o=class extends Error{name="ExitPromptError"},Gmu=class extends Error{name="HookError"},LQr=class extends Error{name="ValidationError"};var Uwy=require("async_hooks");var Jmu=require("async_hooks");var zwy=new Jmu.AsyncLocalStorage;function KkD(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Qwy(e,t){let r=KkD(e);return zwy.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return t(n)})}function WZi(){let e=zwy.getStore();if(!e)throw new Gmu("[Inquirer] Hook functions can only be called from within a prompt");return e}function phf(){return WZi().rl}function _hf(e){let t=(...r)=>{let n=WZi(),i=!1,a=n.handleChange;n.handleChange=()=>{i=!0};let o=e(...r);return i&&a(),n.handleChange=a,o};return Jmu.AsyncResource.bind(t)}function EVa(e){let t=WZi(),{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 Lwy(){WZi().handleChange()}var HZi={queue(e){let t=WZi(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(phf());if(n!=null&&typeof n!="function")throw new LQr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=WZi();_hf(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=WZi();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function PS(e){return EVa(t=>{let r=Uwy.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),Lwy())});if(t.initialized)return[t.get(),r];let n=typeof e=="function"?e():e;return t.set(n),[n,r]})}function yrt(e,t){EVa(r=>{let n=r.get();(!Array.isArray(n)||t.some((a,o)=>!Object.is(a,n[o])))&&HZi.queue(e),r.set(t)})}var d_t=aa(ise(),1);var Vwy={prefix:{idle:d_t.default.blue("?"),done:d_t.default.green(Pne.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>d_t.default.yellow(e))},style:{answer:d_t.default.cyan,message:d_t.default.bold,error:e=>d_t.default.red(`> ${e}`),defaultAnswer:e=>d_t.default.dim(`(${e})`),help:d_t.default.dim,highlight:d_t.default.cyan,key:e=>d_t.default.cyan(d_t.default.bold(`<${e}>`))}};function Wwy(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 Hwy(...e){let t={};for(let r of e)for(let[n,i]of Object.entries(r)){let a=t[n];t[n]=Wwy(a)&&Wwy(i)?Hwy(a,i):i}return t}function qK(...e){let t=[Vwy,...e.filter(r=>r!=null)];return Hwy(...t)}function Fk({status:e="idle",theme:t}){let[r,n]=PS(!1),[i,a]=PS(0),{prefix:o,spinner:c}=qK(t);return yrt(()=>{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 EVa(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 p_t(e){return PS({current:e})[0]}function zk(e){let t=p_t(e);t.current=e,yrt(r=>{let n=!1,i=_hf((a,o)=>{n||t.current(o,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var Gwy=aa(MYl(),1),Jwy=aa(zYl(),1);function p8o(e,t){return e.split(`
|
|
2362
2362
|
`).flatMap(r=>(0,Jwy.default)(r,t,{trim:!1,hard:!0}).split(`
|
|
2363
2363
|
`).map(n=>n.trimEnd())).join(`
|
|
@@ -2399,7 +2399,7 @@ ${R}${z}${V}${SVa}`});function eOu({message:e,error:t,logger:r,logLevel:n=j1.Err
|
|
|
2399
2399
|
Run ${gd.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
2400
2400
|
Run ${gd.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),QQa(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Vhf({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!Bjy(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+=`
|
|
2401
2401
|
${await zeC(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+gd.dim(c.currentVersion)+gd.reset(" \u2192 ")+gd.green(c.latestVersion);return i+=`
|
|
2402
|
-
`,n?QQa(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function zeC(e){let r=await new Mjy.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 QeC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await qjy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,u,s,l)=>{c.versions[u]==null&&(c.versions[u]={});let m=IDi(s.name,l),A=await L7r({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 qjy({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=IDi(u.name,s),m=await L7r({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 qjy({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 fIr({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 Rjy(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=Ixe(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 iOu({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await QeC({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(...Rjy(u,f,t.logger));else o.push(...Rjy(c.versions,void 0,t.logger))}return o}var O8o=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 MVa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Whf=(()=>{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})(),Njy=typeof globalThis.AbortController=="function",xjy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Fjy=typeof globalThis.ReadableStream=="function",zjy=typeof globalThis.FormData=="function",aOu=["get","post","put","patch","head","delete"],LeC=()=>{};LeC();var Qjy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},oOu=2147483647,Ljy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,sOu=Symbol("stop"),Ujy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Vjy={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 UeC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=Ljy,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},Wjy=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(i){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){let{done:c,value:f}=await a.read();if(c){i.close();return}if(t){n+=f.byteLength;let u=r===0?0:n/r;t({percent:u,transferredBytes:n,totalBytes:r},f)}i.enqueue(f),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},Hjy=(e,t,r)=>{let n=UeC(r??e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let o=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:f,value:u}=await o.read();if(f){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(n,i)},new Uint8Array),a.close();return}i+=u.byteLength;let s=n===0?0:i/n;(n<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:n},u),a.enqueue(u),await c()}await c()}})})};var BVa=e=>e!==null&&typeof e=="object";var A8o=(...e)=>{for(let t of e)if((!BVa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Jhf({},...e)},Hhf=(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 uOu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Jhf(e[r]??[],t[r]??[])}var Ghf=(e={},t={})=>({beforeRequest:uOu(e,t,"beforeRequest"),beforeRetry:uOu(e,t,"beforeRetry"),afterResponse:uOu(e,t,"afterResponse"),beforeError:uOu(e,t,"beforeError")}),Jhf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(BVa(i)){for(let[a,o]of Object.entries(i))BVa(o)&&a in t&&(o=Jhf(t[a],o)),t={...t,[a]:o};BVa(i.hooks)&&(n=Ghf(n,i.hooks),t.hooks=n),BVa(i.headers)&&(r=Hhf(r,i.headers),t.headers=r)}return t};var Jjy=e=>aOu.includes(e)?e.toUpperCase():e,VeC=["get","put","head","delete","options","trace"],WeC=[408,413,429,500,502,503,504],HeC=[413,429,503],Gjy={limit:2,methods:VeC,statusCodes:WeC,afterStatusCodes:HeC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Kjy=(e={})=>{if(typeof e=="number")return{...Gjy,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{...Gjy,...e}};async function Khf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new MVa(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function $hf(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 $jy=(e,t)=>{let r={};for(let n in t)!(n in Vjy)&&!(n in Ujy)&&!(n in e)&&(r[n]=t[n]);return r},Yjy=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 P8o=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>oOu)throw new RangeError(`The \`timeout\` option cannot be greater than ${oOu}`);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 O8o(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(!Fjy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Wjy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{n.request.bodyUsed||await n.request.body?.cancel()});for(let[c,f]of Object.entries(Qjy))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;constructor(t,r={}){if(this._input=t,this._options={...r,headers:Hhf(this._input.headers,r.headers),hooks:Ghf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Jjy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Kjy(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(Njy&&xjy){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(Whf&&(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),Yjy(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);(zjy&&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(!Whf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Hjy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof MVa)throw t;if(t instanceof O8o){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),oOu);if(this._retryCount<1)throw r;await $hf(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})===sOu)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=$jy(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Khf(r,t,this.abortController,this._options)}};var Yhf=e=>{let t=(r,n)=>P8o.create(r,A8o(e,n));for(let r of aOu)t[r]=(n,i)=>P8o.create(n,A8o(e,i,{method:r}));return t.create=r=>Yhf(A8o(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Yhf(A8o(e,r))),t.stop=sOu,t},GeC=Yhf(),Xjy=GeC;var m1y=aa(g1y(),1);function tyf(e){let t=(0,m1y.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var _Ey=aa(pEy(),1),hEy=aa(z6r(),1),_yf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},hyf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function yyf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??tyf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,_Ey.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 Xjy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new _yf(e):l}if(t.allVersions)return u;let s=new hyf(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=hEy.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 C8o(e,t){let{version:r}=await yyf(e.toLowerCase(),t);return r}async function hBi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:C8o(e.packageName,{version:t?"prerelease":"latest"})}var yEy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mOu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=j1.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new nOu(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.83.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${gd.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Loe}failWithoutThrowing(t,r){this.didSucceed=!1,eOu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IQa()).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 Tjy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2402
|
+
`,n?QQa(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function zeC(e){let r=await new Mjy.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 QeC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await qjy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,u,s,l)=>{c.versions[u]==null&&(c.versions[u]={});let m=IDi(s.name,l),A=await L7r({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 qjy({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=IDi(u.name,s),m=await L7r({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 qjy({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 fIr({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 Rjy(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=Ixe(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 iOu({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await QeC({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(...Rjy(u,f,t.logger));else o.push(...Rjy(c.versions,void 0,t.logger))}return o}var O8o=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 MVa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Whf=(()=>{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})(),Njy=typeof globalThis.AbortController=="function",xjy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Fjy=typeof globalThis.ReadableStream=="function",zjy=typeof globalThis.FormData=="function",aOu=["get","post","put","patch","head","delete"],LeC=()=>{};LeC();var Qjy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},oOu=2147483647,Ljy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,sOu=Symbol("stop"),Ujy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Vjy={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 UeC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=Ljy,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},Wjy=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(i){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){let{done:c,value:f}=await a.read();if(c){i.close();return}if(t){n+=f.byteLength;let u=r===0?0:n/r;t({percent:u,transferredBytes:n,totalBytes:r},f)}i.enqueue(f),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},Hjy=(e,t,r)=>{let n=UeC(r??e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let o=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:f,value:u}=await o.read();if(f){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(n,i)},new Uint8Array),a.close();return}i+=u.byteLength;let s=n===0?0:i/n;(n<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:n},u),a.enqueue(u),await c()}await c()}})})};var BVa=e=>e!==null&&typeof e=="object";var A8o=(...e)=>{for(let t of e)if((!BVa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Jhf({},...e)},Hhf=(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 uOu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Jhf(e[r]??[],t[r]??[])}var Ghf=(e={},t={})=>({beforeRequest:uOu(e,t,"beforeRequest"),beforeRetry:uOu(e,t,"beforeRetry"),afterResponse:uOu(e,t,"afterResponse"),beforeError:uOu(e,t,"beforeError")}),Jhf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(BVa(i)){for(let[a,o]of Object.entries(i))BVa(o)&&a in t&&(o=Jhf(t[a],o)),t={...t,[a]:o};BVa(i.hooks)&&(n=Ghf(n,i.hooks),t.hooks=n),BVa(i.headers)&&(r=Hhf(r,i.headers),t.headers=r)}return t};var Jjy=e=>aOu.includes(e)?e.toUpperCase():e,VeC=["get","put","head","delete","options","trace"],WeC=[408,413,429,500,502,503,504],HeC=[413,429,503],Gjy={limit:2,methods:VeC,statusCodes:WeC,afterStatusCodes:HeC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Kjy=(e={})=>{if(typeof e=="number")return{...Gjy,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{...Gjy,...e}};async function Khf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new MVa(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function $hf(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 $jy=(e,t)=>{let r={};for(let n in t)!(n in Vjy)&&!(n in Ujy)&&!(n in e)&&(r[n]=t[n]);return r},Yjy=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 P8o=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>oOu)throw new RangeError(`The \`timeout\` option cannot be greater than ${oOu}`);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 O8o(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(!Fjy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Wjy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{n.request.bodyUsed||await n.request.body?.cancel()});for(let[c,f]of Object.entries(Qjy))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;constructor(t,r={}){if(this._input=t,this._options={...r,headers:Hhf(this._input.headers,r.headers),hooks:Ghf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Jjy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Kjy(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(Njy&&xjy){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(Whf&&(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),Yjy(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);(zjy&&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(!Whf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Hjy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof MVa)throw t;if(t instanceof O8o){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),oOu);if(this._retryCount<1)throw r;await $hf(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})===sOu)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=$jy(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Khf(r,t,this.abortController,this._options)}};var Yhf=e=>{let t=(r,n)=>P8o.create(r,A8o(e,n));for(let r of aOu)t[r]=(n,i)=>P8o.create(n,A8o(e,i,{method:r}));return t.create=r=>Yhf(A8o(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Yhf(A8o(e,r))),t.stop=sOu,t},GeC=Yhf(),Xjy=GeC;var m1y=aa(g1y(),1);function tyf(e){let t=(0,m1y.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var _Ey=aa(pEy(),1),hEy=aa(z6r(),1),_yf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},hyf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function yyf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??tyf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,_Ey.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 Xjy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new _yf(e):l}if(t.allVersions)return u;let s=new hyf(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=hEy.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 C8o(e,t){let{version:r}=await yyf(e.toLowerCase(),t);return r}async function hBi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:C8o(e.packageName,{version:t?"prerelease":"latest"})}var yEy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mOu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=j1.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new nOu(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.83.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${gd.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Loe}failWithoutThrowing(t,r){this.didSucceed=!1,eOu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IQa()).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 Tjy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2403
2403
|
`)||(r+=`
|
|
2404
2404
|
`),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=GFl(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 h8o(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 Loe}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await IQa()).sendEvent(t)}logger=r4r((t,...r)=>this.log(t,...r));stderr=r4r((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=vEy(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?vEy(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=yEy[this.numTasks++%yEy.length],o=gd.hex(a)(i);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===C9.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=>USi.indexOf(i.level)>=USi.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===j1.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 hBi({cliEnvironment:this.environment,includePreReleases:t}),n=Ixe(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await iOu({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Dhf({message:t,default:r})}async getInput(t){return await Chf({message:t.message,default:t.default})}};function vEy(e){return`[${e}]:`}var aMr=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 brt=class extends aMr{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 oMr={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0};function I8o({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??oMr.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??oMr.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??oMr.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??oMr.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??oMr.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??oMr.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??oMr.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??oMr.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??oMr.respectForwardCompatibleEnums,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??oMr.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??oMr.coerceOptionalSchemasToNullable}}var fPe={openapi:e=>({...e,type:"openapi",_visit:function(t){return fPe._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return fPe._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 zVa={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return zVa._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var $fe={basic:e=>({...e,type:"basic",_visit:function(t){return $fe._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return $fe._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return $fe._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return $fe._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return $fe._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 ZE={primitive:e=>({value:e,type:"primitive",_visit:function(t){return ZE._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ZE._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return ZE._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return ZE._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return ZE._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return ZE._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ZE._visit(this,t)}}),null:e=>({...e,type:"null",_visit:function(t){return ZE._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return ZE._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 pO={int:e=>({value:e,type:"int",_visit:function(t){return pO._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return pO._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return pO._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return pO._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return pO._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return pO._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return pO._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return pO._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return pO._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return pO._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return pO._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 yBi={boolean:e=>({value:e,type:"boolean",_visit:function(t){return yBi._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return yBi._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 vBi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return vBi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return vBi._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 OOu={};lf(OOu,{Availability:()=>Yfe,CustomCodeSample:()=>UQr,EndpointExample:()=>y_t,EndpointResponseExample:()=>v_t,HttpMethod:()=>Zfe,LiteralSchemaValue:()=>K9,MultipartRequestPropertyEncoding:()=>gyf,MultipartSchema:()=>VQr,OneOfSchema:()=>WQr,Pagination:()=>grt,PrimitiveSchemaValue:()=>KT,Request:()=>sMr,Response:()=>zve,RetriesConfiguration:()=>M8o,Schema:()=>Ij,SupportedSdkLanguage:()=>Xfe,WebhookHttpMethod:()=>byf,WebsocketMessageOrigin:()=>vyf});var vyf={Client:"client",Server:"server",_visit:(e,t)=>{switch(e){case vyf.Client:return t.client();case vyf.Server:return t.server();default:return t._other()}}};var byf={Get:"GET",Post:"POST",_visit:(e,t)=>{switch(e){case byf.Get:return t.get();case byf.Post:return t.post();default:return t._other()}}};var Yfe={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case Yfe.GenerallyAvailable:return t.generallyAvailable();case Yfe.Beta:return t.beta();case Yfe.Deprecated:return t.deprecated();default:return t._other()}}};var M8o={disabled:e=>({value:e,type:"disabled",_visit:function(t){return M8o._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"disabled":return t.disabled(e.value);default:return t._other(e)}}};var grt={cursor:e=>({...e,type:"cursor",_visit:function(t){return grt._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return grt._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return grt._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 UQr={language:e=>({...e,type:"language",_visit:function(t){return UQr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return UQr._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 Xfe={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 Xfe.Curl:return t.curl();case Xfe.Python:return t.python();case Xfe.Javascript:return t.javascript();case Xfe.Typescript:return t.typescript();case Xfe.Go:return t.go();case Xfe.Ruby:return t.ruby();case Xfe.Csharp:return t.csharp();case Xfe.Java:return t.java();case Xfe.Js:return t.js();case Xfe.Node:return t.node();case Xfe.Ts:return t.ts();case Xfe.Nodets:return t.nodets();case Xfe.Golang:return t.golang();case Xfe.Dotnet:return t.dotnet();case Xfe.Jvm:return t.jvm();default:return t._other()}}};var y_t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return y_t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return y_t._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 v_t={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return v_t._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return v_t._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 Zfe={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case Zfe.Get:return t.get();case Zfe.Post:return t.post();case Zfe.Put:return t.put();case Zfe.Patch:return t.patch();case Zfe.Delete:return t.delete();case Zfe.Head:return t.head();case Zfe.Options:return t.options();case Zfe.Trace:return t.trace();default:return t._other()}}};var sMr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return sMr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return sMr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return sMr._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return sMr._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 gyf={Json:"json",Form:"form",_visit:(e,t)=>{switch(e){case gyf.Json:return t.json();case gyf.Form:return t.form();default:return t._other()}}};var VQr={file:e=>({...e,type:"file",_visit:function(t){return VQr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return VQr._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 zve={file:e=>({...e,type:"file",_visit:function(t){return zve._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return zve._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return zve._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return zve._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return zve._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return zve._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return zve._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 Ij={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ij._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ij._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ij._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ij._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ij._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ij._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ij._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ij._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ij._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ij._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ij._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 KT={int:e=>({...e,type:"int",_visit:function(t){return KT._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return KT._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return KT._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return KT._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return KT._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return KT._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return KT._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return KT._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return KT._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return KT._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return KT._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 K9={boolean:e=>({value:e,type:"boolean",_visit:function(t){return K9._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return K9._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 WQr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return WQr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return WQr._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 WDe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return WDe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return WDe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return WDe._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return WDe._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 dL={file:e=>({...e,type:"file",_visit:function(t){return dL._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return dL._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return dL._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return dL._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return dL._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return dL._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return dL._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 ny={primitive:e=>({...e,type:"primitive",_visit:function(t){return ny._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ny._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return ny._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return ny._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return ny._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return ny._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return ny._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return ny._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ny._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return ny._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return ny._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 mrt={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return mrt._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return mrt._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 R0={int:e=>({...e,type:"int",_visit:function(t){return R0._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return R0._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return R0._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return R0._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return R0._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return R0._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return R0._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return R0._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return R0._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return R0._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return R0._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 uj={};lf(uj,{AllOfPropertyConflict:()=>fWa,ArraySchema:()=>FAu,ArraySchemaWithExample:()=>hPu,Availability:()=>MOu,Base64WithExample:()=>lPu,BasicSecurityScheme:()=>TOu,BearerSecurityScheme:()=>qOu,BooleanSchema:()=>BAu,BooleanWithExample:()=>fPu,BytesResponse:()=>tWa,CasingOverrides:()=>xOu,CommonProperty:()=>GAu,CommonPropertyWithExample:()=>wPu,CursorPagination:()=>hAu,CustomCodeSample:()=>pAu,CustomCodeSampleLanguage:()=>lAu,CustomCodeSampleSdk:()=>dAu,CustomPagination:()=>vAu,DateWithExample:()=>cPu,DatetimeWithExample:()=>uPu,DiscriminatedOneOfSchema:()=>WAu,DiscriminatedOneOfSchemaWithExample:()=>APu,DoubleSchema:()=>IAu,DoubleWithExample:()=>oPu,Encoding:()=>IOu,Endpoint:()=>bAu,EndpointExample:()=>aWa,EndpointResponseExample:()=>cAu,EndpointSdkName:()=>JQr,EndpointSecurity:()=>JVa,EndpointWithExample:()=>JEy,EnumSchema:()=>WVa,EnumSchemaWithExample:()=>pPu,EnumValue:()=>mBi,ErrorExample:()=>iAu,FernExample:()=>oAu,FileResponse:()=>kVa,FileSchema:()=>YOu,FloatWithExample:()=>aPu,FormUrlEncodedRequest:()=>tAu,FullEndpointExample:()=>_Au,FullExample:()=>N8,FullObjectExample:()=>HOu,FullOneOfExample:()=>JOu,GlobalHeader:()=>qAu,Header:()=>ABi,HeaderExample:()=>iWa,HeaderSecurityScheme:()=>ROu,HeaderWithExample:()=>jBi,HttpEndpointServer:()=>rWa,HttpError:()=>aAu,HttpErrorWithExample:()=>ePu,HttpMethod:()=>KVa,IdempotencyHeader:()=>RAu,Int64WithExample:()=>rPu,IntSchema:()=>DAu,IntWithExample:()=>tPu,JsonRequest:()=>eAu,JsonRequestWithExample:()=>YAu,JsonResponse:()=>eWa,JsonResponseWithExample:()=>_Wa,KeyValuePair:()=>GOu,LiteralExample:()=>VOu,LiteralSchema:()=>lWa,LiteralSchemaValue:()=>NAu,LongSchema:()=>CAu,MapSchema:()=>zAu,MapSchemaWithExample:()=>yPu,MultipartRequest:()=>ZVa,MultipartRequestProperty:()=>kOu,MultipartRequestPropertyEncoding:()=>ZOu,MultipartSchema:()=>XOu,NamedFullExample:()=>g_t,Namespace:()=>FOu,NamespaceId:()=>UOu,NullExample:()=>WOu,NullableSchema:()=>LAu,NullableSchemaWithExample:()=>bPu,OauthSecurityScheme:()=>QOu,ObjectProperty:()=>VAu,ObjectPropertyConflictInfo:()=>dWa,ObjectPropertyWithExample:()=>OPu,ObjectSchema:()=>xAu,ObjectSchemaWithExample:()=>gPu,OctetStreamRequest:()=>XVa,OffsetPagination:()=>yAu,OneOfSchema:()=>UAu,OneOfSchemaWithExample:()=>mPu,OpenApiIntermediateRepresentation:()=>HEy,OpenApiSource:()=>EOu,OptionalSchema:()=>QAu,OptionalSchemaWithExample:()=>vPu,Pagination:()=>oWa,ParseFormUrlEncodedRequest:()=>XAu,ParseMultipartRequest:()=>$Au,ParseOctetStreamRequest:()=>KAu,PathParameter:()=>$Va,PathParameterExample:()=>sAu,PathParameterWithExample:()=>JAu,PrimitiveExample:()=>GVa,PrimitiveSchema:()=>wBi,PrimitiveSchemaValue:()=>TAu,PrimitiveSchemaValueWithExample:()=>dPu,PrimitiveSchemaWithExample:()=>hWa,PropertyKey:()=>HVa,ProtobufEncoding:()=>COu,ProtobufSource:()=>SOu,QueryParameter:()=>YVa,QueryParameterExample:()=>nWa,QueryParameterWithExample:()=>pWa,QuerySecurityScheme:()=>NOu,ReferencedSchema:()=>KQr,Request:()=>rAu,RequestWithExample:()=>ZAu,Response:()=>nAu,ResponseWithExample:()=>kAu,RetriesConfiguration:()=>sWa,Schema:()=>eI,SchemaId:()=>HDe,SchemaWithExample:()=>yz,Schemas:()=>SAu,SdkGroup:()=>zOu,SdkGroupInfo:()=>KOu,SdkGroupName:()=>OBi,SecurityScheme:()=>LOu,SecuritySchemeId:()=>VVa,Server:()=>R8o,Source:()=>DOu,StatusCode:()=>HQr,StreamingResponseExample:()=>uAu,StringSchema:()=>MAu,StringSchemaWithExample:()=>sPu,SupportedSdkLanguage:()=>fAu,Tag:()=>BOu,TagId:()=>GDe,Tags:()=>$Ou,TextResponse:()=>PBi,Uint64WithExample:()=>iPu,UintWithExample:()=>nPu,UnDiscriminatedOneOfSchema:()=>HAu,UnDiscriminatedOneOfSchemaWithExample:()=>PPu,UnknownSchemaWithExample:()=>_Pu,Webhook:()=>gAu,WebhookExampleCall:()=>cWa,WebhookHttpMethod:()=>uWa,WebhookWithExample:()=>KEy,WebsocketChannel:()=>EAu,WebsocketHandshake:()=>mAu,WebsocketHandshakeWithExample:()=>GEy,WebsocketMessageExample:()=>wAu,WebsocketMessageOrigin:()=>OAu,WebsocketMessageSchema:()=>AAu,WebsocketServer:()=>PAu,WebsocketSessionExample:()=>jAu,WithAvailability:()=>gP,WithDescription:()=>Xy,WithEncoding:()=>Bxe,WithInline:()=>hz,WithName:()=>QS,WithNamespace:()=>kE,WithSdkGroupName:()=>XI,WithSdkMethodName:()=>GQr,WithSource:()=>QA,WithStatusCode:()=>b_t,WithTitle:()=>YI,commons:()=>wyf,example:()=>jyf,finalIr:()=>Eyf,parseIr:()=>Syf});var wyf={};lf(wyf,{BasicSecurityScheme:()=>TOu,BearerSecurityScheme:()=>qOu,Encoding:()=>IOu,HeaderSecurityScheme:()=>ROu,Namespace:()=>FOu,NamespaceId:()=>UOu,OauthSecurityScheme:()=>QOu,OpenApiSource:()=>EOu,ProtobufEncoding:()=>COu,ProtobufSource:()=>SOu,QuerySecurityScheme:()=>NOu,SchemaId:()=>HDe,SdkGroup:()=>zOu,SdkGroupName:()=>OBi,SecurityScheme:()=>LOu,SecuritySchemeId:()=>VVa,Server:()=>R8o,Source:()=>DOu,StatusCode:()=>HQr,Tag:()=>BOu,TagId:()=>GDe,WithAvailability:()=>gP,WithDescription:()=>Xy,WithEncoding:()=>Bxe,WithInline:()=>hz,WithName:()=>QS,WithNamespace:()=>kE,WithSdkGroupName:()=>XI,WithSdkMethodName:()=>GQr,WithSource:()=>QA,WithStatusCode:()=>b_t,WithTitle:()=>YI});var Gr={};lf(Gr,{JsonError:()=>QVa,ParseError:()=>LVa,any:()=>BEy,bigint:()=>gEy,boolean:()=>TEy,booleanLiteral:()=>MEy,date:()=>mEy,discriminant:()=>UEy,enum_:()=>POu,getObjectLikeUtils:()=>uMr,getObjectUtils:()=>nki,getSchemaUtils:()=>R8,isProperty:()=>gBi,lazy:()=>OEy,lazyObject:()=>DEy,list:()=>jOu,number:()=>qEy,object:()=>wOu,objectWithoutOptionalProperties:()=>SEy,optional:()=>myf,property:()=>PEy,record:()=>FEy,set:()=>zEy,string:()=>REy,stringLiteral:()=>IEy,transform:()=>Oyf,undiscriminatedUnion:()=>LEy,union:()=>WEy,unknown:()=>NEy,withParsedProperties:()=>Pyf});var $T={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 b4(e,t){return`Expected ${t}. Received ${ZtC(e)}.`}function ZtC(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 kfe(e){return{...e,json:bEy(e.json),parse:bEy(e.parse)}}function bEy(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(`
|
|
2405
2405
|
`)),{ok:!0,value:t}):n}}function AOu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var QVa=class e extends Error{errors;constructor(t){super(t.map(AOu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var LVa=class e extends Error{errors;constructor(t){super(t.map(AOu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function R8(e){return{optional:()=>myf(e),transform:t=>Oyf(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new LVa(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new QVa(n.errors)}}}function myf(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:()=>$T.OPTIONAL};return{...t,...R8(t)}}function Oyf(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,...R8(r)}}function gEy(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:b4(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:b4(t,"bigint")}]},getType:()=>$T.BIGINT};return{...kfe(e),...R8(e)}}var ktC=/^([+-]?\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 mEy(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:b4(t,"string")}]}:ktC.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:b4(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:b4(t,"Date object")}]},getType:()=>$T.DATE};return{...kfe(e),...R8(e)}}function dPe(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...kfe(r),...R8(r)}}}function POu(e){let t=new Set(e);return dPe($T.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:a=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:a,message:b4(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:a,message:b4(n,"enum")}]}:{ok:!0,value:n})()}function OEy(e){let t=Ayf(e);return{...t,...R8(t)}}function Ayf(e){return{parse:(t,r)=>UVa(e).parse(t,r),json:(t,r)=>UVa(e).json(t,r),getType:()=>UVa(e).getType()}}function UVa(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function B8o(e){return Object.entries(e)}function T8o(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,a])=>(r.has(i)&&(n[i]=a),n),{})}function bBi(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 q8o(e){return Object.keys(e)}function AEy(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}function uMr(e){return{withParsedProperties:t=>Pyf(e,t)}}function Pyf(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(!bBi(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:b4(n,"object")}]};let a=new Set(Object.keys(t)),o=T8o(n,Object.keys(n).filter(c=>!a.has(c)));return e.json(o,i)},getType:()=>e.getType()};return{...r,...R8(r),...uMr(r)}}function PEy(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function gBi(e){return e.isProperty}function wOu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,n])=>gBi(n)?n.rawKey:r),_getParsedProperties:()=>q8o(e),parse:(r,n)=>{let i={},a=[];for(let[o,c]of B8o(e)){let f=gBi(c)?c.rawKey:o,u=gBi(c)?c.valueSchema:c,s={rawKey:f,parsedKey:o,valueSchema:u};i[f]=s,EEy(u)&&a.push(f)}return wEy({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 B8o(e)){let c=gBi(o)?o.valueSchema:o;EEy(c)&&i.push(a)}return wEy({value:r,requiredKeys:i,getProperty:a=>{let o=e[a];if(o!=null)return gBi(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:()=>$T.OBJECT};return{...kfe(t),...R8(t),...uMr(t),...nki(t)}}function wEy({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:n="fail",skipValidation:i=!1,breadcrumbsPrefix:a=[]}){if(!bBi(e))return{ok:!1,errors:[{path:a,message:b4(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 nki(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>jEy({extensionKeys:t._getRawProperties(),value:n,transformBase:a=>e.parse(a,i),transformExtension:a=>t.parse(a,i)}),json:(n,i)=>jEy({extensionKeys:t._getParsedProperties(),value:n,transformBase:a=>e.json(a,i),transformExtension:a=>t.json(a,i)}),getType:()=>$T.OBJECT};return{...r,...R8(r),...uMr(r),...nki(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:()=>$T.OBJECT};return{...t,...R8(t),...uMr(t),...nki(t)}}}}function jEy({extensionKeys:e,value:t,transformBase:r,transformExtension:n}){let i=new Set(e),[a,o]=AEy(q8o(t),u=>i.has(u)),c=r(T8o(t,o)),f=n(T8o(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 EEy(e){return!erC(e)}function erC(e){switch(e.getType()){case $T.ANY:case $T.UNKNOWN:case $T.OPTIONAL:return!0;default:return!1}}function SEy(e){return wOu(e)}function DEy(e){let t={...Ayf(e),_getRawProperties:()=>UVa(e)._getRawProperties(),_getParsedProperties:()=>UVa(e)._getParsedProperties()};return{...t,...R8(t),...uMr(t),...nki(t)}}function jOu(e){let t={parse:(r,n)=>CEy(r,(i,a)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,n)=>CEy(r,(i,a)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>$T.LIST};return{...kfe(t),...R8(t)}}function CEy(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:b4(e,"list"),path:[]}]}}function IEy(e){return dPe($T.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:b4(r,`"${e}"`)}]})()}function MEy(e){return dPe($T.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:b4(r,`${e.toString()}`)}]})()}var BEy=dPe($T.ANY,e=>({ok:!0,value:e}));var TEy=dPe($T.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:b4(e,"boolean")}]});var qEy=dPe($T.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:b4(e,"number")}]});var REy=dPe($T.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:b4(e,"string")}]});var NEy=dPe($T.UNKNOWN,e=>({ok:!0,value:e}));function FEy(e,t){let r={parse:(n,i)=>xEy({value:n,isKeyNumeric:e.getType()===$T.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)=>xEy({value:n,isKeyNumeric:e.getType()===$T.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:()=>$T.RECORD};return{...kfe(r),...R8(r)}}function xEy({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){return bBi(e)?B8o(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:b4(e,"object")}]}}function zEy(e){let t=jOu(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:b4(n,"Set")}]},getType:()=>$T.SET};return{...kfe(r),...R8(r)}}function LEy(e){let t={parse:(r,n)=>QEy((i,a)=>i.parse(r,a),e,n),json:(r,n)=>QEy((i,a)=>i.json(r,a),e,n),getType:()=>$T.UNDISCRIMINATED_UNION};return{...kfe(t),...R8(t)}}function QEy(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 UEy(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function WEy(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=POu(q8o(t)),a={parse:(o,c)=>VEy({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)=>VEy({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:()=>$T.UNION};return{...kfe(a),...R8(a),...uMr(a)}}function VEy({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!bBi(e))return{ok:!1,errors:[{path:c,message:b4(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 YI=Gr.objectWithoutOptionalProperties({title:Gr.string().optional()});var EOu=Gr.objectWithoutOptionalProperties({file:Gr.string()});var SOu=Gr.objectWithoutOptionalProperties({file:Gr.string()});var DOu=Gr.union("type",{openapi:EOu,protobuf:SOu}).transform({transform:e=>{switch(e.type){case"openapi":return fPe.openapi(e);case"protobuf":return fPe.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var QA=Gr.objectWithoutOptionalProperties({source:DOu.optional()});var COu=Gr.objectWithoutOptionalProperties({typeName:Gr.string()});var IOu=Gr.union("type",{protobuf:COu}).transform({transform:e=>{switch(e.type){case"protobuf":return zVa.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Bxe=Gr.objectWithoutOptionalProperties({encoding:IOu.optional()});var Xy=Gr.objectWithoutOptionalProperties({description:Gr.string().optional()});var MOu=Gr.enum_(["GenerallyAvailable","Beta","Deprecated"]);var gP=Gr.objectWithoutOptionalProperties({availability:MOu.optional()});var HQr=Gr.number();var b_t=Gr.objectWithoutOptionalProperties({statusCode:HQr.optional()});var QS=Gr.objectWithoutOptionalProperties({nameOverride:Gr.string().optional(),generatedName:Gr.string()});var hz=Gr.objectWithoutOptionalProperties({inline:Gr.boolean().optional()});var HDe=Gr.string();var GDe=Gr.string();var BOu=Gr.objectWithoutOptionalProperties({id:GDe}).extend(Xy);var VVa=Gr.string();var TOu=Gr.objectWithoutOptionalProperties({usernameVariableName:Gr.string().optional(),usernameEnvVar:Gr.string().optional(),passwordVariableName:Gr.string().optional(),passwordEnvVar:Gr.string().optional()});var qOu=Gr.objectWithoutOptionalProperties({tokenVariableName:Gr.string().optional(),tokenEnvVar:Gr.string().optional()});var ROu=Gr.objectWithoutOptionalProperties({headerName:Gr.string(),prefix:Gr.string().optional(),headerVariableName:Gr.string().optional(),headerEnvVar:Gr.string().optional()});var NOu=Gr.objectWithoutOptionalProperties({queryParameterName:Gr.string()});var xOu=Gr.objectWithoutOptionalProperties({snake:Gr.string().optional(),camel:Gr.string().optional(),screamingSnake:Gr.string().optional(),pascal:Gr.string().optional()});var mBi=Gr.objectWithoutOptionalProperties({nameOverride:Gr.string().optional(),generatedName:Gr.string(),value:Gr.string(),casing:xOu.optional()}).extend(Xy).extend(gP);var FOu=Gr.objectWithoutOptionalProperties({type:Gr.stringLiteral("namespace"),name:Gr.string()});var zOu=Gr.undiscriminatedUnion([Gr.string(),FOu]);var OBi=Gr.list(zOu);var XI=Gr.objectWithoutOptionalProperties({groupName:OBi.optional()});var kE=Gr.objectWithoutOptionalProperties({namespace:Gr.string().optional()});var WVa=Gr.objectWithoutOptionalProperties({default:mBi.optional(),values:Gr.list(mBi)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(QA).extend(YI).extend(hz);var QOu=Gr.objectWithoutOptionalProperties({scopesEnum:WVa.optional()});var LOu=Gr.union("type",{basic:TOu,bearer:qOu,header:ROu,query:NOu,oauth:QOu}).transform({transform:e=>{switch(e.type){case"basic":return $fe.basic(e);case"bearer":return $fe.bearer(e);case"header":return $fe.header(e);case"query":return $fe.query(e);case"oauth":return $fe.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var R8o=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),url:Gr.string(),audiences:Gr.list(Gr.string()).optional()}).extend(Xy);var UOu=Gr.string();var GQr=Gr.objectWithoutOptionalProperties({sdkMethodName:Gr.string().optional()});var jyf={};lf(jyf,{FullExample:()=>N8,FullObjectExample:()=>HOu,FullOneOfExample:()=>JOu,KeyValuePair:()=>GOu,LiteralExample:()=>VOu,NullExample:()=>WOu,PrimitiveExample:()=>GVa,PropertyKey:()=>HVa});var HVa=Gr.string();var GVa=Gr.union("type",{int:Gr.object({value:Gr.number()}),int64:Gr.object({value:Gr.number()}),uint:Gr.object({value:Gr.number()}),uint64:Gr.object({value:Gr.number()}),float:Gr.object({value:Gr.number()}),double:Gr.object({value:Gr.number()}),string:Gr.object({value:Gr.string()}),datetime:Gr.object({value:Gr.string()}),date:Gr.object({value:Gr.string()}),base64:Gr.object({value:Gr.string()}),boolean:Gr.object({value:Gr.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return pO.int(e.value);case"int64":return pO.int64(e.value);case"uint":return pO.uint(e.value);case"uint64":return pO.uint64(e.value);case"float":return pO.float(e.value);case"double":return pO.double(e.value);case"string":return pO.string(e.value);case"datetime":return pO.datetime(e.value);case"date":return pO.date(e.value);case"base64":return pO.base64(e.value);case"boolean":return pO.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var VOu=Gr.union("type",{boolean:Gr.object({value:Gr.boolean()}),string:Gr.object({value:Gr.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return yBi.boolean(e.value);case"string":return yBi.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var WOu=Gr.objectWithoutOptionalProperties({});var N8=Gr.union("type",{primitive:Gr.object({value:GVa}),object:Gr.lazyObject(()=>HOu),array:Gr.object({value:Gr.list(Gr.lazy(()=>N8))}),map:Gr.object({value:Gr.list(Gr.lazyObject(()=>GOu))}),enum:Gr.object({value:Gr.string()}),literal:Gr.object({value:VOu}),oneOf:Gr.object({value:Gr.lazy(()=>JOu)}),null:WOu,unknown:Gr.object({value:Gr.lazy(()=>N8)})}).transform({transform:e=>{switch(e.type){case"primitive":return ZE.primitive(e.value);case"object":return ZE.object(e);case"array":return ZE.array(e.value);case"map":return ZE.map(e.value);case"enum":return ZE.enum(e.value);case"literal":return ZE.literal(e.value);case"oneOf":return ZE.oneOf(e.value);case"null":return ZE.null(e);case"unknown":return ZE.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var HOu=Gr.objectWithoutOptionalProperties({properties:Gr.record(HVa,Gr.lazy(()=>N8))});var GOu=Gr.objectWithoutOptionalProperties({key:GVa,value:Gr.lazy(()=>N8)});var JOu=Gr.union("type",{discriminated:Gr.object({value:Gr.record(HVa,Gr.lazy(()=>N8))}),undiscriminated:Gr.object({value:Gr.lazy(()=>N8)})}).transform({transform:e=>{switch(e.type){case"discriminated":return vBi.discriminated(e.value);case"undiscriminated":return vBi.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Eyf={};lf(Eyf,{AllOfPropertyConflict:()=>fWa,ArraySchema:()=>FAu,Availability:()=>MOu,BooleanSchema:()=>BAu,BytesResponse:()=>tWa,CasingOverrides:()=>xOu,CommonProperty:()=>GAu,CursorPagination:()=>hAu,CustomCodeSample:()=>pAu,CustomCodeSampleLanguage:()=>lAu,CustomCodeSampleSdk:()=>dAu,CustomPagination:()=>vAu,DiscriminatedOneOfSchema:()=>WAu,DoubleSchema:()=>IAu,Endpoint:()=>bAu,EndpointExample:()=>aWa,EndpointResponseExample:()=>cAu,EndpointSdkName:()=>JQr,EndpointSecurity:()=>JVa,EnumSchema:()=>WVa,EnumValue:()=>mBi,ErrorExample:()=>iAu,FernExample:()=>oAu,FileResponse:()=>kVa,FileSchema:()=>YOu,FormUrlEncodedRequest:()=>tAu,FullEndpointExample:()=>_Au,GlobalHeader:()=>qAu,Header:()=>ABi,HeaderExample:()=>iWa,HttpEndpointServer:()=>rWa,HttpError:()=>aAu,HttpMethod:()=>KVa,IdempotencyHeader:()=>RAu,IntSchema:()=>DAu,JsonRequest:()=>eAu,JsonResponse:()=>eWa,LiteralSchema:()=>lWa,LiteralSchemaValue:()=>NAu,LongSchema:()=>CAu,MapSchema:()=>zAu,MultipartRequest:()=>ZVa,MultipartRequestProperty:()=>kOu,MultipartRequestPropertyEncoding:()=>ZOu,MultipartSchema:()=>XOu,NullableSchema:()=>LAu,ObjectProperty:()=>VAu,ObjectPropertyConflictInfo:()=>dWa,ObjectSchema:()=>xAu,OctetStreamRequest:()=>XVa,OffsetPagination:()=>yAu,OneOfSchema:()=>UAu,OpenApiIntermediateRepresentation:()=>HEy,OptionalSchema:()=>QAu,Pagination:()=>oWa,PathParameter:()=>$Va,PathParameterExample:()=>sAu,PrimitiveSchema:()=>wBi,PrimitiveSchemaValue:()=>TAu,QueryParameter:()=>YVa,QueryParameterExample:()=>nWa,ReferencedSchema:()=>KQr,Request:()=>rAu,Response:()=>nAu,RetriesConfiguration:()=>sWa,Schema:()=>eI,Schemas:()=>SAu,SdkGroupInfo:()=>KOu,StreamingResponseExample:()=>uAu,StringSchema:()=>MAu,SupportedSdkLanguage:()=>fAu,Tags:()=>$Ou,TextResponse:()=>PBi,UnDiscriminatedOneOfSchema:()=>HAu,Webhook:()=>gAu,WebhookExampleCall:()=>cWa,WebhookHttpMethod:()=>uWa,WebsocketChannel:()=>EAu,WebsocketHandshake:()=>mAu,WebsocketMessageExample:()=>wAu,WebsocketMessageOrigin:()=>OAu,WebsocketMessageSchema:()=>AAu,WebsocketServer:()=>PAu,WebsocketSessionExample:()=>jAu});var KOu=Gr.objectWithoutOptionalProperties({summary:Gr.string().optional(),description:Gr.string().optional()});var $Ou=Gr.objectWithoutOptionalProperties({tagsById:Gr.record(GDe,BOu),orderedTagIds:Gr.list(GDe).optional()});var JVa=Gr.list(Gr.record(VVa,Gr.list(Gr.string())));var KVa=Gr.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var $Va=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>eI),variableReference:Gr.string().optional(),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var YVa=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>eI),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var ABi=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>eI),env:Gr.string().optional(),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var JQr=Gr.objectWithoutOptionalProperties({groupName:OBi,methodName:Gr.string()});var XVa=Gr.objectWithoutOptionalProperties({contentType:Gr.string().optional()}).extend(Xy).extend(QA);var YOu=Gr.objectWithoutOptionalProperties({isOptional:Gr.boolean(),isArray:Gr.boolean()}).extend(Xy);var XOu=Gr.union("type",{file:YOu,json:Gr.object({value:Gr.lazy(()=>eI)})}).transform({transform:e=>{switch(e.type){case"file":return VQr.file(e);case"json":return VQr.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var ZOu=Gr.enum_(["json","form"]);var kOu=Gr.objectWithoutOptionalProperties({key:Gr.string(),schema:XOu,contentType:Gr.string().optional(),exploded:Gr.boolean().optional(),encoding:ZOu.optional()}).extend(Xy);var ZVa=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),properties:Gr.list(kOu)}).extend(Xy).extend(QA);var eAu=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>eI),contentType:Gr.string().optional(),additionalProperties:Gr.boolean()}).extend(Xy).extend(QA);var tAu=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>eI),contentType:Gr.string().optional(),additionalProperties:Gr.boolean()}).extend(Xy).extend(QA);var rAu=Gr.union("type",{octetStream:XVa,multipart:ZVa,json:eAu,formUrlEncoded:tAu}).transform({transform:e=>{switch(e.type){case"octetStream":return sMr.octetStream(e);case"multipart":return sMr.multipart(e);case"json":return sMr.json(e);case"formUrlEncoded":return sMr.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var kVa=Gr.objectWithoutOptionalProperties({}).extend(Xy).extend(QA).extend(b_t);var eWa=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>eI),responseProperty:Gr.string().optional()}).extend(Xy).extend(QA).extend(b_t);var PBi=Gr.objectWithoutOptionalProperties({}).extend(Xy).extend(QA).extend(b_t);var tWa=Gr.objectWithoutOptionalProperties({}).extend(Xy).extend(QA).extend(b_t);var nAu=Gr.union("type",{file:kVa,json:eWa,text:PBi,bytes:tWa,streamingSse:eWa,streamingText:PBi,streamingJson:eWa}).transform({transform:e=>{switch(e.type){case"file":return zve.file(e);case"json":return zve.json(e);case"text":return zve.text(e);case"bytes":return zve.bytes(e);case"streamingSse":return zve.streamingSse(e);case"streamingText":return zve.streamingText(e);case"streamingJson":return zve.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var iAu=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),description:Gr.string().optional(),example:Gr.lazy(()=>N8)});var aAu=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>eI).optional(),examples:Gr.list(iAu).optional()}).extend(Xy).extend(QS).extend(QA);var rWa=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),url:Gr.string().optional(),audiences:Gr.list(Gr.string()).optional()});var oAu=Gr.unknown();var sAu=Gr.objectWithoutOptionalProperties({name:Gr.string(),parameterNameOverride:Gr.string().optional(),value:Gr.lazy(()=>N8)});var nWa=Gr.objectWithoutOptionalProperties({name:Gr.string(),value:Gr.lazy(()=>N8)});var iWa=Gr.objectWithoutOptionalProperties({name:Gr.string(),value:Gr.lazy(()=>N8)});var uAu=Gr.objectWithoutOptionalProperties({sse:Gr.boolean(),events:Gr.list(Gr.lazy(()=>N8))});var cAu=Gr.union("type",{withStreaming:uAu,withoutStreaming:Gr.object({value:Gr.lazy(()=>N8)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return v_t.withStreaming(e);case"withoutStreaming":return v_t.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lAu=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),language:Gr.string(),code:Gr.string(),install:Gr.string().optional()}).extend(Xy);var fAu=Gr.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var dAu=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),sdk:fAu,code:Gr.string()}).extend(Xy);var pAu=Gr.union("type",{language:lAu,sdk:dAu}).transform({transform:e=>{switch(e.type){case"language":return UQr.language(e);case"sdk":return UQr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var _Au=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),pathParameters:Gr.list(sAu).optional(),queryParameters:Gr.list(nWa).optional(),headers:Gr.list(iWa).optional(),request:Gr.lazy(()=>N8).optional(),response:cAu.optional(),codeSamples:Gr.list(pAu)}).extend(Xy);var aWa=Gr.union("type",{unknown:Gr.object({value:oAu}),full:_Au}).transform({transform:e=>{switch(e.type){case"unknown":return y_t.unknown(e.value);case"full":return y_t.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var hAu=Gr.objectWithoutOptionalProperties({cursor:Gr.string(),nextCursor:Gr.property("next_cursor",Gr.string()),results:Gr.string()});var yAu=Gr.objectWithoutOptionalProperties({offset:Gr.string(),results:Gr.string(),step:Gr.string().optional(),hasNextPage:Gr.string().optional()});var vAu=Gr.objectWithoutOptionalProperties({results:Gr.string()});var oWa=Gr.union("type",{cursor:hAu,offset:yAu,custom:vAu}).transform({transform:e=>{switch(e.type){case"cursor":return grt.cursor(e);case"offset":return grt.offset(e);case"custom":return grt.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var sWa=Gr.union("type",{disabled:Gr.object({value:Gr.boolean().optional()})}).transform({transform:e=>{switch(e.type){case"disabled":return M8o.disabled(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var bAu=Gr.objectWithoutOptionalProperties({authed:Gr.boolean(),security:JVa,internal:Gr.boolean().optional(),idempotent:Gr.boolean().optional(),method:KVa,audiences:Gr.list(Gr.string()),path:Gr.string(),summary:Gr.string().optional(),operationId:Gr.string().optional(),tags:Gr.list(GDe),pathParameters:Gr.list($Va),queryParameters:Gr.list(YVa),headers:Gr.list(ABi),sdkName:JQr.optional(),generatedRequestName:Gr.string(),requestNameOverride:Gr.string().optional(),request:rAu.optional(),response:nAu.optional(),errors:Gr.record(HQr,aAu),servers:Gr.list(rWa),examples:Gr.list(aWa),pagination:oWa.optional(),retries:sWa.optional()}).extend(Xy).extend(gP).extend(QA).extend(kE);var uWa=Gr.enum_(["GET","POST"]);var cWa=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),payload:Gr.lazy(()=>N8)}).extend(Xy);var gAu=Gr.objectWithoutOptionalProperties({audiences:Gr.list(Gr.string()),sdkName:JQr.optional(),method:uWa,summary:Gr.string().optional(),operationId:Gr.string(),tags:Gr.list(GDe),headers:Gr.list(ABi),generatedPayloadName:Gr.string(),payload:Gr.lazy(()=>eI),examples:Gr.list(cWa)}).extend(Xy).extend(QA).extend(kE);var mAu=Gr.objectWithoutOptionalProperties({queryParameters:Gr.list(YVa),headers:Gr.list(ABi),pathParameters:Gr.list($Va)});var OAu=Gr.enum_(["client","server"]);var AAu=Gr.objectWithoutOptionalProperties({name:Gr.string(),origin:OAu,body:Gr.lazy(()=>eI)});var PAu=Gr.objectWithoutOptionalProperties({name:Gr.string(),url:Gr.string()});var wAu=Gr.objectWithoutOptionalProperties({messageType:Gr.string(),payload:Gr.lazy(()=>N8)}).extend(Xy);var jAu=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),queryParameters:Gr.list(nWa).optional(),headers:Gr.list(iWa).optional(),messages:Gr.list(wAu)}).extend(Xy);var EAu=Gr.objectWithoutOptionalProperties({audiences:Gr.list(Gr.string()),path:Gr.string(),groupName:OBi,summary:Gr.string().optional(),handshake:mAu,messages:Gr.list(AAu),servers:Gr.list(PAu),examples:Gr.list(jAu)}).extend(Xy).extend(QA);var SAu=Gr.objectWithoutOptionalProperties({rootSchemas:Gr.record(HDe,Gr.lazy(()=>eI)),namespacedSchemas:Gr.record(UOu,Gr.record(HDe,Gr.lazy(()=>eI)))});var DAu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),minimum:Gr.number().optional(),maximum:Gr.number().optional(),exclusiveMinimum:Gr.boolean().optional(),exclusiveMaximum:Gr.boolean().optional(),multipleOf:Gr.number().optional()});var CAu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional()});var IAu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),minimum:Gr.number().optional(),maximum:Gr.number().optional(),exclusiveMinimum:Gr.boolean().optional(),exclusiveMaximum:Gr.boolean().optional(),multipleOf:Gr.number().optional()});var MAu=Gr.objectWithoutOptionalProperties({default:Gr.string().optional(),pattern:Gr.string().optional(),format:Gr.string().optional(),minLength:Gr.number().optional(),maxLength:Gr.number().optional()});var BAu=Gr.objectWithoutOptionalProperties({default:Gr.boolean().optional()});var TAu=Gr.union("type",{int:DAu,int64:CAu,uint:Gr.object({}),uint64:Gr.object({}),float:Gr.object({}),double:IAu,string:MAu,datetime:Gr.object({}),date:Gr.object({}),base64:Gr.object({}),boolean:BAu}).transform({transform:e=>{switch(e.type){case"int":return KT.int(e);case"int64":return KT.int64(e);case"uint":return KT.uint();case"uint64":return KT.uint64();case"float":return KT.float();case"double":return KT.double(e);case"string":return KT.string(e);case"datetime":return KT.datetime();case"date":return KT.date();case"base64":return KT.base64();case"boolean":return KT.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var wBi=Gr.objectWithoutOptionalProperties({schema:TAu}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI);var qAu=Gr.objectWithoutOptionalProperties({header:Gr.string(),name:Gr.string().optional(),optional:Gr.boolean().optional(),env:Gr.string().optional(),schema:Gr.lazy(()=>eI).optional()});var RAu=Gr.objectWithoutOptionalProperties({header:Gr.string(),name:Gr.string().optional(),env:Gr.string().optional(),schema:Gr.lazy(()=>eI).optional()});var HEy=Gr.objectWithoutOptionalProperties({apiVersion:Gr.unknown().optional(),title:Gr.string().optional(),description:Gr.string().optional(),basePath:Gr.string().optional(),servers:Gr.list(R8o),websocketServers:Gr.list(R8o),groups:Gr.record(Gr.string(),KOu),tags:$Ou,hasEndpointsMarkedInternal:Gr.boolean(),endpoints:Gr.list(bAu),webhooks:Gr.list(gAu),channels:Gr.record(Gr.string(),EAu),groupedSchemas:SAu,variables:Gr.record(Gr.string(),wBi),nonRequestReferencedSchemas:Gr.set(HDe),securitySchemes:Gr.record(VVa,LOu),globalHeaders:Gr.list(qAu).optional(),idempotencyHeaders:Gr.list(RAu).optional()});var KQr=Gr.objectWithoutOptionalProperties({schema:HDe}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(QA).extend(YI);var NAu=Gr.union("type",{boolean:Gr.object({value:Gr.boolean()}),string:Gr.object({value:Gr.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return K9.boolean(e.value);case"string":return K9.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lWa=Gr.objectWithoutOptionalProperties({value:NAu}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI);var eI=Gr.union("type",{primitive:wBi,object:Gr.lazyObject(()=>xAu),array:Gr.lazyObject(()=>FAu),map:Gr.lazyObject(()=>zAu),optional:Gr.lazyObject(()=>QAu),enum:WVa,reference:KQr,literal:lWa,oneOf:Gr.object({value:Gr.lazy(()=>UAu)}),nullable:Gr.lazyObject(()=>LAu),unknown:QS}).transform({transform:e=>{switch(e.type){case"primitive":return Ij.primitive(e);case"object":return Ij.object(e);case"array":return Ij.array(e);case"map":return Ij.map(e);case"optional":return Ij.optional(e);case"enum":return Ij.enum(e);case"reference":return Ij.reference(e);case"literal":return Ij.literal(e);case"oneOf":return Ij.oneOf(e.value);case"nullable":return Ij.nullable(e);case"unknown":return Ij.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var fWa=Gr.objectWithoutOptionalProperties({propertyKey:Gr.string(),allOfSchemaIds:Gr.list(HDe),conflictingTypeSignatures:Gr.boolean()});var xAu=Gr.objectWithoutOptionalProperties({allOf:Gr.list(KQr),properties:Gr.list(Gr.lazyObject(()=>VAu)),allOfPropertyConflicts:Gr.list(fWa),additionalProperties:Gr.boolean()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(QA).extend(YI).extend(hz);var dWa=Gr.objectWithoutOptionalProperties({differentSchema:Gr.boolean()});var VAu=Gr.objectWithoutOptionalProperties({key:Gr.string(),schema:Gr.lazy(()=>eI),readonly:Gr.boolean().optional(),writeonly:Gr.boolean().optional(),conflict:Gr.record(HDe,dWa),generatedName:Gr.string(),nameOverride:Gr.string().optional(),audiences:Gr.list(Gr.string())}).extend(gP);var FAu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>eI)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var zAu=Gr.objectWithoutOptionalProperties({key:wBi,value:Gr.lazy(()=>eI)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(YI).extend(hz);var QAu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>eI)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var LAu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>eI)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var UAu=Gr.union("type",{discriminated:Gr.lazyObject(()=>WAu),undiscriminated:Gr.lazyObject(()=>HAu)}).transform({transform:e=>{switch(e.type){case"discriminated":return WQr.discriminated(e);case"undiscriminated":return WQr.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var WAu=Gr.objectWithoutOptionalProperties({discriminantProperty:Gr.string(),commonProperties:Gr.list(Gr.lazyObject(()=>GAu)),schemas:Gr.record(Gr.string(),Gr.lazy(()=>eI))}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(QA).extend(YI).extend(hz);var GAu=Gr.objectWithoutOptionalProperties({key:Gr.string(),schema:Gr.lazy(()=>eI)});var HAu=Gr.objectWithoutOptionalProperties({schemas:Gr.list(Gr.lazy(()=>eI))}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(QA).extend(YI).extend(hz);var Syf={};lf(Syf,{ArraySchemaWithExample:()=>hPu,Base64WithExample:()=>lPu,BooleanWithExample:()=>fPu,CommonPropertyWithExample:()=>wPu,DateWithExample:()=>cPu,DatetimeWithExample:()=>uPu,DiscriminatedOneOfSchemaWithExample:()=>APu,DoubleWithExample:()=>oPu,EndpointWithExample:()=>JEy,EnumSchemaWithExample:()=>pPu,FloatWithExample:()=>aPu,HeaderWithExample:()=>jBi,HttpErrorWithExample:()=>ePu,Int64WithExample:()=>rPu,IntWithExample:()=>tPu,JsonRequestWithExample:()=>YAu,JsonResponseWithExample:()=>_Wa,MapSchemaWithExample:()=>yPu,NamedFullExample:()=>g_t,NullableSchemaWithExample:()=>bPu,ObjectPropertyWithExample:()=>OPu,ObjectSchemaWithExample:()=>gPu,OneOfSchemaWithExample:()=>mPu,OptionalSchemaWithExample:()=>vPu,ParseFormUrlEncodedRequest:()=>XAu,ParseMultipartRequest:()=>$Au,ParseOctetStreamRequest:()=>KAu,PathParameterWithExample:()=>JAu,PrimitiveSchemaValueWithExample:()=>dPu,PrimitiveSchemaWithExample:()=>hWa,QueryParameterWithExample:()=>pWa,RequestWithExample:()=>ZAu,ResponseWithExample:()=>kAu,SchemaWithExample:()=>yz,StringSchemaWithExample:()=>sPu,Uint64WithExample:()=>iPu,UintWithExample:()=>nPu,UnDiscriminatedOneOfSchemaWithExample:()=>PPu,UnknownSchemaWithExample:()=>_Pu,WebhookWithExample:()=>KEy,WebsocketHandshakeWithExample:()=>GEy});var g_t=Gr.objectWithoutOptionalProperties({name:Gr.string().optional(),value:Gr.unknown()}).extend(Xy);var pWa=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>yz),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var jBi=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>yz),env:Gr.string().optional(),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var GEy=Gr.objectWithoutOptionalProperties({queryParameters:Gr.list(pWa),headers:Gr.list(jBi)});var JAu=Gr.objectWithoutOptionalProperties({name:Gr.string(),schema:Gr.lazy(()=>yz),variableReference:Gr.string().optional(),parameterNameOverride:Gr.string().optional()}).extend(Xy).extend(gP).extend(QA);var KAu=Gr.objectWithoutOptionalProperties({}).extend(XVa).extend(GQr);var $Au=Gr.objectWithoutOptionalProperties({}).extend(ZVa).extend(GQr);var YAu=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>yz),contentType:Gr.string().optional(),fullExamples:Gr.list(g_t).optional(),additionalProperties:Gr.boolean()}).extend(Xy).extend(QA).extend(GQr);var XAu=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>yz),contentType:Gr.string().optional(),fullExamples:Gr.list(g_t).optional(),additionalProperties:Gr.boolean()}).extend(Xy).extend(QA).extend(GQr);var ZAu=Gr.union("type",{octetStream:KAu,multipart:$Au,json:YAu,formUrlEncoded:XAu}).transform({transform:e=>{switch(e.type){case"octetStream":return WDe.octetStream(e);case"multipart":return WDe.multipart(e);case"json":return WDe.json(e);case"formUrlEncoded":return WDe.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var _Wa=Gr.objectWithoutOptionalProperties({schema:Gr.lazy(()=>yz),responseProperty:Gr.string().optional(),fullExamples:Gr.list(g_t).optional()}).extend(Xy).extend(QA).extend(b_t);var kAu=Gr.union("type",{file:kVa,json:_Wa,text:PBi,bytes:tWa,streamingSse:_Wa,streamingText:PBi,streamingJson:_Wa}).transform({transform:e=>{switch(e.type){case"file":return dL.file(e);case"json":return dL.json(e);case"text":return dL.text(e);case"bytes":return dL.bytes(e);case"streamingSse":return dL.streamingSse(e);case"streamingText":return dL.streamingText(e);case"streamingJson":return dL.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var ePu=Gr.objectWithoutOptionalProperties({statusCode:HQr,schema:Gr.lazy(()=>yz),fullExamples:Gr.list(g_t).optional()}).extend(Xy).extend(QS).extend(QA);var JEy=Gr.objectWithoutOptionalProperties({authed:Gr.boolean(),security:JVa,internal:Gr.boolean().optional(),idempotent:Gr.boolean().optional(),method:KVa,audiences:Gr.list(Gr.string()),path:Gr.string(),summary:Gr.string().optional(),operationId:Gr.string().optional(),tags:Gr.list(GDe),pathParameters:Gr.list(JAu),queryParameters:Gr.list(pWa),headers:Gr.list(jBi),sdkName:JQr.optional(),generatedRequestName:Gr.string(),requestNameOverride:Gr.string().optional(),request:ZAu.optional(),response:kAu.optional(),errors:Gr.record(HQr,ePu),servers:Gr.list(rWa),examples:Gr.list(aWa),pagination:oWa.optional(),retries:sWa.optional()}).extend(Xy).extend(gP).extend(QA).extend(kE);var KEy=Gr.objectWithoutOptionalProperties({audiences:Gr.list(Gr.string()),sdkName:JQr.optional(),method:uWa,summary:Gr.string().optional(),operationId:Gr.string(),tags:Gr.list(GDe),headers:Gr.list(jBi),generatedPayloadName:Gr.string(),payload:Gr.lazy(()=>yz),examples:Gr.list(cWa)}).extend(Xy).extend(QA).extend(kE);var tPu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),minimum:Gr.number().optional(),maximum:Gr.number().optional(),exclusiveMinimum:Gr.boolean().optional(),exclusiveMaximum:Gr.boolean().optional(),multipleOf:Gr.number().optional(),example:Gr.number().optional()});var rPu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),example:Gr.number().optional()});var nPu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),example:Gr.number().optional()});var iPu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),example:Gr.number().optional()});var aPu=Gr.objectWithoutOptionalProperties({example:Gr.number().optional()});var oPu=Gr.objectWithoutOptionalProperties({default:Gr.number().optional(),minimum:Gr.number().optional(),maximum:Gr.number().optional(),exclusiveMinimum:Gr.boolean().optional(),exclusiveMaximum:Gr.boolean().optional(),multipleOf:Gr.number().optional(),example:Gr.number().optional()});var sPu=Gr.objectWithoutOptionalProperties({default:Gr.string().optional(),pattern:Gr.string().optional(),format:Gr.string().optional(),minLength:Gr.number().optional(),maxLength:Gr.number().optional(),example:Gr.string().optional()});var uPu=Gr.objectWithoutOptionalProperties({example:Gr.string().optional()});var cPu=Gr.objectWithoutOptionalProperties({example:Gr.string().optional()});var lPu=Gr.objectWithoutOptionalProperties({example:Gr.string().optional()});var fPu=Gr.objectWithoutOptionalProperties({default:Gr.boolean().optional(),example:Gr.boolean().optional()});var dPu=Gr.union("type",{int:tPu,int64:rPu,uint:nPu,uint64:iPu,float:aPu,double:oPu,string:sPu,datetime:uPu,date:cPu,base64:lPu,boolean:fPu}).transform({transform:e=>{switch(e.type){case"int":return R0.int(e);case"int64":return R0.int64(e);case"uint":return R0.uint(e);case"uint64":return R0.uint64(e);case"float":return R0.float(e);case"double":return R0.double(e);case"string":return R0.string(e);case"datetime":return R0.datetime(e);case"date":return R0.date(e);case"base64":return R0.base64(e);case"boolean":return R0.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var hWa=Gr.objectWithoutOptionalProperties({schema:dPu}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI);var pPu=Gr.objectWithoutOptionalProperties({default:mBi.optional(),values:Gr.list(mBi),example:Gr.string().optional()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(QA).extend(YI).extend(hz);var _Pu=Gr.objectWithoutOptionalProperties({example:Gr.unknown()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI);var yz=Gr.union("type",{primitive:hWa,object:Gr.lazyObject(()=>gPu),array:Gr.lazyObject(()=>hPu),map:Gr.lazyObject(()=>yPu),optional:Gr.lazyObject(()=>vPu),enum:pPu,reference:KQr,literal:lWa,oneOf:Gr.object({value:Gr.lazy(()=>mPu)}),nullable:Gr.lazyObject(()=>bPu),unknown:_Pu}).transform({transform:e=>{switch(e.type){case"primitive":return ny.primitive(e);case"object":return ny.object(e);case"array":return ny.array(e);case"map":return ny.map(e);case"optional":return ny.optional(e);case"enum":return ny.enum(e);case"reference":return ny.reference(e);case"literal":return ny.literal(e);case"oneOf":return ny.oneOf(e.value);case"nullable":return ny.nullable(e);case"unknown":return ny.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var hPu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>yz),example:Gr.list(Gr.unknown()).optional()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var yPu=Gr.objectWithoutOptionalProperties({key:hWa,value:Gr.lazy(()=>yz),example:Gr.unknown().optional()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(YI).extend(hz);var vPu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>yz)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var bPu=Gr.objectWithoutOptionalProperties({value:Gr.lazy(()=>yz)}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(YI).extend(hz);var gPu=Gr.objectWithoutOptionalProperties({allOf:Gr.list(KQr),properties:Gr.list(Gr.lazyObject(()=>OPu)),allOfPropertyConflicts:Gr.list(fWa),fullExamples:Gr.list(g_t).optional(),additionalProperties:Gr.boolean()}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(QA).extend(YI).extend(hz);var OPu=Gr.objectWithoutOptionalProperties({key:Gr.string(),schema:Gr.lazy(()=>yz),readonly:Gr.boolean().optional(),writeonly:Gr.boolean().optional(),audiences:Gr.list(Gr.string()),conflict:Gr.record(HDe,dWa),nameOverride:Gr.string().optional(),generatedName:Gr.string()}).extend(gP);var mPu=Gr.union("type",{discriminated:Gr.lazyObject(()=>APu),undiscriminated:Gr.lazyObject(()=>PPu)}).transform({transform:e=>{switch(e.type){case"discriminated":return mrt.discriminated(e);case"undiscriminated":return mrt.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var APu=Gr.objectWithoutOptionalProperties({discriminantProperty:Gr.string(),commonProperties:Gr.list(Gr.lazyObject(()=>wPu)),schemas:Gr.record(Gr.string(),Gr.lazy(()=>yz))}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(QA).extend(YI).extend(hz);var wPu=Gr.objectWithoutOptionalProperties({key:Gr.string(),schema:Gr.lazy(()=>yz)});var PPu=Gr.objectWithoutOptionalProperties({schemas:Gr.list(Gr.lazy(()=>yz))}).extend(XI).extend(kE).extend(QS).extend(Xy).extend(gP).extend(Bxe).extend(QA).extend(YI).extend(hz);var $Ey=/^(\d+)/,yWa=/^[a-zA-Z][a-zA-Z0-9_]*$/,YEy={"<":"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 EBi(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_${EBi(c)}`}let i=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[i]}_thousand`:`${t[i]}_thousand_${EBi(a)}`}function N8o(e){let t=e.match($Ey);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let a=EBi(i);return n.length>0?`${a}_${n}`:a}}}function vWa(e){let t=N8o(e),r=YEy[e];return t!=null?bU(hA(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":bU(hA(e)))}function Txe(e,t){return e.type==="primitive"&&t.type==="primitive"?XEy(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?trC(e.values,t.values):e.type==="array"&&t.type==="array"?Txe(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"?Txe(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?rrC(e.value,t.value):e.type==="object"&&t.type==="object"?nrC(e,t):e.type==="map"&&t.type==="map"?XEy(e.key.schema,t.key.schema)&&Txe(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function XEy(e,t){return e.type===t.type}function trC(e,t){let r=new Set(...e.map(i=>i.value)),n=new Set(...t.map(i=>i.value));return zoe(r,n)}function rrC(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:Txe(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:Txe(r,i)}):!1}function nrC(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:Txe(a,i.schema)})}function UG(e){switch(e){case Yfe.Deprecated:return"deprecated";case Yfe.Beta:return"pre-release";case Yfe.GenerallyAvailable:return"generally-available";default:return}}function irC(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 ZEy(e){let t=e?irC(e):void 0;if(t==null||t.length===0)return DJi;let r=[];for(let[n,i]of t.entries())if(typeof i=="string")r.push(hA(i));else if(typeof i=="object")switch(i.type){case"namespace":{n<t.length-1?r.push(hA(i.name)):r.push(i.name,DJi);break}default:fc(i.type)}else fc(i);return r.join("/")}function SBi(e){return WP.of(`${ZEy(e)}.yml`)}function Dyf({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?DJi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,ZEy(r))}function kEy({sdkName:e,namespaceOverride:t}){return WP.of(`${Dyf({sdkName:e,namespaceOverride:t})}.yml`)}function eSy({location:e,namespaceOverride:t}){return t!=null?GY(WP.of(t),e):e}function jPu(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:fc(e.type)}}function bWa(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:fc(e)}}function vz(e){return typeof e=="string"?e:e.type}function gWa(e){if(typeof e!="string")return e.docs}function x8o(e){if(typeof e!="string")return e.default}function Cyf(e){if(typeof e!="string")return e.validation}function rSy(e){let t=vz(e);return t.startsWith("nullable<")||t.startsWith("optional<nullable<")?e:typeof e=="string"?tSy(e):{...e,type:tSy(e.type)}}function tSy(e){return e.startsWith("optional<")?e.replace("optional<","optional<nullable<")+">":`nullable<${e}>`}function mWa(e){return vz(e).startsWith("optional<")?e:typeof e=="string"?nSy(e):{...e,type:nSy(e.type)}}function nSy(e){return`optional<${e}>`}var arC=-2147483648,orC=2147483647,srC=-17976931348623157e292,urC=17976931348623157e292;function SD({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 EPu(e);case"array":return Byf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"map":return Tyf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"reference":return Myf({schema:e,fileContainingReference:t,context:n,namespace:i});case"unknown":return Ryf();case"optional":return SPu({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"nullable":return qyf({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"enum":return vrC({schema:e,fileContainingReference:t,context:n,declarationFile:r,declarationDepth:a});case"literal":return e.value,Nyf(e);case"object":return brC({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});case"oneOf":return grC({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});default:fc(e)}}function EPu(e){switch(e.schema.type){case"string":return frC({description:e.description,schema:e.schema});case"int":return drC({description:e.description,schema:e.schema});case"float":return prC({description:e.description,schema:e.schema});case"double":return _rC({description:e.description,schema:e.schema});case"boolean":return crC({description:e.description,schema:e.schema});case"int64":return lrC({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:UG(e.availability)}:{}}}function crC({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 lrC({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 frC({description:e,schema:t}){let r="string",n=hrC(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 drC({description:e,schema:t}){let r="integer",n=iSy(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 prC({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function _rC({description:e,schema:t}){let r="double",n=iSy(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 hrC(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,a=yrC(t);if(!(a==null&&r==null&&n==null&&i==null))return{format:a,pattern:r,minLength:n,maxLength:i}}function yrC(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 iSy(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:a,exclusiveMaximum:o}=e;if(r=Iyf(r,t),n=Iyf(n,t),i=Iyf(i,t),!(r==null&&n==null&&a==null&&o==null&&i==null))return{min:r,max:n,exclusiveMin:a,exclusiveMax:o,multipleOf:i}}function Iyf(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[arC,orC]:[srC,urC];return e<r||e>n?void 0:e}function Myf({schema:e,fileContainingReference:t,context:r,namespace:n}){let i=r.getSchema(e.schema,n);if(i==null)return"unknown";let a=mrC(i)??e.schema,o=bWa(i),c=OrC(i),u=DPu({context:r,fileContainingReference:t,declarationFile:SBi(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:UG(e.availability)}:{}}}function Byf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=SD({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=`list<${vz(o)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:UG(e.availability)}:{},type:c}}function Tyf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=EPu(e.key),c=SD({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),f=e.encoding!=null?jPu(e.encoding):void 0,u=`map<${vz(o)}, ${vz(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=UG(e.availability)),s}function qyf({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){if(!n.respectNullableSchemas)return SPu({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:a});let o=SD({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=vz(o),f=gWa(o),u=x8o(o),s=Cyf(o),l=rSy(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=UG(e.availability)),m}function SPu({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=SD({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}),c=vz(o),f=gWa(o),u=x8o(o),s=Cyf(o),l=mWa(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=UG(e.availability)),m}function Ryf(){return"unknown"}function Nyf(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:fc(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:UG(e.availability)}:{}}}function vrC({schema:e,fileContainingReference:t,declarationFile:r,context:n,declarationDepth:i}){let a=F8o(e,i),o=e.nameOverride??e.generatedName;n.builder.addType(r,{name:o,schema:a.schema});let c=DPu({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=UG(e.availability)),f}function brC({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=xyf({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=DPu({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:UG(e.availability)}:{}}}function grC({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:a}){let o=Fyf({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=DPu({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:UG(e.availability)}:{}}}function DPu({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 mrC(e){return Ij._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 OrC(e){return Ij._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 bse;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(bse||(bse={}));function $di(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:fc(e)}}function oSy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a;switch(e.type){case"primitive":a=wrC(e);break;case"array":a=ArC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"map":a=PrC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"reference":a=jrC({schema:e,context:t,declarationFile:r,namespace:n});break;case"unknown":a=SrC(e.nameOverride,e.generatedName);break;case"optional":a=sSy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"nullable":a=ErC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"enum":a=F8o(e,i);break;case"literal":a=DrC(e,e.nameOverride,e.generatedName);break;case"object":a=xyf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"oneOf":a=Fyf({schema:e.value,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;default:fc(e)}return a}function xyf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a=t.isInState(bse.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(([R,V])=>!V.differentSchema))continue;Object.entries(A.conflict).forEach(([R])=>{zyf({property:A.key,schemaId:R,context:t,namespace:n}).forEach($=>{f.add($)})})}let P=SD({schema:A.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1}),C=A.audiences,M=A.nameOverride,T=UG(A.availability),z=BrC(A);c[A.key]=MrC({typeReference:P,audiences:C,name:M,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=uSy({schema:A.schema,context:t,namespace:n});if(P==null||f.has(A.schema)||f.has(P))continue;let C=SD({schema:Ij.reference(A),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1});s.push(vz(C))}for(let A of f){let P=Qyf(t,A,n);for(let C of P.properties)c[C.key]==null&&(u.has(C.key)&&(c[C.key]="unknown"),c[C.key]=SD({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 M=SD({schema:Ij.reference(C),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1});s.push(vz(M))}}let l={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(c).map(([A,P])=>IrC(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=UG(e.availability)),e.source!=null&&(l.source=$di(e.source)),l.inline=Lyf(e,i);let m=e.nameOverride??e.generatedName;return{name:o&&t.respectReadonlySchemas&&!a?`${m}Read`:m,schema:l}}function zyf({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return zyf({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:a,allOf:o}=Qyf(r,t,n),c=a.some(u=>u.key===e),f=[...o.flatMap(u=>zyf({property:e,context:r,schemaId:u.schema,namespace:n}))];if(c||f.length>0)return[t,...f]}return[]}function Qyf(e,t,r){let n=e.getSchema(t,r);if(n==null)return{properties:[],allOf:[]};if(n.type==="object")return{properties:n.properties,allOf:n.allOf};if(n.type==="reference")return Qyf(e,n.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${n.type}`)}function ArC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Byf({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function PrC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Tyf({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function wrC(e){let t=EPu(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 aSy(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function F8o(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||aSy(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&&!aSy(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=Lyf(e,t);let n=new Set,i={...r,enum:[],source:e.source!=null?$di(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 jrC({schema:e,context:t,declarationFile:r,namespace:n}){return{name:e.nameOverride??e.generatedName,schema:Myf({schema:e,context:t,fileContainingReference:r,namespace:n})}}function ErC({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:qyf({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}:sSy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i})}function sSy({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:SPu({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}}function SrC(e,t){return{name:e??t,schema:Ryf()}}function DrC(e,t,r){return{name:t??r,schema:Nyf(e)}}function Fyf({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){let a=e.encoding!=null?jPu(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let u of e.commonProperties)c[u.key]=SD({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]=SD({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?UG(e.availability):void 0,union:f,encoding:a,source:e.source!=null?$di(e.source):void 0}}}let o=[];for(let c of e.schemas)o.push(SD({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?$di(e.source):void 0,inline:Lyf(e,i)}}}var CrC=/^[0-9]/;function IrC(e){return CrC.test(e)}function uSy({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?uSy({context:t,schema:n.schema,namespace:r}):e}function MrC({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 Lyf(e,t){return e.inline===!0||t>0?!0:void 0}function BrC(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return ZY.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return ZY.ObjectPropertyAccess.WriteOnly}}function cSy(e){let t=e.replace(/^x-|^X-/,"");return hA(t)}var lSy="BasicAuthScheme",CPu="BearerAuthScheme";function fSy(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:lSy,schema:i}),t||(e.builder.setAuth(lSy),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:CPu,schema:i}),t||(e.builder.setAuth(CPu),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??cSy(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:CPu,schema:i}),t||(e.builder.setAuth(CPu),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(WP.of("__package__.yml"),{name:"OauthScope",schema:F8o(n.scopesEnum,0).schema})}}function $Qr({header:e,context:t,fileContainingReference:r,namespace:n}){let i=SD({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),a=vz(i),o=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:hA(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=UG(e.availability)),f}function IPu({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=SD({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return vz(i);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:vz(i)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=UG(e.availability)),a}function BPu({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Uyf({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let a=vz(i.value),o=x8o(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=UG(e.availability)),TrC(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 Uyf({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:SD({schema:Ij.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:WP.of(xN),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"&&(yWa.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:vWa(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&&MPu({array:c,primitive:f}))return{value:SD({schema:Ij.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&&MPu({array:c,primitive:f}))return{value:SD({schema:Ij.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 Uyf({schema:f,context:t,fileContainingReference:r,namespace:n})}else if(t.objectQueryParameters)return{value:SD({schema:e,context:t,fileContainingReference:r,declarationFile:WP.of(xN),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){let i=e.type==="optional"?Ij.optional:Ij.nullable;if(e.value.type==="reference"){let a=t.getSchema(e.value.schema,n);if(a==null)return;if(a.type==="array")return{value:SD({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:WP.of(xN),namespace:n,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:SD({schema:e,context:t,fileContainingReference:r,declarationFile:WP.of(xN),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:SD({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"&&(yWa.test(f.value.value)?a.push(f.value.value):a.push({value:f.value.value,name:vWa(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&&MPu({array:c,primitive:f}))return{value:SD({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&&MPu({array:f,primitive:c}))return{value:SD({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:SD({schema:e,context:t,fileContainingReference:r,declarationFile:WP.of(xN),namespace:n,declarationDepth:0}),allowMultiple:!1};for(let[c,f]of Object.entries(e.value.value.schemas))return Uyf({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:SD({schema:e,context:t,fileContainingReference:r,declarationFile:WP.of(xN),namespace:n,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:SD({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:SD({schema:Ij.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:SD({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}function MPu({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function TrC(e){return e.type!=null}function dSy({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"]=qrC(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=RrC({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=DBi(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function qrC(e){let t={};return e.forEach(r=>{let n=DBi(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function RrC({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let a=DBi(i.value);r.has(i.name)||a!=null&&(n[i.name]=a)}),n}function DBi(e){switch(e.type){case"primitive":return pSy(e.value);case"object":return _Sy(e.properties);case"array":return NrC(e.value);case"map":return xrC(e.value);case"oneOf":return FrC(e.value);case"enum":return e.value;case"literal":return zrC(e.value);case"unknown":return DBi(e.value);case"null":return null;default:fc(e)}}function pSy(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:fc(e)}}function _Sy(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,DBi(r)]))}function NrC(e){return e.map(t=>DBi(t))}function xrC(e){return Object.fromEntries(e.map(t=>[pSy(t.key),DBi(t.value)]))}function FrC(e){return e.type==="discriminated"?_Sy(e.value):DBi(e.value)}function zrC(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:fc(e)}}function Ydi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function TPu(e,t){return t??(e?.groupName!=null?Ydi(e.groupName):void 0)}function hSy({channel:e,context:t,declarationFile:r}){let n={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(n.audiences=e.audiences),e.summary!=null&&(n["display-name"]=e.summary),e.description!=null&&(n.docs=e.description);let i=Ydi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let f of e.handshake.pathParameters)a[f.name]=IPu({pathParameter:f,context:t,fileContainingReference:r,namespace:i});Object.keys(a).length>0&&(n["path-parameters"]=a);let o={};if(e.handshake.queryParameters.length>0)for(let f of e.handshake.queryParameters){let u=BPu({queryParameter:f,context:t,fileContainingReference:r,namespace:i});u!=null&&(o[f.name]=u)}Object.keys(o).length>0&&(n["query-parameters"]=o);let c={};if(e.handshake.headers.length>0)for(let f of e.handshake.headers){let u=$Qr({header:f,context:t,fileContainingReference:r,namespace:i});c[f.name]=u}Object.keys(c).length>0&&(n.headers=c),t.builder.addChannel(r,{channel:n});for(let f of e.messages)t.builder.addChannelMessage(r,{messageId:f.name,message:{origin:f.origin,body:SD({schema:f.body,context:t,fileContainingReference:r,namespace:i,declarationDepth:0})}});for(let f of e.examples){let u=dSy({context:t,websocketExample:f});t.builder.addChannelExample(r,{example:u})}}function ySy(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}var Xdi="Base",QrC="Default";function iki(e){return Object.entries(e).reduce((t,[r,n])=>(Rtt(n)?Object.entries(n.urls).forEach(([i,a])=>{t[i]=a}):t[r]=typeof n=="string"?n:n.url,t),{})}function vSy(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=>ySy(T)),i=e.ir.servers;for(let T of i)if(ySy(T)){let z={urls:{}};for(let[U,R]of Object.entries(T.urls))z.urls[U]=R.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){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(!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(Xdi);return}if(c.length>0&&e.logger.error(`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[QrC]=U}}let C=Object.values(t).map(T=>typeof T=="string"?T:Rtt(T)?Object.values(T.urls)[0]:T.url),M=r.filter(T=>{let z=typeof T=="string"?T:T.url;return!C.includes(z)});if(M.length>0&&e.logger.error(`Skipping top level servers ${M.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),Rtt(U)){let R=Object.keys(U.urls)[0];R&&e.builder.setDefaultUrl(R)}T=!1}return}if(!m&&!A){let T=!0;for(let[z,U]of Object.entries(t))if(T){if(P){let R=typeof U=="string"?U:Rtt(U)?Object.values(U.urls)[0]:U.url;e.builder.addEnvironment({name:z,schema:{urls:{[Xdi]:R??"",...iki(f)}}})}else e.builder.addEnvironment({name:z,schema:U});e.builder.setDefaultEnvironment(z),T=!1}else if(P){let R=typeof U=="string"?U:Rtt(U)?Object.values(U.urls)[0]:U.url;e.builder.addEnvironment({name:z,schema:{urls:{[Xdi]:R??"",...iki(f)}}})}else e.builder.addEnvironment({name:z,schema:U});P&&e.builder.setDefaultUrl(Xdi)}else if(s===1){let T=Object.keys(t)[0],z=Object.values(t)[0],U=typeof z=="string"?z:Rtt(z)?Object.values(z.urls)[0]:z.url;e.builder.addEnvironment({name:T,schema:{urls:{[Xdi]:U??"",...iki(o),...iki(f)}}}),e.builder.setDefaultEnvironment(T),e.builder.setDefaultUrl(Xdi)}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 R=U.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",V=T.get(U.name);V&&V.set(R,U.url)}if(T.size>0){let z=!0;for(let[U,R]of Object.entries(t)){let V=typeof R=="string"?R:Rtt(R)?Object.values(R.urls)[0]:R.url;if(!V)continue;let $=V.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",re={[Xdi]:V};for(let[Y,te]of T.entries()){let ne=te.get($)||te.get("production")||te.values().next().value;ne&&(re[Y]=ne)}P&&Object.assign(re,iki(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(Xdi)}else{let z=!0;for(let[U,R]of Object.entries(t)){if(P||Object.keys(o).length>0){let V=typeof R=="string"?R:Rtt(R)?Object.values(R.urls)[0]:R.url;e.builder.addEnvironment({name:U,schema:{urls:{[Xdi]:V??"",...iki(o),...iki(f)}}})}else e.builder.addEnvironment({name:U,schema:R});z&&(e.builder.setDefaultEnvironment(U),z=!1)}}}}var Vyf=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},LrC=.75,UrC=new Set("authorization");function bSy(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?bWa(n.schema):void 0,o=a!=null?Ydi(a):void 0,c=WP.of("api.yml");i={name:n.name,env:n.env,type:n.schema!=null?vz(SD({schema:n.schema,context:e,fileContainingReference:o?GY(WP.of(hA(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(UrC.has(a.name.toLowerCase()))continue;let o=r[a.name];if(o==null){let c=t[a.name],f=$Qr({header:{...a,schema:c?.schema??a.schema,name:c?.name??a.name},fileContainingReference:WP.of(sk),context:e,namespace:void 0});o=new Vyf(f),r[a.name]=o}o.increment()}let n=e.ir.endpoints.length*LrC;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:mWa(a.schema)}))}}}function gSy(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?bWa(t.schema):void 0,n=r!=null?Ydi(r):void 0,i=$Qr({header:{...t,schema:t.schema??Ij.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:KT.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:WP.of(sk),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:mWa(i)})}}function pPe(e){switch(e.type){case"primitive":return OSy(e.value);case"object":return ASy(e.properties);case"array":return PSy(e.value);case"map":return WrC(e.value);case"oneOf":return HrC(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return GrC(e.value);case"unknown":return pPe(e.value);case"null":return null;default:fc(e)}}function mSy(e){switch(e.type){case"withStreaming":return e.sse?{stream:VrC(e.events)}:{stream:PSy(e.events)};case"withoutStreaming":return{body:pPe(e.value)};default:fc(e)}}function OSy(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:fc(e)}}function ASy(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,pPe(r)]))}function VrC(e){return e.map(t=>({event:"",data:pPe(t)}))}function PSy(e){return e.map(t=>pPe(t))}function WrC(e){return Object.fromEntries(e.map(t=>[OSy(t.key),pPe(t.value)]))}function HrC(e){return e.type==="discriminated"?ASy(e.value):pPe(e.value)}function GrC(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:fc(e)}}function wSy({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"]=JrC(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=KrC(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=Ok({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:Wc}});s!=null&&c.push({name:f,value:ZE.literal(yBi.string(s))})}else c.push({name:f,value:ZE.primitive(pO.string(f))});r.headers=$rC({context:t,namedFullExamples:c})}return e.request!=null&&(r.request=pPe(e.request)),e.response!=null&&(r.response=mSy(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(Tw)),r}function JrC(e){let t={};return e.forEach(r=>{let n=pPe(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function KrC(e){let t={};return e.forEach(r=>{let n=pPe(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function $rC({context:e,namedFullExamples:t}){let r={};return t.forEach(n=>{let i=pPe(n.value);i!=null&&(r[n.name]=i)}),r}function jSy(e){return Zfe._visit(e,{get:()=>ZY.HttpMethodSchema.Get,post:()=>ZY.HttpMethodSchema.Post,put:()=>ZY.HttpMethodSchema.Put,patch:()=>ZY.HttpMethodSchema.Patch,delete:()=>ZY.HttpMethodSchema.Delete,head:()=>ZY.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 ESy(e){return e==="POST"||e==="PUT"||e==="PATCH"}function SSy({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:n}=r.ir,i=[],a=new Set,o=e.path,c=TPu(e.sdkName,e.namespace),f={};for(let M of e.pathParameters)M.parameterNameOverride&&(o=o.replace(M.name,M.parameterNameOverride)),f[M.parameterNameOverride??M.name]=IPu({pathParameter:M,context:r,fileContainingReference:t,namespace:c}),a.add(M.name);let u={};for(let M of e.queryParameters){let T=BPu({queryParameter:M,context:r,fileContainingReference:t,namespace:c});T!=null&&(u[M.name]=T,a.add(M.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:fc(e.pagination)}let l={path:o,method:jSy(e.method),auth:Object.keys(e.security).length>0?e.security:void 0,docs:e.description??void 0,pagination:s,source:e.source!=null?$di(e.source):void 0};!krC({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(M=>!A.has(M.name));for(let M of C){let T=$Qr({header:M,context:r,fileContainingReference:t,namespace:c});m[M.name]=T,a.add(typeof T=="string"?M.name:T.name??M.name)}if(e.request!=null){r.setInState(bse.Request);let M=ZrC({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=M.value,i=[...i,...M.schemaIdsToExclude??[]],r.unsetInState(bse.Request)}else{let M=r.inlinePathParameters&&Object.keys(f).length>0,T=Object.keys(u).length>0,z=Object.keys(m).length>0,U={};(M||T||z)&&(U.name=e.requestNameOverride??e.generatedRequestName),M&&(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:M=>{let T=SD({schema:M.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l.response={docs:M.description??void 0,type:vz(T)},M.statusCode!=null&&(l.response["status-code"]=M.statusCode),M.responseProperty!=null&&(l.response.property=M.responseProperty)},streamingJson:M=>{let T=SD({schema:M.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:M.description??void 0,type:vz(T),format:"json"}},streamingSse:M=>{let T=SD({schema:M.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:M.description??void 0,type:vz(T),format:"sse"}},file:M=>{l.response={docs:M.description??void 0,type:"file","status-code":M.statusCode}},bytes:M=>{l.response={docs:M.description??void 0,type:"bytes","status-code":M.statusCode}},streamingText:M=>{l["response-stream"]={docs:M.description??void 0,type:"text"}},text:M=>{l.response={docs:M.description??void 0,type:"text","status-code":M.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let M=r.getDefaultServerName(),T=e.servers[0];T==null?M!=null&&(l.url=M):l.url=T.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=UG(e.availability)),Object.entries(e.errors).forEach(([M,T])=>{let z=T.generatedName,U=WP.of(xN);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 R={"status-code":parseInt(M)},V=eSy({location:DSy,namespaceOverride:c});if(T.schema!=null){let Y=SD({schema:T.schema,context:r,fileContainingReference:V,declarationFile:V,namespace:c,declarationDepth:0});R.type=vz(Y),R.docs=T.description}r.builder.addError(V,{name:z,schema:r.isErrorUnknownSchema(parseInt(M))?{...R,type:"unknown"}:R}),l.errors==null&&(l.errors=[]);let $=r.builder.addImport({file:t,fileToImport:V});l.errors.push($!=null?`${$}.${z}`:z),R.type!=null&&T.examples?.forEach(Y=>{let te={value:pPe(Y.example),name:Y.name,docs:Y.description};r.builder.addErrorExample(V,{name:z,example:te})})}),e.examples.length>0&&(l.examples=YrC({endpointExamples:e.examples,context:r})),e.retries!=null&&(l.retries=XrC({retries:e.retries})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[Wyf,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:i}}function YrC({endpointExamples:e,context:t}){return e.map(r=>{try{return wSy({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function XrC({retries:e}){if(e!=null)switch(e.type){case"disabled":return{disabled:e.value??void 0};default:fc(e)}}function ZrC({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=SD({schema:n.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),U={schemaIdsToExclude:[],value:{body:z}},R=Object.keys(o??{}).length>0,V=Object.keys(c??{}).length>0,$=Object.keys(u??{}).length>0;return R&&(U.value["path-parameters"]=o),V&&(U.value["query-parameters"]=c),$&&(U.value.headers=u),(R||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:!(ESy(e.method)&&z.readonly)).map(z=>{let U=SD({schema:z.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:1}),R=z.nameOverride??z.key,V=UG(z.availability);if(!s.has(R)&&z.audiences.length<=0)return s.add(R),z.nameOverride!=null?[z.key,{type:vz(U),docs:gWa(U),name:z.nameOverride,availability:V}]:[z.key,V?{...typeof U=="string"?{type:U}:U,availability:V}:U];let $={type:vz(U),docs:gWa(U)};return s.has(R)&&($.name=z.generatedName),z.audiences.length>0&&($.audiences=z.audiences),V!=null&&($.availability=V),s.add(R),[z.key,$]})),C=A.allOf.map(z=>{let U=SD({schema:Ij.reference(z),fileContainingReference:t,context:r,namespace:l,declarationDepth:0});return vz(U)}).filter(z=>z!=="unknown"),M={properties:P};C.length>0&&(M.extends=C),n.additionalProperties&&(M["extra-properties"]=!0);let T={name:i??A.nameOverride??A.generatedName,"path-parameters":o,"query-parameters":c,headers:u,body:M};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??c7.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 M=A.contentType.split(",")[0];C["content-type"]=M}return[A.key,C]}return[A.key,P]}else{let P=SD({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":c7.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else fc(n)}function krC({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:fc(t)}}function enC({location:e,namespaceOverride:t}){return t!=null?{...e,file:GY(WP.of(t),e.file)}:e}function tnC(e){let t=e.namespace,r=e.tags.filter(f=>f!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:WP.of(`${hA(r)}.yml`),endpointId:e.summary!=null?hA(e.summary):hA(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:WP.of(xN),endpointId:hA(e.summary)}:{file:WP.of(xN),endpointId:hA(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:WP.of(xN),endpointId:n};let i=z8o(r),a=z8o(n);if(zoe(i,a))return{file:WP.of("__package__.yml"),endpointId:r};let o=inC({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=hA(r);return{file:WP.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:WP.of(hA(c.join("_"))+".yml"),endpointId:hA(a.slice(c.length).join("_")),tag:r}}function Q8o(e){let t=e.tags[0];if(e.sdkName!=null){let r=Dyf({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:WP.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return enC({namespaceOverride:e.namespace,location:tnC(e)})}function z8o(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=gft(t),t}var rnC=new RegExp("[^a-zA-Z0-9{}]+"),nnC=new RegExp("[{}]","g");function inC({operationId:e,tag:t,path:r,method:n}){let a=`${r.split(rnC).join("_").replaceAll(nnC,"_")}_${n.toLowerCase()}`;if(e.endsWith(a))return{file:WP.of(hA(t)+".yml"),endpointId:hA(e.slice(0,-1*a.length)),tag:t}}function CSy(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let a of r){let{endpointId:o,file:c,tag:f}=Q8o(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,M=A[C];if(M==null)break;if(M.summary!=null||M.description!=null){s=A[C];break}}}let l=f==null?void 0:n.tagsById[f];e.setInState(bse.Endpoint),e.setEndpointMethod(a.method);let m=SSy({context:e,endpoint:a,declarationFile:c});e.unsetEndpointMethod(),e.unsetInState(bse.Endpoint),i=[...i,...m.schemaIdsToExclude],e.builder.addEndpoint(c,{name:o,schema:m.value,source:a.source!=null?$di(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 ISy(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?Ydi(r.groupName):void 0,i=SD({schema:Ij.primitive(r),context:e,fileContainingReference:WP.of(xN),namespace:n,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:vz(i),docs:r.description??void 0}})}}function MSy(e){for(let t of e.ir.webhooks){let r=snC({webhook:t,context:e});if(r==null)continue;let n=TPu(t.sdkName,t.namespace),i={};for(let o of t.headers)i[o.name]=$Qr({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:SD({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:pPe(o.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function anC({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:GY(WP.of(t),e.file)}:e}function onC({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:WP.of(xN),endpointId:n};let i=z8o(r),a=z8o(n);if(zoe(i,a))return{file:WP.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=hA(r);return{file:WP.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:WP.of(hA(o.join("_"))+".yml"),endpointId:hA(a.slice(o.length).join("_")),tag:r}}function snC({webhook:e,context:t}){return e.sdkName!=null?{file:kEy({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:anC({namespaceOverride:e.namespace,location:onC({webhook:e,context:t})})}var unC=WP.of(xN);function TSy(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return BSy({namespace:e.namespace,groupName:e.groupName});case"oneOf":return BSy({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return unC;default:fc(e)}}function BSy({namespace:e,groupName:t}){return e!=null&&t!=null?SBi([{type:"namespace",name:e},...t]):e!=null?SBi([{type:"namespace",name:e}]):SBi(t)}var Wyf="external",DSy=WP.of(xN);function qSy({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,a]of Object.entries(e)){if(t.includes(i))continue;let o=TSy(a),c=oSy({schema:a,context:n,declarationFile:o,namespace:r,declarationDepth:0});if(mCi(c.schema)){let f=vz(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 RSy(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),vSy(e),bSy(e),gSy(e),fSy(e),ISy(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(Wyf);let t=CSy(e),r=t.sdkGroups;e.setInState(bse.Webhook),MSy(e),e.unsetInState(bse.Webhook),e.setInState(bse.Channel);for(let i of Object.values(e.ir.channels)){let a=SBi(i.groupName);hSy({channel:i,context:e,declarationFile:a})}e.unsetInState(bse.Channel);let n=cnC({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});qSy({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:n,namespace:void 0,context:e});for(let[i,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))qSy({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 cnC({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 L8o=class{context;constructor(t){this.context=t}};var qPu=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[o,c]of Object.entries(n.files)){let f=i!=null?WP.of(`${i}${"/"}${o}`):WP.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[WP.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 aki=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new qPu,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 r8r(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"]))NSy(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(NSy(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??hA((Bft(r)+"/"+$Ji(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===WP.of(sk))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=fWs(Bft(Hza.of(`/${t}`)),Hza.of(`/${r}`)),i;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[i]=fWs(Bft(Hza.of(`/${t}`)),Hza.of(`/${r}`)),i}addType(t,{name:r,schema:n}){if(t===WP.of(sk))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=>zoe(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=GY(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:GY(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:GY(r,o.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===xN?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 NSy(e){return e?.header!=null}var RPu=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;wrapReferencesToNullableInOptional;coerceOptionalSchemasToNullable;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;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.builder=new aki(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&&Txe(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}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(bse.Channel,bse.Endpoint,bse.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:fc(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:fc(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 Hyf(e){let t=new RPu(e);return RSy(t)}var NPu=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:n,absoluteFilePath:i}){let a=Hyf({taskContext:t,ir:r,options:I8o({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}}),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:Fg.dump(a.rootApiFile)},namedDefinitionFiles:{...fg(a.definitionFiles,o=>({absoluteFilepath:i??this.args.absoluteFilePath,rawContents:Fg.dump(o),contents:o})),[WP.of(xN)]:{absoluteFilepath:i??this.args.absoluteFilePath,rawContents:Fg.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var U8o=class extends aMr{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;wrapReferencesToNullableInOptional;coerceOptionalSchemasToNullable;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;inlineAllOfSchemas;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.wrapReferencesToNullableInOptional=t.wrapReferencesToNullableInOptional,this.coerceOptionalSchemasToNullable=t.coerceOptionalSchemasToNullable,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.inlineAllOfSchemas=t.inlineAllOfSchemas,this.converter=new NPu(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 brt({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:n,cliVersion:this.cliVersion})}};var Qve={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 OWa={of(e){return e}};var xSy={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},Gyf={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:xSy,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},mb={SOURCE:OWa.of("source"),SDK_NAMESPACE:OWa.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:OWa.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:OWa.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:OWa.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 QW={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,groupMultiApiEnvironments:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0};function m_t({options:e,overrides:t}){return{disableExamples:t?.disableExamples??QW.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??QW.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??QW.useTitlesAsName,audiences:t?.audiences??e?.audiences??QW.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??QW.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??QW.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??QW.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??QW.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??QW.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??QW.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??QW.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??QW.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??QW.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??QW.objectQueryParameters,filter:t?.filter??e?.filter??QW.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??QW.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??QW.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??QW.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??QW.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??QW.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??QW.preserveSingleSchemaOneOf,inlineAllOfSchemas:t?.inlineAllOfSchemas??e?.inlineAllOfSchemas??QW.inlineAllOfSchemas,groupMultiApiEnvironments:t?.groupMultiApiEnvironments??e?.groupMultiApiEnvironments??QW.groupMultiApiEnvironments,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??QW.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??QW.coerceOptionalSchemasToNullable}}var FSy={naming:"v1"};function Vy(e,t){let r=Array.isArray(t)?t:[t];for(let n of r){let i=e[n];if(i!=null)return i}}function V8o(e,t,r,n,i=[]){try{let a=Vy(e,t);if(a!=null)return r.parse(a)}catch{let o=gft(i).join(" -> ");n.error(`${o.length>0?`${o}: `:""}Failed to parse ${t}`)}}function oki(e){let t=Vy(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 zSy({schema:e,logger:t}){return Vy(e,mb.ENCODING)??void 0}function QSy(e){return Vy(e,mb.FERN_ENUM)}function LSy({nameOverride:e,generatedName:t,title:r,schema:n,description:i,availability:a}){let o=Vy(n,mb.SDK_NAMESPACE),c=Vy(n,mb.SDK_GROUP_NAME),f=Vy(n,mb.TYPE_DEFINITION);if(f!=null)return W8o({fernType:f,nameOverride:e,generatedName:t,title:r,description:i,availability:a,namespace:o,groupName:typeof c=="string"?[c]:c})}function W8o({fernType:e,nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c}){return Ok({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>{switch(f.v1){case"BASE_64":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.base64({example:void 0})});case"BOOLEAN":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.boolean({default:void 0,example:void 0})});case"DATE":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.date({example:void 0})});case"DATE_TIME":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.datetime({example:void 0})});case"FLOAT":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.float({example:void 0})});case"DOUBLE":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.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 ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.uint({default:void 0,example:void 0})});case"INTEGER":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.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 ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.uint64({default:void 0,example:void 0})});case"LONG":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return ny.primitive({nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,schema:R0.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:fc(f.v1)}},unknown:()=>ny.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?ny.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?ny.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?ny.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?ny.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?ny.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=>ny.literal({nameOverride:t,generatedName:r,title:n,value:f._visit({string:u=>K9.string(u),boolean:u=>K9.boolean(u),_other:()=>{throw new Error("Unexpected literal type")}}),description:i,availability:a,namespace:o,groupName:c}),named:f=>ny.reference({schema:f,nameOverride:t,generatedName:r,title:n,description:i,availability:a,namespace:o,groupName:c,source:fPe.openapi({file:"<memory>"})})}})}function USy(e){let t=Vy(e,mb.SOURCE);if(t!=null)return t.endsWith(".proto")?fPe.protobuf({file:t}):fPe.openapi({file:t})}function ski(e){if(e!=null&&typeof e=="boolean")return e}function u0(e){return e?.$ref!=null}function VSy({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),Jyf({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:R0.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"||H8o(i,u.options)?ny.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}):WSy(_E(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 WSy(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=WSy(e.value);break;case"oneOf":e.value.inline=!0;break;default:fc(e)}return e}function Jyf({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=ny.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=ny.nullable({nameOverride:e,generatedName:t,title:r,value:A,description:c,availability:f,namespace:u,groupName:s,inline:void 0})),a&&(A=ny.optional({nameOverride:e,generatedName:t,title:r,value:A,description:c,availability:f,namespace:u,groupName:s,inline:void 0})),A}function H8o(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!u0(e)&&Object.keys(e).length===0}function HSy({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?ny.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:l}):_E(i,!1,!1,u,[...n,"Item"],A,s);return lnC({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:l,itemSchema:P,wrapAsOptional:c,wrapAsNullable:f,description:a,availability:o,example:m})}function lnC({nameOverride:e,generatedName:t,title:r,itemSchema:n,wrapAsOptional:i,wrapAsNullable:a,description:o,availability:c,namespace:f,groupName:u,example:s}){let l=ny.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=ny.nullable({nameOverride:e,generatedName:t,title:r,value:l,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),i&&(l=ny.optional({nameOverride:e,generatedName:t,title:r,value:l,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),l}function _Pe(e){switch(Vy(e,mb.AVAILABILITY)){case"deprecated":return Yfe.Deprecated;case"beta":return Yfe.Beta;case"generally-available":return Yfe.GenerallyAvailable;default:break}if(!u0(e)&&e.deprecated)return Yfe.Deprecated}function Kyf({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 M=s.propertyName,T=Object.fromEntries(Object.entries(s.mapping??{}).map(([U,R])=>{let V=Zdi({$ref:R},!1,!1,l,[R],P,C,m);return l.markReferencedByDiscriminatedUnion({$ref:R},M,1),[U,V]})),z=Object.entries(i).filter(([U])=>U!==M).map(([U,R])=>{let V=c!=null&&c.includes(U),[$,re]=l.options.coerceOptionalSchemasToNullable?[!1,!V]:[!V,!1],Y=_E(R,$,re,l,[...n,U],C,m);return{key:U,schema:Y}});return GSy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:f,wrapAsNullable:u,properties:z,description:a,availability:o,discriminant:M,subtypes:T,namespace:m,groupName:A,source:C})}function $yf({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:M}){let T=Object.fromEntries(Object.entries(l).map(([U,R])=>{if(u0(R)){let V=Zdi(R,!1,!1,m,[R.$ref],C,M,A);return m.markReferencedByDiscriminatedUnion(R,s,1),[U,V]}else{let V=G8o(R,!1,!1,m,[...n,U],C,M,A,new Set([s]));return[U,V]}})),z=Object.entries(i).filter(([U])=>U!==s).map(([U,R])=>{let V=c!=null&&c.includes(U),[$,re]=m.options.coerceOptionalSchemasToNullable?[!1,!V]:[!V,!1],Y=_E(R,$,re,m,[...n,U],M,A);return{key:U,schema:Y}});return GSy({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:M})}function GSy({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=ny.oneOf(mrt.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=ny.nullable({nameOverride:e,generatedName:t,title:r,value:A,namespace:s,groupName:l,description:o,availability:c,inline:void 0})),n&&(A=ny.optional({nameOverride:e,generatedName:t,title:r,value:A,namespace:s,groupName:l,description:o,availability:c,inline:void 0})),A}function JSy(e){if(e.proto!=null)return zVa.protobuf({typeName:e.proto.type})}function CBi({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 M=dnC(i??[]),T=new Set(a),z=Array.from(T).map((R,V)=>{let $=n?.[R],re=M[V],Y=yWa.test(R),te=$?.name??re,ne=Y?R:vWa(R);return te!=null&&!yWa.test(te)&&(A?.logger.warn(`Enum name override ${te} is not a valid name. Falling back on ${ne}.`),te=void 0),{nameOverride:te,generatedName:ne,value:R,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(R=>R.value===o):void 0;return fnC({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 fnC({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=ny.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=ny.nullable({nameOverride:r,generatedName:n,title:i,value:A,description:c,availability:f,namespace:u,groupName:s,inline:m})),e&&(A=ny.optional({nameOverride:r,generatedName:n,title:i,value:A,description:c,availability:f,namespace:u,groupName:s,inline:m})),A}function dnC(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 KSy({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:M}){return n==="int64"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.int64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="uint32"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.uint({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="uint64"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.uint64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):gse({nameOverride:e,generatedName:t,title:r,primitive:R0.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:M})}function pnC(e){return typeof e=="string"?K9.string(e):typeof e=="boolean"?K9.boolean(e):K9.string(`${e}`)}function $Sy({nameOverride:e,generatedName:t,title:r,wrapAsOptional:n,wrapAsNullable:i,value:a,description:o,availability:c,namespace:f,groupName:u}){let s=ny.literal({nameOverride:e,generatedName:t,title:r,value:pnC(a),description:o,availability:c,namespace:f,groupName:u});return i&&(s=ny.nullable({nameOverride:e,generatedName:t,title:r,value:s,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),n&&(s=ny.optional({nameOverride:e,generatedName:t,title:r,value:s,description:o,availability:c,namespace:f,groupName:u,inline:void 0})),s}function Yyf({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:M}){return n==null||n==="double"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.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:M}):n==="float"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="int32"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.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:M}):n==="int64"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.int64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="uint32"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.uint({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="uint64"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.uint64({default:i,example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):n==="time-delta"?gse({nameOverride:e,generatedName:t,title:r,primitive:R0.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M}):gse({nameOverride:e,generatedName:t,title:r,primitive:R0.float({example:P}),wrapAsOptional:m,wrapAsNullable:A,description:s,availability:l,namespace:C,groupName:M})}var _nC={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},hnC={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}}},ynC={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}}},vnC={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},bnC={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},gnC={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},mnC={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},OnC={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function xPu(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],n=[_nC,hnC,ynC,vnC,bnC,gnC,mnC,OnC],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:bU(hA(i))).join("");return/^\d/.test(n)?N8o(n)??n:n}function Xyf(e){let t=e.join("_");return hA(t)}function l6(e){switch(e.type){case"object":return Ij.object({allOf:e.allOf,properties:e.properties.map(t=>PnC(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 Ij.array({description:e.description,availability:e.availability,value:l6(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return Ij.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 Ij.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 Ij.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:l6(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return Ij.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:l6(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return Ij.primitive({description:e.description,availability:e.availability,schema:YSy(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Ij.map({description:e.description,availability:e.availability,key:Ij.primitive({description:e.key.description,availability:e.key.availability,schema:YSy(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:l6(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 Ij.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 Ij.oneOf(AnC(e.value));case"unknown":return Ij.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:fc(e)}}function AnC(e){switch(e.type){case"discriminated":return WQr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:l6(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,l6(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return WQr.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>l6(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:fc(e)}}function YSy(e){switch(e.type){case"string":return KT.string(e);case"base64":return KT.base64();case"boolean":return KT.boolean(e);case"date":return KT.date();case"datetime":return KT.datetime();case"double":return KT.double(e);case"float":return KT.float();case"int":return KT.int(e);case"int64":return KT.int64(e);case"uint":return KT.uint();case"uint64":return KT.uint64();default:fc(e)}}function PnC(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:l6(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function FPu(e,t){return Txe(l6(e),l6(t))}function XSy({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:M,source:T}){let z=[...o??[]],U={...i},R=[],V=[];for(let ne of u)if(!s.options.inlineAllOfSchemas&&u0(ne)){let Oe=s.resolveSchemaReference(ne);if(Oe.discriminator!=null&&Oe.discriminator.mapping!=null)continue;if(Oe.oneOf!=null||Oe.anyOf!=null){let ve=Oe.oneOf??Oe.anyOf;if(ve!=null){for(let be of ve){let Me=u0(be)?s.resolveSchemaReference(be):be,Be=_E(Me,!1,!1,s.DUMMY,n,T,m);Be.type==="object"&&R.push(...Be.properties.map(Se=>Se.schema.type!=="optional"&&Se.schema.type!=="nullable"?{...Se,schema:ny.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 ge=IBi(ne);if(ge==null)continue;V.push({schemaId:ge,convertedSchema:Zyf(ne,[ge],T,s.options.preserveSchemaIds),properties:ZSy({schema:ne,context:s,breadcrumbs:n,source:T,namespace:m})}),s.markSchemaAsReferencedByNonRequest(ge)}else if(u0(ne)){let Oe=s.resolveSchemaReference(ne),ge=_E(Oe,!1,!1,s,n,T,m);ge.type==="object"&&R.push(...ge.properties)}else{let Oe=ne.required??[];R=R.map(ve=>(ve.schema.type==="optional"||ve.schema.type==="nullable")&&Oe.includes(ve.key)?{...ve,schema:ve.schema.value}:ve);let ge=_E(ne,!1,!1,s,n,T,m);ge.type==="object"&&R.push(...ge.properties)}let $={};for(let ne of V)for(let[Oe,ge]of Object.entries(ne.properties)){let ve=$[Oe];ve!=null?(ve.schemaIds.push(ne.schemaId),ve.schemas.some(Me=>FPu(Me,ge))||ve.schemas.push(ge)):$[Oe]={schemaIds:[ne.schemaId],schemas:[ge]}}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])=>!(!u0(Oe)&&Oe.type==="null"))),te=Object.entries(Y).map(([ne,Oe])=>{let ge=Vy(Oe,mb.AUDIENCES)??[],ve=_Pe(Oe),be=u0(Oe)?!1:Oe.readOnly,Me=u0(Oe)?!1:Oe.writeOnly,Be=z.includes(ne)&&!be,Se=Vy(Oe,mb.FERN_PROPERTY_NAME),St=[...n,ne],_t=Xyf(St),qe=Be?_E(Oe,!1,!1,s,St,T,m):ny.optional({nameOverride:e,generatedName:_t,title:r,description:void 0,availability:ve,value:_E(Oe,!1,!1,s,St,T,m),namespace:m,groupName:A,inline:void 0}),De={};for(let Qt of V){let Xe=Qt.properties[ne];Xe!=null&&!FPu(qe,Xe)?De[Qt.schemaId]={differentSchema:!0}:Xe!=null&&(De[Qt.schemaId]={differentSchema:!1})}return{key:ne,schema:qe,nameOverride:Se,audiences:ge,conflict:De,generatedName:Xyf([...n,ne]),availability:ve,readonly:be,writeonly:Me}});return te.push(...R.map(ne=>{let Oe=ne.conflict;for(let ge of V){let ve=ge.properties[ne.key];ve!=null&&!FPu(ne.schema,ve)?Oe[ge.schemaId]={differentSchema:!0}:ve!=null&&(Oe[ge.schemaId]={differentSchema:!1})}return{...ne,conflict:Oe}})),wnC({nameOverride:e,generatedName:t,title:r,wrapAsOptional:c,wrapAsNullable:f,properties:te.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:M,source:T,context:s})}function wnC({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 M=ny.object({description:o,properties:a,nameOverride:e,generatedName:t,title:r,allOf:c,allOfPropertyConflicts:f,namespace:u,groupName:s,fullExamples:l,additionalProperties:H8o(m,C.options),availability:A,source:P,inline:void 0});return i&&(M=ny.nullable({nameOverride:e,generatedName:t,title:r,value:M,description:o,availability:A,namespace:u,groupName:s,inline:void 0})),n&&(M=ny.optional({nameOverride:e,generatedName:t,title:r,value:M,description:o,availability:A,namespace:u,groupName:s,inline:void 0})),M}function ZSy({schema:e,context:t,breadcrumbs:r,source:n,namespace:i}){let a={},[o,c]=u0(e)?[t.resolveSchemaReference(e),xPu(e.$ref)]:[e,r];for(let f of o.allOf??[])a={...a,...ZSy({schema:f,context:t,breadcrumbs:c,source:n,namespace:i})};for(let[f,u]of Object.entries(o.properties??{})){let s=_E(u,!1,!1,t,[...c,f],n,i);a[f]=s}return a}function MBi({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=SnC({schemas:u}),M=u.flatMap((z,U)=>{if(!u0(z)&&z.enum!=null&&f.options.coerceEnumsToLiterals&&z.type==="string")return z.enum.map(V=>ny.literal({nameOverride:void 0,generatedName:xne([t,V],f.options.preserveSchemaIds),title:void 0,value:K9.string(String(V)),namespace:s,groupName:void 0,description:void 0,availability:V.availability}));let R=C[U];if(P!=null){let V=P[U];V!=null&&"name"in V&&(R=V.name)}return[_E(z,!1,!1,f,[...n,R??`${U}`],A,s)]}),T=jnC(M);return EnC({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 jnC(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&&Txe(n,o)){i=!0;break}}n!=null&&!i&&t.push(n)}return t}function EnC({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(([M,T])=>{T.type==="literal"&&T.value.type==="string"&&(C.push(T.value.value),T.description!=null&&(P[T.value.value]={description:T.description}))}),CBi({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})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:kSy({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 kyf({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(([M,T],z)=>{let U={$ref:T},R=Zdi(U,!1,!1,c,[T],l,m,f);return c.markSchemaWithDiscriminantValue(U,s.propertyName,M),R.type==="object"&&(R.properties={[s.propertyName]:ny.literal({nameOverride:void 0,generatedName:xne([t,M],c.options.preserveSchemaIds),title:void 0,value:K9.string(M),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...R.properties.filter(V=>V.key!==s.propertyName)}),R}),P=[];for(let M=0;M<A.length;++M){let T=A[M],z=!1;for(let U=M+1;U<A.length;++U){let R=A[U];if(T!=null&&R!=null&&Txe(T,R)){z=!0;break}}T!=null&&!z&&P.push(T)}if(Object.entries(P).every(([M,T])=>T.type==="literal")){let M={},T=[];return Object.entries(P).forEach(([z,U])=>{U.type==="literal"&&U.value.type==="string"&&(T.push(U.value.value),U.description!=null&&(M[U.value.value]={description:U.description}))}),CBi({nameOverride:e,generatedName:t,title:r,wrapAsOptional:a,wrapAsNullable:o,description:n,availability:i,fernEnum:M,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]:kSy({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 SnC({schemas:e}){let t={},r=0;for(let a of e){if(!u0(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=lLs(s,o);f=lLs(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}}u0(a)?n.push(EBi(i)??`${i}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?n.push(""):n.push(EBi(i)??`${i}`),++i}return n}function kSy({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=ny.oneOf(mrt.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=ny.nullable({nameOverride:e,generatedName:t,title:r,value:m,description:a,availability:o,namespace:f,groupName:u,inline:void 0})),n&&(m=ny.optional({nameOverride:e,generatedName:t,title:r,value:m,description:a,availability:o,namespace:f,groupName:u,inline:void 0})),m}function AWa(e){if(e.default!=null&&typeof e.default=="string")return e.default}function zPu({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let n=oki(e);for(let i of n??[])if(typeof i=="number")return i;if(r&&typeof r=="number")return r}function eDy({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let n=oki(e);for(let i of n??[])if(typeof i=="boolean")return i;if(r&&typeof r=="boolean")return r}function YQr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let n=oki(e);for(let i of n??[])if(typeof i=="string")return i;if(r&&typeof r=="string")return r}function tDy({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let n=oki(e);for(let i of n??[])if(Array.isArray(i))return i;if(r&&Array.isArray(r))return r}var uki="#/components/schemas/";function _E(e,t,r,n,i,a,o,c=!1,f=new Set,u){let s=USy(e)??a,l=RnC({schema:e,logger:n.logger});if(u0(e)){let m=IBi(e);return m!=null?(c?n.markSchemaAsReferencedByRequest(m):n.markSchemaAsReferencedByNonRequest(m),Zdi(e,t,r,n,i,l,s,o)):G8o(n.resolveSchemaReference(e),t,r,n,xPu(e.$ref),l,s,o,f,c,u)}return G8o(e,t,r,n,i,l,s,o,f,c,u)}function Zdi(e,t,r,n,i,a,o,c){let f=e.$ref.includes("properties")?G8o(n.resolveSchemaReference(e),t,r,n,i,a,o,c,new Set):ny.reference(Zyf(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=ny.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=ny.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 DnC(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function G8o(e,t,r,n,i,a,o,c,f=new Set,u=!1,s){typeof e=="string"&&(e={type:e});let l=Vy(e,mb.TYPE_NAME)??(n.options.useTitlesAsName?DnC(e.title):void 0),m=Vy(e,mb.SDK_GROUP_NAME)??Vy(e,Qve.TAGS)?.[0],A=(typeof m=="string"?[m]:m)??[];A=n.resolveGroupName(A);let P=xne(i,n.options.preserveSchemaIds),C=e.title,M=e.description,T=_Pe(e),z=[];e.example!=null&&z.push({name:void 0,value:e.example,description:void 0});let U=Vy(e,Qve.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 R=oki(e);R!=null&&Object.keys(R).length>0&&z.push(...R.map($=>({name:void 0,value:$,description:void 0})));let V=LSy({schema:e,description:M,title:C,nameOverride:l,generatedName:P,availability:T});if(V!=null)return V;try{if(Array.isArray(e.type)){let re=e.type.indexOf("null"),Y=re!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&Y)e.type.splice(re,1),e.type=e.type[0],e.nullable=!0;else if(Y&&(e.type.splice(re,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let te=new Set([...e.oneOf,...e.type]);e.oneOf=[...te]}}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(Y=>Y!==null),!UPu(e.enum))return gse({nameOverride:l,generatedName:P,title:C,primitive:R0.string({default:AWa(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:YQr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A,wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T});let re=QSy(e);return e.enum.length===1&&e.enum[0]!=null&&re==null?$Sy({nameOverride:l,generatedName:P,title:C,wrapAsOptional:t,wrapAsNullable:r,value:e.enum[0],description:M,availability:T,namespace:c,groupName:A}):CBi({nameOverride:l,generatedName:P,title:C,fernEnum:re,enumVarNames:Vy(e,[Qve.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,namespace:c,groupName:A,context:n,source:o,inline:void 0})}if(UPu(e.type)&&e.type.length>1){let re=e.type.includes("null"),Y=e.type.filter(te=>te!=="null").map(te=>({type:te,nullable:re}));return MBi({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,subtypes:Y,namespace:c,groupName:A,encoding:a,source:o})}if(e.type==="boolean"){let re=Vy(e,mb.BOOLEAN_LITERAL);return re!=null?rDy({nameOverride:l,generatedName:P,title:C,literal:K9.boolean(re),wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T,namespace:c,groupName:A}):gse({nameOverride:l,generatedName:P,title:C,primitive:R0.boolean({default:CnC(e.default),example:eDy({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T,namespace:c,groupName:A})}if(e.type==="number")return Yyf({nameOverride:l,generatedName:P,title:C,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ski(e.exclusiveMinimum),exclusiveMaximum:ski(e.exclusiveMaximum),multipleOf:e.multipleOf,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:zPu({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="integer")return KSy({nameOverride:l,generatedName:P,title:C,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ski(e.exclusiveMinimum),exclusiveMaximum:ski(e.exclusiveMaximum),multipleOf:e.multipleOf,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:zPu({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="float")return Yyf({nameOverride:l,generatedName:P,title:C,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ski(e.exclusiveMinimum),exclusiveMaximum:ski(e.exclusiveMaximum),multipleOf:e.multipleOf,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,example:zPu({schema:e,logger:n.logger,fallback:s}),namespace:c,groupName:A});if(e.type==="string"){if(e.format==="date-time")return gse({nameOverride:l,generatedName:P,title:C,primitive:R0.datetime({example:YQr({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T,namespace:c,groupName:A});if(e.format==="date"&&n.options.typeDatesAsStrings===!1)return gse({nameOverride:l,generatedName:P,title:C,primitive:R0.date({example:YQr({schema:e,logger:n.logger,fallback:s})}),wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T,namespace:c,groupName:A});if(e.format==="json-string")return ny.unknown({nameOverride:l,generatedName:P,title:C,description:M,availability:T,namespace:c,groupName:A,example:void 0});let re=aDy(e,"const");return re!=null?rDy({nameOverride:l,generatedName:P,title:C,literal:K9.string(re),wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T,namespace:c,groupName:A}):gse({nameOverride:l,generatedName:P,title:C,primitive:R0.string({default:AWa(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:YQr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A,wrapAsOptional:t,wrapAsNullable:r,description:M,availability:T})}if(e.type==="array")return HSy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,item:e.items,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,example:tDy({schema:e,logger:n.logger,fallback:s}),source:o});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&QPu(e))return VSy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,additionalProperties:e.additionalProperties,description:M,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&&Vy(e,mb.IS_DISCRIMINATED)===!1)return MBi({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,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?kyf({nameOverride:l,generatedName:P,title:C,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,discriminator:e.discriminator,encoding:a,source:o}):Kyf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,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 re=Vy(e,mb.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return n.options.discriminatedUnionV2||re?kyf({nameOverride:l,generatedName:P,title:C,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,namespace:c,groupName:A,discriminator:e.discriminator,encoding:a,source:o}):Kyf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,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 MBi({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,context:n,subtypes:e.oneOf.filter(te=>u0(te)||te.type!=="null"),encoding:a,namespace:c,groupName:A,source:o});let Y=_E(e.oneOf[0],t,r,n,i,o,c,u);return PWa(Y,M,c,A)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let Oe=e.oneOf[0],ge=e.oneOf[1];if(!u0(Oe)&&Oe.type==="null")return _E(ge,!1,!0,n,i,o,c);if(!u0(ge)&&ge.type==="null")return _E(Oe,!1,!0,n,i,o,c)}let Y=BnC({schemas:e.oneOf});if(Y!=null)return CBi({nameOverride:l,generatedName:P,title:C,fernEnum:void 0,enumVarNames:void 0,enumValues:Y,_default:e.default,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,namespace:c,groupName:A,context:n,source:o,inline:void 0});let te=nDy({schemas:e.oneOf,context:n});if(te!=null&&!n.options.discriminatedUnionV2&&!re)return $yf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},required:e.required,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,discriminant:te.discriminant,variants:te.schemas,context:n,namespace:c,groupName:A,encoding:a,source:o});let ne=e.oneOf.filter(Oe=>!u0(Oe)&&Oe.type==="null").length>0;return MBi({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r||ne,context:n,subtypes:e.oneOf.filter(Oe=>u0(Oe)||Oe.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 te=_E(e.anyOf[0],t,r,n,i,o,c,u);return PWa(te,M,c,A)}if(e.anyOf.length===2){let[te,ne]=e.anyOf;if(te!=null&&ne!=null){if(!u0(te)&&te.type==="null"){let Oe=_E(ne,!1,!0,n,i,o,c);return PWa(Oe,M,c,A)}else if(!u0(ne)&&ne.type==="null"){let Oe=_E(te,!1,!0,n,i,o,c);return PWa(Oe,M,c,A)}}}let re=nDy({schemas:e.anyOf,context:n});if(re!=null&&!n.options.discriminatedUnionV2)return $yf({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},required:e.required,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,discriminant:re.discriminant,variants:re.schemas,context:n,namespace:c,groupName:A,encoding:a,source:o});let Y=e.anyOf.filter(te=>!u0(te)&&te.type==="null").length>0;return MBi({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r||Y,context:n,subtypes:e.anyOf.filter(te=>u0(te)||te.type!=="null"),encoding:a,namespace:c,groupName:A,source:o})}if(e.allOf!=null||e.properties!=null){let re=[];for(let te of e.allOf??[])(u0(te)||Object.keys(te).length>0)&&re.push(te);if((e.properties==null||QPu(e))&&re.length===1&&re[0]!=null){let te=_E(re[0],t,r,n,i,o,c,u);return PWa(te,M,c,A)}let Y=re.filter(te=>{let ne=LPu(te);return ne||n.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(te)}`),ne});if((e.properties==null||QPu(e))&&Y.length===1&&Y[0]!=null){let te=_E(Y[0],t,r,n,i,o,c,u);return PWa(te,M,c,A)}return XSy({nameOverride:l,generatedName:P,title:C,breadcrumbs:i,properties:e.properties??{},description:M,required:e.required,wrapAsOptional:t,wrapAsNullable:r,allOf:Y,context:n,propertiesToExclude:f,namespace:c,groupName:A,fullExamples:z,additionalProperties:e.additionalProperties,availability:T,encoding:a,source:o})}if(e.type==="object"&&InC(e)&&MnC(e)&&QPu(e))return Jyf({nameOverride:l,generatedName:P,title:C,description:M,availability:T,wrapAsOptional:t,wrapAsNullable:r,keySchema:{nameOverride:void 0,generatedName:`${P}Key`,title:void 0,description:void 0,availability:void 0,schema:R0.string({default:AWa(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:YQr({schema:e,logger:n.logger,fallback:s})}),namespace:c,groupName:A},valueSchema:ny.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;return ny.unknown({nameOverride:l,generatedName:P,title:C,description:M,availability:T,namespace:c,groupName:A,example:$})}catch($){return n.logger.debug(`Error converting schema: ${$.message}
|