fern-api 0.71.0 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1718,7 +1718,7 @@ ${X$p.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&ffc(th
1718
1718
  `+Ptn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Ptn.default.cyan(oGp(t,this.opt.mask)):Ptn.default.italic(Ptn.default.dim("[hidden]")):this.opt.mask?oGp(t,this.opt.mask):Ptn.default.italic(Ptn.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 sGo=ui(u5(),1),CQp=ui(TQp(),1),BQp=ui(YAe(),1);var u7a=class extends s5{_run(t){this.done=t,this.editorResult=new BQp.Subject;let r=r$(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?sGo.default.dim("Received"):sGo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=sGo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,CQp.editAsync)(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var NQp=require("stream");var xQp=ui(require("readline"),1),RQp=ui(zQp(),1),Atn=class{constructor(t){this.rl||=xQp.default.createInterface(KQD(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 KQD(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new RQp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var s7a=class extends Atn{constructor(t={}){super(t),this.log=new NQp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return WNa(this.rl,this.bottomBar.split(`
1719
1719
  `).length),this}updateBottomBar(t){return WNa(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
1720
1720
  `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&x$o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var CM=ui(YAe(),1),UQp=ui(lNa(),1);var cGo=ui(YAe(),1),FQp=ui(lNa(),1),lGo=function(e,t,r){return typeof e[t]!="function"?(0,cGo.of)(e):(0,cGo.from)((0,FQp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var LQp={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,u)=>{n==="__proto__"||n==="constructor"||(a===u.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((u,c)=>u!=null?u[c]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},OWn=class extends Atn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,CM.from)(t):(0,CM.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,CM.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,CM.from)([t]),this.process=i.pipe((0,CM.concatMap)(this.processQuestion.bind(this)),(0,CM.publish)()),this.process.connect(),this.process.pipe((0,CM.reduce)((n,a)=>(LQp.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,CM.defer)(()=>(0,CM.of)(t).pipe((0,CM.concatMap)(this.setDefaultType.bind(this)),(0,CM.concatMap)(this.filterIfRunnable.bind(this)),(0,CM.concatMap)(()=>lGo(t,"message",this.answers)),(0,CM.concatMap)(()=>lGo(t,"default",this.answers)),(0,CM.concatMap)(()=>lGo(t,"choices",this.answers)),(0,CM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,CM.defer)(()=>(0,CM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,CM.defer)(()=>(0,CM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&LQp.get(this.answers,t.name)!==void 0)return CM.EMPTY;if(t.when===!1)return CM.EMPTY;if(typeof t.when!="function")return(0,CM.of)(t);let{answers:r}=this;return(0,CM.defer)(()=>(0,CM.from)((0,UQp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,CM.filter)(i=>i!=null)))}};function VQp(e){let t=function(r,i){let n;try{n=new OWn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",$Na),this.registerPrompt("input",mtn),this.registerPrompt("number",GNa),this.registerPrompt("confirm",QNa),this.registerPrompt("rawlist",JNa),this.registerPrompt("expand",KNa),this.registerPrompt("checkbox",YNa),this.registerPrompt("password",XNa),this.registerPrompt("editor",u7a)},t.restoreDefaultPrompts(),t}var ndc=VQp();function XQD(e,t){ndc.registerPrompt(e,t)}function ZQD(){ndc.restoreDefaultPrompts()}var kQD={prompt:ndc,ui:{BottomBar:s7a,Prompt:OWn},createPromptModule:VQp,registerPrompt:XQD,restoreDefaultPrompts:ZQD,Separator:sue},fGo=kQD;var CWn=require("path"),DKp=require("fs"),EKp=require("readline"),XJp="posthog-node";function UYD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[BGo.POSTHOG_ID_TAG];if(c===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],l=o.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(O=>({...O,platform:"node:javascript"}))}:void 0})),b={$exception_message:o[0]?.value||a.message,$exception_type:o[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:o[0]?.value||a.message,$sentry_exception_type:o[0]?.type,$sentry_tags:a.tags};return t&&r&&(b.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:b}),a}}var BGo=class{constructor(t,r,i,n){this.name=XJp,this.name=XJp,this.setupOnce=function(a,u){let c=u()?.getClient()?.getDsn()?.projectId;a(UYD(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};BGo.POSTHOG_ID_TAG="posthog_distinct_id";var MGo="0123456789abcdef",IGo=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=MGo.charAt(this.bytes[r]>>>4),t+=MGo.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+=MGo.charAt(this.bytes[r]>>>4),t+=MGo.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Jdc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??VYD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return IGo.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,IGo.ofInner(t)}},VYD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),ZJp,Kdc=()=>WYD().toString(),WYD=()=>(ZJp||(ZJp=new Jdc)).generate();function HYD(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(u=>u.name!=="domainUncaughtExceptionClear"&&u._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function $YD(e,t){global.process.on("uncaughtException",HYD(e,t))}function GYD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var AGo,kJp,qGo;function QYD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return qGo&&r.length===kJp||(kJp=r.length,qGo=r.reduce((i,n)=>{AGo||(AGo={});let a=AGo[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let c=u.length-1;c>=0;c--){let s=u[c]?.filename,o=t[n];if(s&&o){i[s]=o,AGo[n]=[s,o];break}}}return i},{})),qGo}function JYD(e){return typeof Event<"u"&&MKp(e,Event)}function KYD(e){return AKp(e,"Object")}function ipc(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return MKp(e,Error)}}function MKp(e,t){try{return e instanceof t}catch{return!1}}function YYD(e){return AKp(e,"ErrorEvent")}function AKp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function XYD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=qKp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await nXD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function qKp(e,t,r){let i=ZYD(e,t,r);return i.cause?[i,...qKp(e,i.cause,r)]:[i]}function ZYD(e,t,r){if(ipc(t))return t;if(e.synthetic=!0,KYD(t)){let n=kYD(t);if(n)return n;let a=eXD(t),u=r?.syntheticException||new Error(a);return u.message=a,u}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function kYD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(ipc(r))return r}}function eXD(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message '${e.message}'`),i}else if("message"in e&&typeof e.message=="string")return e.message;let t=rXD(e);if(YYD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=tXD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function tXD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function rXD(e,t=40){let r=Object.keys(iXD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return eKp(i,t);for(let n=r.length;n>0;n--){let a=r.slice(0,n).join(", ");if(!(a.length>t))return n===r.length?a:eKp(a,t)}return""}function eKp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function iXD(e){return ipc(e)?{message:e.message,name:e.name,stack:e.stack,...tKp(e)}:JYD(e)?{type:e.type,target:rKp(e.target),currentTarget:rKp(e.currentTarget),...tKp(e)}:e}function tKp(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 rKp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function nXD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=aXD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function aXD(e,t){return oXD(e(t.stack||"",1),e)}function oXD(e,t){let r=QYD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var uXD=2e3,AWn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let c=await XYD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||Kdc(),properties:{...c,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&($YD(this.onException.bind(this),this.onFatalError.bind(this)),GYD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(uXD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function sXD(e=process.argv[1]?(0,CWn.dirname)(process.argv[1]):process.cwd(),t=CWn.sep==="\\"){let r=t?iKp(e):e;return i=>{if(!i)return;let n=t?iKp(i):i,{dir:a,base:u,ext:c}=CWn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(u=u.slice(0,c.length*-1));let d=decodeURIComponent(u);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let o=a.slice(r.length+1).replace(/\//g,".");return o?`${o}:${d}`:d}return d}}function iKp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var zGo=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)}}},CGo=new zGo(25),TKp=new zGo(20),npc=7,cXD=1e3,lXD=1e4;async function fXD(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],u=a?.filename;if(!a||typeof u!="string"||typeof a.lineno!="number"||hXD(u)||yXD(a))continue;t[u]||(t[u]=[]),t[u].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(TKp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=bXD(a);if(u.every(d=>vXD(n,d)))continue;let c=gXD(CGo,n,{});i.push(dXD(n,u,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&pXD(e,CGo),CGo.reduce(),e}function dXD(e,t,r){return new Promise(i=>{let n=(0,DKp.createReadStream)(e),a=(0,EKp.createInterface)({input:n});function u(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],l=s[1];function b(){TKp.set(e,1),a.close(),a.removeAllListeners(),u()}n.on("error",b),a.on("error",b),a.on("close",u),a.on("line",g=>{if(c++,!(c<o)&&(r[c]=OXD(g,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let O=t[d];if(O===void 0){a.close(),a.removeAllListeners();return}o=O[0],l=O[1]}})})}function pXD(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;_XD(r.lineno,r,i)}}function _XD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=CKp(e);n<e;n++){let a=r[n];if(a===void 0){nKp(t);return}t.pre_context.push(a)}if(r[e]===void 0){nKp(t);return}t.context_line=r[e];let i=BKp(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function nKp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function hXD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function yXD(e){return e.lineno!==void 0&&e.lineno>lXD||e.colno!==void 0&&e.colno>cXD}function vXD(e,t){let r=CGo.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function bXD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=aKp(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+npc:(n.push(i),i=aKp(a)),t++}return n}function aKp(e){return[CKp(e),BKp(e)]}function CKp(e){return Math.max(1,e-npc)}function BKp(e){return e+npc}function gXD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function OXD(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}var mXD="4.18.0",_ue;(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"})(_ue||(_ue={}));var oKp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(oKp||(oKp={}));var uKp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(uKp||(uKp={}));var sKp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(sKp||(sKp={}));var cKp;(function(e){e.Html="html",e.Text="text"})(cKp||(cKp={}));var lKp;(function(e){e.Number="number",e.Emoji="emoji"})(lKp||(lKp={}));var fKp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(fKp||(fKp={}));var dKp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(dKp||(dKp={}));var pKp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(pKp||(pKp={}));var _Kp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(_Kp||(_Kp={}));var PXD=e=>{if("flags"in e){let t=wXD(e.flags),r=SXD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,IKp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,jXD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function jXD(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 wXD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,apc(r)]).filter(([,t])=>t!==void 0)),SXD=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?IKp(i):void 0]}))},apc=e=>e===void 0?void 0:e.variant??e.enabled,IKp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},DXD=1,EXD=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"]),MXD="utf8";function AXD(e,t){if(!e||typeof e!="string"||qXD(e))throw new Error(t)}function qXD(e){return e.trim().length===0}function TXD(e){return e?.replace(/\/+$/,"")}async function CXD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function hKp(){return new Date().getTime()}function Gdc(){return new Date().toISOString()}function xGo(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function BXD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function IXD(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 zXD(e,t=0,r){let i=IXD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function yKp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var O7a=String.fromCharCode,vKp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",TGo={};function xXD(e,t){if(!TGo[e]){TGo[e]={};for(let r=0;r<e.length;r++)TGo[e][e.charAt(r)]=r}return TGo[e][t]}var EWn={compressToBase64:function(e){if(e==null)return"";let t=EWn._compress(e,6,function(r){return vKp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:EWn._decompress(e.length,32,function(t){return xXD(vKp,e.charAt(t))})},compress:function(e){return EWn._compress(e,16,function(t){return O7a(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,c,d="",s="",o="",l=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++)}for(c=2,u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:EWn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,c=4,d=3,s="",o,l,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=O7a(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=O7a(b);break;case 2:return""}for(i[3]=P,l=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[c++]=O7a(b),P=c-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[c++]=O7a(b),P=c-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),u--,l=s,u==0&&(u=Math.pow(2,d),d++)}}},Ydc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}},qWn=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},m7a=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function bKp(e){if(e instanceof qWn){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Qdc(e){return typeof e=="object"&&(e instanceof qWn||e instanceof m7a)}function gKp(e){return typeof e=="object"&&e instanceof qWn&&e.status===413}var Xdc;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Xdc||(Xdc={}));var Zdc=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new Ydc,this._isInitialized=!1,AXD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=TXD(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:Qdc},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(_ue.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(_ue.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(_ue.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=Kdc();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let c=zXD(this.apiKey,DXD,EXD)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>PXD(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(c===void 0)return{response:void 0,requestId:void 0};let d=apc(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,u){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,u){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,u){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),u&&(c.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes(Xdc.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let u=`Surveys API could not be loaded: ${a.status}`,c=new Error(u);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(u));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(_ue.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(_ue.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(_ue.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(_ue.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:n}),this.setPersistedProperty(_ue.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xGo(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:Gdc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${hKp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(EWn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,c)}catch(d){this._events.emit("error",d)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:Gdc(),uuid:i?.uuid?i.uuid:Kdc()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await bKp(t)})}async flush(){let t=yKp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),yKp([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(_ue.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(b=>b.message),u=()=>{let g=(this.getPersistedProperty(_ue.Queue)||[]).slice(n.length);this.setPersistedProperty(_ue.Queue,g),t=g},c={api_key:this.apiKey,batch:a,sent_at:Gdc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${hKp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,o=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(EWn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},l={retryCheck:b=>gKp(b)?!1:Qdc(b)};try{await this.fetchWithRetry(s,o,l)}catch(b){if(gKp(b)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw b instanceof m7a||u(),this._events.emit("error",b),b}u(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let o=new AbortController;return setTimeout(()=>o.abort(),s),o.signal});let u=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(u,MXD)}catch{c=new TextEncoder().encode(u).length}return await CXD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new m7a(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new qWn(d,c);return d},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(_ue.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Qdc(n))throw n;await bKp(n)}};return Promise.race([new Promise((n,a)=>{xGo(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}},kdc=BXD();if(!kdc){let e=YJp();kdc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var zKp=kdc,RGo=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()}},xKp=new RGo(async()=>{try{return await import("crypto")}catch{return}});async function RXD(){return await xKp.getValue()}var NXD=new RGo(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await xKp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function FXD(){return await NXD.getValue()}async function LXD(e){let t=await RXD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await FXD();if(r){let i=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var UXD=60*1e3,VXD=1152921504606847e3,WXD=["is_not"],MWn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},c5=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},epc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||zKp,this.onError=c.onError,this.customHeaders=u,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,c;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){c=d;break}if(c!==void 0)try{u=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof c5?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async d=>{try{let s=await this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof c5||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),c=!0}})),{response:a,payloads:u,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new c5("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let d=this.groupTypeMapping[String(c)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new c5("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return await this.matchFeatureFlagProperties(t,i[d],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,c,d=[...a].sort((s,o)=>{let l=!!s.variant,b=!!o.variant;return l&&b?0:l?-1:b?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,l=n.multivariate?.variants||[];o&&l.some(b=>b.key===o)?c=o:c=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof c5)u=!0;else throw o}if(c!==void 0)return c;if(u)throw new c5("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let d=c.type,s=!1;if(d==="cohort"?s=NKp(c,n,this.cohorts,this.debugMode):s=RKp(c,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await OKp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await OKp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(UXD,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new MWn(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof MWn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xGo(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,i=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;n=xGo(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function OKp(e,t,r=""){let i=await LXD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/VXD}function RKp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new c5("Operator is_not_set is not supported")}else throw new c5(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!WXD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,o){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,l){if(l==="gt")return s>o;if(l==="gte")return s>=o;if(l==="lt")return s<o;if(l==="lte")return s<=o;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,u);case"is_not":return!c(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return mKp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return mKp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=HXD(String(n));if(s==null&&(s=PKp(n)),s==null)throw new c5(`Invalid date: ${n}`);let o=PKp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new c5(`Unknown operator: ${a}`)}}function NKp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new c5("can't match cohort without a given cohort property value");let a=r[n];return FKp(a,t,r,i)}function FKp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let c of a)try{let d=FKp(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let d;c.type==="cohort"?d=NKp(c,t,r,i):d=RKp(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("can't match cohort without a given cohort property value");return n==="AND"}}function mKp(e){try{return new RegExp(e),!0}catch{return!1}}function PKp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new c5(`${e} is in an invalid date format`)}else throw new c5(`The date provided ${e} must be a string, number, or date object`)}function HXD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var tpc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},$XD=100,jKp=30*1e3,GXD=50*1e3,rpc=class extends Zdc{constructor(t,r={}){if(super(t,r),this._memoryStorage=new tpc,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,$XD):jKp,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 epc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new AWn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||GXD}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):zKp(t,r)}getLibraryVersion(){return mXD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:c,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:c,disableGeoip:d,uuid:s})},l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,b=Promise.resolve().then(async()=>{if(u)return await l(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})});this.addPendingPromise(b)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:c,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:c,disableGeoip:d,uuid:s}),l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await l(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:n},{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=jKp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=l!==void 0,g,O;if(!b&&!u){let P=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(P===void 0)return;O=P.response,l=apc(O),g=P?.requestId}let m=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(m))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(m):this.distinctIdHasSentFlagCalls[r]=[m],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:O?.metadata?.id,$feature_flag_version:O?.metadata?.version,$feature_flag_reason:O?.reason?.description??O?.reason?.code,locally_evaluated:b,[`$feature/${t}`]:l,$feature_flag_request_id:g},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,o);s=l.allPersonProperties,o=l.allGroupProperties;let b;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),d==null&&(d=!0),c==null&&(c=!1),!(b!==void 0)&&!c&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:c}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,c);u=d.allPersonProperties,c=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,c),o={},l={},b=!0;if(s&&(o=s.response,l=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,c,n);o={...o,...g.flags||{}},l={...l,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let c of Object.keys(r))u[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");AWn.captureException(this,t,{syntheticException:n},r,i)}},wKp=/\(error: (.*)\)/,LKp=50,UKp="?";function QXD(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,c,d,s;if(n[1]){c=n[1];let b=c.lastIndexOf(".");if(c[b-1]==="."&&b--,b>0){a=c.slice(0,b),u=c.slice(b+1);let g=a.indexOf(".Module");g>0&&(c=c.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||UKp,c=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!l&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:c,lineno:SKp(n[3]),colno:SKp(n[4]),in_app:JXD(o||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function JXD(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 SKp(e){return parseInt(e||"",10)||void 0}function KXD(e){return[90,QXD(e)]}function YXD(e){let r=[KXD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
1721
- `);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=wKp.test(d)?d.replace(wKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=LKp)break}}return XXD(a)}}function XXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,LKp).map(r=>({...r,filename:r.filename||ZXD(t).filename,function:r.function||UKp}))}function ZXD(e){return e[e.length-1]||{}}AWn.stackParser=YXD(sXD());AWn.frameModifiers=[fXD];var TWn=class extends rpc{getLibraryId(){return"posthog-node"}};var NGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new TWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.71.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var P7a=class{async sendEvent(){}async identify(){}async flush(){}};var BWn=require("fs/promises"),$Kp=require("os"),GKp=require("path");var VKp=ui(require("crypto")),LGo=new Uint8Array(256),FGo=LGo.length;function opc(){return FGo>LGo.length-16&&(VKp.default.randomFillSync(LGo),FGo=0),LGo.slice(FGo,FGo+=16)}var a$=[];for(let e=0;e<256;++e)a$.push((e+256).toString(16).slice(1));function WKp(e,t=0){return a$[e[t+0]]+a$[e[t+1]]+a$[e[t+2]]+a$[e[t+3]]+"-"+a$[e[t+4]]+a$[e[t+5]]+"-"+a$[e[t+6]]+a$[e[t+7]]+"-"+a$[e[t+8]]+a$[e[t+9]]+"-"+a$[e[t+10]]+a$[e[t+11]]+a$[e[t+12]]+a$[e[t+13]]+a$[e[t+14]]+a$[e[t+15]]}var HKp=ui(require("crypto")),upc={randomUUID:HKp.default.randomUUID};function kXD(e,t,r){if(upc.randomUUID&&!t&&!e)return upc.randomUUID();e=e||{};let i=e.random||(e.rng||opc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return WKp(i)}var hue=kXD;var eZD="id",tZD=".fern",j7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new TWn(r),this.userId=t==null?void 0:Gac(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.71.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,$Kp.homedir)()),za.of(tZD),za.of(eZD));await Cf(t)||(await(0,BWn.mkdir)((0,GKp.dirname)(t),{recursive:!0}),await(0,BWn.writeFile)(t,hue())),this.persistedDistinctId=(await(0,BWn.readFile)(t)).toString()}return this.persistedDistinctId}};var spc;async function IWn(){return spc==null&&(spc=await rZD()),spc}async function rZD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new P7a;let r=await rLo();return r!=null?new j7a({token:r,posthogApiKey:e}):await qUn()!=null?new NGo({posthogApiKey:e}):new j7a({token:void 0,posthogApiKey:e})}catch{return new P7a}}function w7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:iZD}=Object.prototype,{getPrototypeOf:lpc}=Object,{iterator:VGo,toStringTag:JKp}=Symbol,WGo=(e=>t=>{let r=iZD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),UGt=e=>(e=e.toLowerCase(),t=>WGo(t)===e),HGo=e=>t=>typeof t===e,{isArray:zWn}=Array,S7a=HGo("undefined");function D7a(e){return e!==null&&!S7a(e)&&e.constructor!==null&&!S7a(e.constructor)&&yue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var KKp=UGt("ArrayBuffer");function nZD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&KKp(e.buffer),t}var aZD=HGo("string"),yue=HGo("function"),YKp=HGo("number"),E7a=e=>e!==null&&typeof e=="object",oZD=e=>e===!0||e===!1,UGo=e=>{if(WGo(e)!=="object")return!1;let t=lpc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(JKp in e)&&!(VGo in e)},uZD=e=>{if(!E7a(e)||D7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},sZD=UGt("Date"),cZD=UGt("File"),lZD=UGt("Blob"),fZD=UGt("FileList"),dZD=e=>E7a(e)&&yue(e.pipe),pZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||yue(e.append)&&((t=WGo(e))==="formdata"||t==="object"&&yue(e.toString)&&e.toString()==="[object FormData]"))},_ZD=UGt("URLSearchParams"),[hZD,yZD,vZD,bZD]=["ReadableStream","Request","Response","Headers"].map(UGt),gZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function M7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(D7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function XKp(e,t){if(D7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ztn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ZKp=e=>!S7a(e)&&e!==ztn;function cpc(){let{caseless:e}=ZKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&XKp(t,n)||n;UGo(t[a])&&UGo(i)?t[a]=cpc(t[a],i):UGo(i)?t[a]=cpc({},i):zWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&M7a(arguments[i],r);return t}var OZD=(e,t,r,{allOwnKeys:i}={})=>(M7a(t,(n,a)=>{r&&yue(n)?e[a]=w7a(n,r):e[a]=n},{allOwnKeys:i}),e),mZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),PZD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},jZD=(e,t,r,i)=>{let n,a,u,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&lpc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},wZD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},SZD=e=>{if(!e)return null;if(zWn(e))return e;let t=e.length;if(!YKp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},DZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&lpc(Uint8Array)),EZD=(e,t)=>{let i=(e&&e[VGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},MZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},AZD=UGt("HTMLFormElement"),qZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),QKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),TZD=UGt("RegExp"),kKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};M7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},CZD=e=>{kKp(e,(t,r)=>{if(yue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(yue(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},BZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zWn(e)?i(e):i(String(e).split(t)),r},IZD=()=>{},zZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function xZD(e){return!!(e&&yue(e.append)&&e[JKp]==="FormData"&&e[VGo])}var RZD=e=>{let t=new Array(10),r=(i,n)=>{if(E7a(i)){if(t.indexOf(i)>=0)return;if(D7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zWn(i)?[]:{};return M7a(i,(u,c)=>{let d=r(u,n+1);!S7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},NZD=UGt("AsyncFunction"),FZD=e=>e&&(E7a(e)||yue(e))&&yue(e.then)&&yue(e.catch),eYp=((e,t)=>e?setImmediate:t?((r,i)=>(ztn.addEventListener("message",({source:n,data:a})=>{n===ztn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ztn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",yue(ztn.postMessage)),LZD=typeof queueMicrotask<"u"?queueMicrotask.bind(ztn):typeof process<"u"&&process.nextTick||eYp,UZD=e=>e!=null&&yue(e[VGo]),hs={isArray:zWn,isArrayBuffer:KKp,isBuffer:D7a,isFormData:pZD,isArrayBufferView:nZD,isString:aZD,isNumber:YKp,isBoolean:oZD,isObject:E7a,isPlainObject:UGo,isEmptyObject:uZD,isReadableStream:hZD,isRequest:yZD,isResponse:vZD,isHeaders:bZD,isUndefined:S7a,isDate:sZD,isFile:cZD,isBlob:lZD,isRegExp:TZD,isFunction:yue,isStream:dZD,isURLSearchParams:_ZD,isTypedArray:DZD,isFileList:fZD,forEach:M7a,merge:cpc,extend:OZD,trim:gZD,stripBOM:mZD,inherits:PZD,toFlatObject:jZD,kindOf:WGo,kindOfTest:UGt,endsWith:wZD,toArray:SZD,forEachEntry:EZD,matchAll:MZD,isHTMLForm:AZD,hasOwnProperty:QKp,hasOwnProp:QKp,reduceDescriptors:kKp,freezeMethods:CZD,toObjectSet:BZD,toCamelCase:qZD,noop:IZD,toFiniteNumber:zZD,findKey:XKp,global:ztn,isContextDefined:ZKp,isSpecCompliantForm:xZD,toJSONObject:RZD,isAsyncFn:NZD,isThenable:FZD,setImmediate:eYp,asap:LZD,isIterable:UZD};function xWn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}hs.inherits(xWn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var tYp=xWn.prototype,rYp={};["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=>{rYp[e]={value:e}});Object.defineProperties(xWn,rYp);Object.defineProperty(tYp,"isAxiosError",{value:!0});xWn.from=(e,t,r,i,n,a)=>{let u=Object.create(tYp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),xWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=xWn;var iYp=ui(cdc(),1),$Go=iYp.default;function fpc(e){return hs.isPlainObject(e)||hs.isArray(e)}function aYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function nYp(e,t,r){return e?e.concat(t).map(function(n,a){return n=aYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function VZD(e){return hs.isArray(e)&&!e.some(fpc)}var WZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function HZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new($Go||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&VZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=aYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?nYp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return fpc(O)?!0:(t.append(nYp(P,m,a),s(O)),!1)}let l=[],b=Object.assign(WZD,{defaultVisitor:o,convertValue:s,isVisitable:fpc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,b))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Sxi=HZD;function oYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function uYp(e,t){this._pairs=[],e&&Sxi(e,this,t)}var sYp=uYp.prototype;sYp.append=function(t,r){this._pairs.push([t,r])};sYp.toString=function(t){let r=t?function(i){return t.call(this,i,oYp)}:oYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var cYp=uYp;function $ZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xtn(e,t,r){if(!t)return e;let i=r&&r.encode||$ZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new cYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var dpc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},ppc=dpc;var RWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pYp=ui(require("crypto"),1);var lYp=ui(require("url"),1),fYp=lYp.default.URLSearchParams;var _pc="abcdefghijklmnopqrstuvwxyz",dYp="0123456789",_Yp={DIGIT:dYp,ALPHA:_pc,ALPHA_DIGIT:_pc+_pc.toUpperCase()+dYp},GZD=(e=16,t=_Yp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);pYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},hYp={isNode:!0,classes:{URLSearchParams:fYp,FormData:$Go,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:_Yp,generateString:GZD,protocols:["http","https","file","data"]};var vpc={};Na(vpc,{hasBrowserEnv:()=>ypc,hasStandardBrowserEnv:()=>QZD,hasStandardBrowserWebWorkerEnv:()=>JZD,navigator:()=>hpc,origin:()=>KZD});var ypc=typeof window<"u"&&typeof document<"u",hpc=typeof navigator=="object"&&navigator||void 0,QZD=ypc&&(!hpc||["ReactNative","NativeScript","NS"].indexOf(hpc.product)<0),JZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",KZD=ypc&&window.location.href||"http://localhost";var iq={...vpc,...hYp};function bpc(e,t){return Sxi(e,new iq.classes.URLSearchParams,{visitor:function(r,i,n,a){return iq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function YZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function XZD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function ZZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=XZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t(YZD(i),n,r,0)}),r}return null}var GGo=ZZD;function kZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var gpc={transitional:RWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(GGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return bpc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Sxi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),kZD(t)):t}],transformResponse:[function(t){let r=this.transitional||gpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:iq.classes.FormData,Blob:iq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{gpc.headers[e]={}});var NWn=gpc;var ekD=hs.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),yYp=e=>{let t={},r,i,n;return e&&e.split(`
1721
+ `);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=wKp.test(d)?d.replace(wKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=LKp)break}}return XXD(a)}}function XXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,LKp).map(r=>({...r,filename:r.filename||ZXD(t).filename,function:r.function||UKp}))}function ZXD(e){return e[e.length-1]||{}}AWn.stackParser=YXD(sXD());AWn.frameModifiers=[fXD];var TWn=class extends rpc{getLibraryId(){return"posthog-node"}};var NGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new TWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.71.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var P7a=class{async sendEvent(){}async identify(){}async flush(){}};var BWn=require("fs/promises"),$Kp=require("os"),GKp=require("path");var VKp=ui(require("crypto")),LGo=new Uint8Array(256),FGo=LGo.length;function opc(){return FGo>LGo.length-16&&(VKp.default.randomFillSync(LGo),FGo=0),LGo.slice(FGo,FGo+=16)}var a$=[];for(let e=0;e<256;++e)a$.push((e+256).toString(16).slice(1));function WKp(e,t=0){return a$[e[t+0]]+a$[e[t+1]]+a$[e[t+2]]+a$[e[t+3]]+"-"+a$[e[t+4]]+a$[e[t+5]]+"-"+a$[e[t+6]]+a$[e[t+7]]+"-"+a$[e[t+8]]+a$[e[t+9]]+"-"+a$[e[t+10]]+a$[e[t+11]]+a$[e[t+12]]+a$[e[t+13]]+a$[e[t+14]]+a$[e[t+15]]}var HKp=ui(require("crypto")),upc={randomUUID:HKp.default.randomUUID};function kXD(e,t,r){if(upc.randomUUID&&!t&&!e)return upc.randomUUID();e=e||{};let i=e.random||(e.rng||opc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return WKp(i)}var hue=kXD;var eZD="id",tZD=".fern",j7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new TWn(r),this.userId=t==null?void 0:Gac(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.71.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,$Kp.homedir)()),za.of(tZD),za.of(eZD));await Cf(t)||(await(0,BWn.mkdir)((0,GKp.dirname)(t),{recursive:!0}),await(0,BWn.writeFile)(t,hue())),this.persistedDistinctId=(await(0,BWn.readFile)(t)).toString()}return this.persistedDistinctId}};var spc;async function IWn(){return spc==null&&(spc=await rZD()),spc}async function rZD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new P7a;let r=await rLo();return r!=null?new j7a({token:r,posthogApiKey:e}):await qUn()!=null?new NGo({posthogApiKey:e}):new j7a({token:void 0,posthogApiKey:e})}catch{return new P7a}}function w7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:iZD}=Object.prototype,{getPrototypeOf:lpc}=Object,{iterator:VGo,toStringTag:JKp}=Symbol,WGo=(e=>t=>{let r=iZD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),UGt=e=>(e=e.toLowerCase(),t=>WGo(t)===e),HGo=e=>t=>typeof t===e,{isArray:zWn}=Array,S7a=HGo("undefined");function D7a(e){return e!==null&&!S7a(e)&&e.constructor!==null&&!S7a(e.constructor)&&yue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var KKp=UGt("ArrayBuffer");function nZD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&KKp(e.buffer),t}var aZD=HGo("string"),yue=HGo("function"),YKp=HGo("number"),E7a=e=>e!==null&&typeof e=="object",oZD=e=>e===!0||e===!1,UGo=e=>{if(WGo(e)!=="object")return!1;let t=lpc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(JKp in e)&&!(VGo in e)},uZD=e=>{if(!E7a(e)||D7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},sZD=UGt("Date"),cZD=UGt("File"),lZD=UGt("Blob"),fZD=UGt("FileList"),dZD=e=>E7a(e)&&yue(e.pipe),pZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||yue(e.append)&&((t=WGo(e))==="formdata"||t==="object"&&yue(e.toString)&&e.toString()==="[object FormData]"))},_ZD=UGt("URLSearchParams"),[hZD,yZD,vZD,bZD]=["ReadableStream","Request","Response","Headers"].map(UGt),gZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function M7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(D7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function XKp(e,t){if(D7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ztn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ZKp=e=>!S7a(e)&&e!==ztn;function cpc(){let{caseless:e}=ZKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&XKp(t,n)||n;UGo(t[a])&&UGo(i)?t[a]=cpc(t[a],i):UGo(i)?t[a]=cpc({},i):zWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&M7a(arguments[i],r);return t}var OZD=(e,t,r,{allOwnKeys:i}={})=>(M7a(t,(n,a)=>{r&&yue(n)?e[a]=w7a(n,r):e[a]=n},{allOwnKeys:i}),e),mZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),PZD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},jZD=(e,t,r,i)=>{let n,a,u,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&lpc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},wZD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},SZD=e=>{if(!e)return null;if(zWn(e))return e;let t=e.length;if(!YKp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},DZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&lpc(Uint8Array)),EZD=(e,t)=>{let i=(e&&e[VGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},MZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},AZD=UGt("HTMLFormElement"),qZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),QKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),TZD=UGt("RegExp"),kKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};M7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},CZD=e=>{kKp(e,(t,r)=>{if(yue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(yue(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},BZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zWn(e)?i(e):i(String(e).split(t)),r},IZD=()=>{},zZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function xZD(e){return!!(e&&yue(e.append)&&e[JKp]==="FormData"&&e[VGo])}var RZD=e=>{let t=new Array(10),r=(i,n)=>{if(E7a(i)){if(t.indexOf(i)>=0)return;if(D7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zWn(i)?[]:{};return M7a(i,(u,c)=>{let d=r(u,n+1);!S7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},NZD=UGt("AsyncFunction"),FZD=e=>e&&(E7a(e)||yue(e))&&yue(e.then)&&yue(e.catch),eYp=((e,t)=>e?setImmediate:t?((r,i)=>(ztn.addEventListener("message",({source:n,data:a})=>{n===ztn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ztn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",yue(ztn.postMessage)),LZD=typeof queueMicrotask<"u"?queueMicrotask.bind(ztn):typeof process<"u"&&process.nextTick||eYp,UZD=e=>e!=null&&yue(e[VGo]),hs={isArray:zWn,isArrayBuffer:KKp,isBuffer:D7a,isFormData:pZD,isArrayBufferView:nZD,isString:aZD,isNumber:YKp,isBoolean:oZD,isObject:E7a,isPlainObject:UGo,isEmptyObject:uZD,isReadableStream:hZD,isRequest:yZD,isResponse:vZD,isHeaders:bZD,isUndefined:S7a,isDate:sZD,isFile:cZD,isBlob:lZD,isRegExp:TZD,isFunction:yue,isStream:dZD,isURLSearchParams:_ZD,isTypedArray:DZD,isFileList:fZD,forEach:M7a,merge:cpc,extend:OZD,trim:gZD,stripBOM:mZD,inherits:PZD,toFlatObject:jZD,kindOf:WGo,kindOfTest:UGt,endsWith:wZD,toArray:SZD,forEachEntry:EZD,matchAll:MZD,isHTMLForm:AZD,hasOwnProperty:QKp,hasOwnProp:QKp,reduceDescriptors:kKp,freezeMethods:CZD,toObjectSet:BZD,toCamelCase:qZD,noop:IZD,toFiniteNumber:zZD,findKey:XKp,global:ztn,isContextDefined:ZKp,isSpecCompliantForm:xZD,toJSONObject:RZD,isAsyncFn:NZD,isThenable:FZD,setImmediate:eYp,asap:LZD,isIterable:UZD};function xWn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}hs.inherits(xWn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var tYp=xWn.prototype,rYp={};["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=>{rYp[e]={value:e}});Object.defineProperties(xWn,rYp);Object.defineProperty(tYp,"isAxiosError",{value:!0});xWn.from=(e,t,r,i,n,a)=>{let u=Object.create(tYp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),xWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=xWn;var iYp=ui(cdc(),1),$Go=iYp.default;function fpc(e){return hs.isPlainObject(e)||hs.isArray(e)}function aYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function nYp(e,t,r){return e?e.concat(t).map(function(n,a){return n=aYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function VZD(e){return hs.isArray(e)&&!e.some(fpc)}var WZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function HZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new($Go||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&VZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=aYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?nYp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return fpc(O)?!0:(t.append(nYp(P,m,a),s(O)),!1)}let l=[],b=Object.assign(WZD,{defaultVisitor:o,convertValue:s,isVisitable:fpc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,b))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Sxi=HZD;function oYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function uYp(e,t){this._pairs=[],e&&Sxi(e,this,t)}var sYp=uYp.prototype;sYp.append=function(t,r){this._pairs.push([t,r])};sYp.toString=function(t){let r=t?function(i){return t.call(this,i,oYp)}:oYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var cYp=uYp;function $ZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xtn(e,t,r){if(!t)return e;let i=r&&r.encode||$ZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new cYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var dpc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},ppc=dpc;var RWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pYp=ui(require("crypto"),1);var lYp=ui(require("url"),1),fYp=lYp.default.URLSearchParams;var _pc="abcdefghijklmnopqrstuvwxyz",dYp="0123456789",_Yp={DIGIT:dYp,ALPHA:_pc,ALPHA_DIGIT:_pc+_pc.toUpperCase()+dYp},GZD=(e=16,t=_Yp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);pYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},hYp={isNode:!0,classes:{URLSearchParams:fYp,FormData:$Go,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:_Yp,generateString:GZD,protocols:["http","https","file","data"]};var vpc={};Na(vpc,{hasBrowserEnv:()=>ypc,hasStandardBrowserEnv:()=>QZD,hasStandardBrowserWebWorkerEnv:()=>JZD,navigator:()=>hpc,origin:()=>KZD});var ypc=typeof window<"u"&&typeof document<"u",hpc=typeof navigator=="object"&&navigator||void 0,QZD=ypc&&(!hpc||["ReactNative","NativeScript","NS"].indexOf(hpc.product)<0),JZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",KZD=ypc&&window.location.href||"http://localhost";var iq={...vpc,...hYp};function bpc(e,t){return Sxi(e,new iq.classes.URLSearchParams,{visitor:function(r,i,n,a){return iq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function YZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function XZD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function ZZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=XZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t(YZD(i),n,r,0)}),r}return null}var GGo=ZZD;function kZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var gpc={transitional:RWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(GGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return bpc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Sxi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),kZD(t)):t}],transformResponse:[function(t){let r=this.transitional||gpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:iq.classes.FormData,Blob:iq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{gpc.headers[e]={}});var NWn=gpc;var ekD=hs.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),yYp=e=>{let t={},r,i,n;return e&&e.split(`
1722
1722
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&ekD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var vYp=Symbol("internals");function A7a(e){return e&&String(e).trim().toLowerCase()}function QGo(e){return e===!1||e==null?e:hs.isArray(e)?e.map(QGo):String(e)}function tkD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var rkD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Opc(e,t,r,i,n){if(hs.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!hs.isString(t)){if(hs.isString(i))return t.indexOf(i)!==-1;if(hs.isRegExp(i))return i.test(t)}}function ikD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function nkD(e,t){let r=hs.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var FWn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let o=A7a(d);if(!o)throw new Error("header name must be a non-empty string");let l=hs.findKey(n,o);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=QGo(c))}let u=(c,d)=>hs.forEach(c,(s,o)=>a(s,o,d));if(hs.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(hs.isString(t)&&(t=t.trim())&&!rkD(t))u(yYp(t),r);else if(hs.isObject(t)&&hs.isIterable(t)){let c={},d,s;for(let o of t){if(!hs.isArray(o))throw TypeError("Object iterator must return a key-value pair");c[s=o[0]]=(d=c[s])?hs.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=A7a(t),t){let i=hs.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return tkD(n);if(hs.isFunction(r))return r.call(this,n,i);if(hs.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=A7a(t),t){let i=hs.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Opc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=A7a(u),u){let c=hs.findKey(i,u);c&&(!r||Opc(i,i[c],c,r))&&(delete i[c],n=!0)}}return hs.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||Opc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return hs.forEach(this,(n,a)=>{let u=hs.findKey(i,a);if(u){r[u]=QGo(n),delete r[a];return}let c=t?ikD(a):String(a).trim();c!==a&&delete r[a],r[c]=QGo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return hs.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&hs.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1723
1723
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[vYp]=this[vYp]={accessors:{}}).accessors,n=this.prototype;function a(u){let c=A7a(u);i[c]||(nkD(n,u),i[c]=!0)}return hs.isArray(t)?t.forEach(a):a(t),this}};FWn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);hs.reduceDescriptors(FWn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});hs.freezeMethods(FWn);var y3=FWn;function q7a(e,t){let r=this||NWn,i=t||r,n=y3.from(i.headers),a=i.data;return hs.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function T7a(e){return!!(e&&e.__CANCEL__)}function bYp(e,t,r){n_.call(this,e??"canceled",n_.ERR_CANCELED,t,r),this.name="CanceledError"}hs.inherits(bYp,n_,{__CANCEL__:!0});var ZAe=bYp;function tar(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new n_("Request failed with status code "+r.status,[n_.ERR_BAD_REQUEST,n_.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function mpc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ppc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Rtn(e,t,r){let i=!mpc(t);return e&&(i||r==!1)?Ppc(e,t):t}var IYp=ui(c7a(),1),zYp=ui(require("http"),1),xYp=ui(require("https"),1),RYp=ui(require("util"),1),NYp=ui(Pdc(),1),AOi=ui(require("zlib"),1);var Ntn="1.11.0";function C7a(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var akD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function jpc(e,t,r){let i=r&&r.Blob||iq.classes.Blob,n=C7a(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=akD.exec(e);if(!a)throw new n_("Invalid URL",n_.ERR_INVALID_URL);let u=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new n_("Blob is not supported",n_.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new n_("Unsupported protocol "+n,n_.ERR_NOT_SUPPORT)}var Ltn=ui(require("stream"),1);var gYp=ui(require("stream"),1);var wpc=Symbol("internals"),Spc=class extends gYp.default.Transform{constructor(t){t=hs.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!hs.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[wpc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[wpc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[wpc],a=n.maxRate,u=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,D=u,A,M=0;if(a){let E=Date.now();(!n.ts||(M=E-n.ts)>=c)&&(n.ts=E,A=s-n.bytes,n.bytes=A<0?-A:0,M=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},c-M);A<D&&(D=A)}D&&m>D&&m-D>o&&(P=g.subarray(D),g=g.subarray(0,D)),l(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},Dpc=Spc;var FYp=require("events");var mYp=ui(require("util"),1),PYp=require("stream");var{asyncIterator:OYp}=Symbol,okD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[OYp]?yield*e[OYp]():yield e},JGo=okD;var ukD=iq.ALPHABET.ALPHA_DIGIT+"-_",B7a=typeof TextEncoder=="function"?new TextEncoder:new mYp.default.TextEncoder,Ftn=`\r
1724
1724
  `,skD=B7a.encode(Ftn),ckD=2,Epc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=hs.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Ftn}`;n?r=B7a.encode(String(r).replace(/\r?\n|\r\n?/g,Ftn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Ftn}`,this.headers=B7a.encode(a+Ftn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+ckD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;hs.isTypedArray(t)?yield t:yield*JGo(t),yield skD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},lkD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+iq.generateString(n,ukD)}=r||{};if(!hs.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=B7a.encode("--"+a+Ftn),c=B7a.encode("--"+a+"--"+Ftn),d=c.byteLength,s=Array.from(e.entries()).map(([l,b])=>{let g=new Epc(l,b);return d+=g.size,g});d+=u.byteLength*s.length,d=hs.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),PYp.Readable.from((async function*(){for(let l of s)yield u,yield*l.encode();yield c})())},jYp=lkD;var wYp=ui(require("stream"),1),Mpc=class extends wYp.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},SYp=Mpc;var fkD=(e,t)=>hs.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,DYp=fkD;function dkD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let l=a,b=0;for(;l!==n;)b+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var EYp=dkD;function pkD(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let o=Date.now(),l=o-r;l>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-l)))},()=>n&&u(n)]}var MYp=pkD;var MOi=(e,t,r=3)=>{let i=0,n=EYp(50,250);return MYp(a=>{let u=a.loaded,c=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=c;i=u;let l={loaded:u,total:c,progress:c?u/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&o?(c-u)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},LWn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},UWn=e=>(...t)=>hs.asap(()=>e(...t));var AYp={flush:AOi.default.constants.Z_SYNC_FLUSH,finishFlush:AOi.default.constants.Z_SYNC_FLUSH},_kD={flush:AOi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:AOi.default.constants.BROTLI_OPERATION_FLUSH},qYp=hs.isFunction(AOi.default.createBrotliDecompress),{http:hkD,https:ykD}=NYp.default,vkD=/https:?/,TYp=iq.protocols.map(e=>e+":"),CYp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function bkD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function LYp(e,t,r){let i=t;if(!i&&i!==!1){let n=IYp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){LYp(a,t,a.href)}}var gkD=typeof process<"u"&&hs.kindOf(process)==="process",OkD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(u,c,d=>i=d).catch(c)}),mkD=({address:e,family:t})=>{if(!hs.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},BYp=(e,t)=>mkD(hs.isObject(e)?e:{address:e,family:t}),UYp=gkD&&function(t){return OkD(async function(i,n,a){let{data:u,lookup:c,family:d}=t,{responseType:s,responseEncoding:o}=t,l=t.method.toUpperCase(),b,g=!1,O;if(c){let me=DYp(c,Le=>hs.isArray(Le)?Le:[Le]);c=(Le,yt,De)=>{me(Le,yt,(Ae,Ct,Pe)=>{if(Ae)return De(Ae);let St=hs.isArray(Ct)?Ct.map(at=>BYp(at)):[BYp(Ct,Pe)];yt.all?De(Ae,St):De(Ae,St[0].address,St[0].family)})}}let m=new FYp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(D),t.signal&&t.signal.removeEventListener("abort",D),m.removeAllListeners()};a((me,Le)=>{b=!0,Le&&(g=!0,P())});function D(me){m.emit("abort",!me||me.type?new ZAe(null,t,O):me)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(D),t.signal&&(t.signal.aborted?D():t.signal.addEventListener("abort",D)));let A=Rtn(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(A,iq.hasBrowserEnv?iq.origin:void 0),E=M.protocol||TYp[0];if(E==="data:"){let me;if(l!=="GET")return tar(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{me=jpc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Le){throw n_.from(Le,n_.ERR_BAD_REQUEST,t)}return s==="text"?(me=me.toString(o),(!o||o==="utf8")&&(me=hs.stripBOM(me))):s==="stream"&&(me=Ltn.default.Readable.from(me)),tar(i,n,{data:me,status:200,statusText:"OK",headers:new y3,config:t})}if(TYp.indexOf(E)===-1)return n(new n_("Unsupported protocol "+E,n_.ERR_BAD_REQUEST,t));let T=y3.from(t.headers).normalize();T.set("User-Agent","axios/"+Ntn,!1);let{onUploadProgress:z,onDownloadProgress:G}=t,I=t.maxRate,R,U;if(hs.isSpecCompliantForm(u)){let me=T.getContentType(/boundary=([-_\w\d]{10,70})/i);u=jYp(u,Le=>{T.set(Le)},{tag:`axios-${Ntn}-boundary`,boundary:me&&me[1]||void 0})}else if(hs.isFormData(u)&&hs.isFunction(u.getHeaders)){if(T.set(u.getHeaders()),!T.hasContentLength())try{let me=await RYp.default.promisify(u.getLength).call(u);Number.isFinite(me)&&me>=0&&T.setContentLength(me)}catch{}}else if(hs.isBlob(u)||hs.isFile(u))u.size&&T.setContentType(u.type||"application/octet-stream"),T.setContentLength(u.size||0),u=Ltn.default.Readable.from(JGo(u));else if(u&&!hs.isStream(u)){if(!Buffer.isBuffer(u))if(hs.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(hs.isString(u))u=Buffer.from(u,"utf-8");else return n(new n_("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",n_.ERR_BAD_REQUEST,t));if(T.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new n_("Request body larger than maxBodyLength limit",n_.ERR_BAD_REQUEST,t))}let Y=hs.toFiniteNumber(T.getContentLength());hs.isArray(I)?(R=I[0],U=I[1]):R=U=I,u&&(z||R)&&(hs.isStream(u)||(u=Ltn.default.Readable.from(u,{objectMode:!1})),u=Ltn.default.pipeline([u,new Dpc({maxRate:hs.toFiniteNumber(R)})],hs.noop),z&&u.on("progress",CYp(u,LWn(Y,MOi(UWn(z),!1,3)))));let J;if(t.auth){let me=t.auth.username||"",Le=t.auth.password||"";J=me+":"+Le}if(!J&&M.username){let me=M.username,Le=M.password;J=me+":"+Le}J&&T.delete("authorization");let X;try{X=xtn(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(me){let Le=new Error(me.message);return Le.config=t,Le.url=t.url,Le.exists=!0,n(Le)}T.set("Accept-Encoding","gzip, compress, deflate"+(qYp?", br":""),!1);let ae={path:X,method:l,headers:T.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:E,family:d,beforeRedirect:bkD,beforeRedirects:{}};!hs.isUndefined(c)&&(ae.lookup=c),t.socketPath?ae.socketPath=t.socketPath:(ae.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,ae.port=M.port,LYp(ae,t.proxy,E+"//"+M.hostname+(M.port?":"+M.port:"")+ae.path));let pe,de=vkD.test(ae.protocol);if(ae.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?xYp.default:zYp.default:(t.maxRedirects&&(ae.maxRedirects=t.maxRedirects),t.beforeRedirect&&(ae.beforeRedirects.config=t.beforeRedirect),pe=de?ykD:hkD),t.maxBodyLength>-1?ae.maxBodyLength=t.maxBodyLength:ae.maxBodyLength=1/0,t.insecureHTTPParser&&(ae.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(ae,function(Le){if(O.destroyed)return;let yt=[Le],De=+Le.headers["content-length"];if(G||U){let at=new Dpc({maxRate:hs.toFiniteNumber(U)});G&&at.on("progress",CYp(at,LWn(De,MOi(UWn(G),!0,3)))),yt.push(at)}let Ae=Le,Ct=Le.req||O;if(t.decompress!==!1&&Le.headers["content-encoding"])switch((l==="HEAD"||Le.statusCode===204)&&delete Le.headers["content-encoding"],(Le.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":yt.push(AOi.default.createUnzip(AYp)),delete Le.headers["content-encoding"];break;case"deflate":yt.push(new SYp),yt.push(AOi.default.createUnzip(AYp)),delete Le.headers["content-encoding"];break;case"br":qYp&&(yt.push(AOi.default.createBrotliDecompress(_kD)),delete Le.headers["content-encoding"])}Ae=yt.length>1?Ltn.default.pipeline(yt,hs.noop):yt[0];let Pe=Ltn.default.finished(Ae,()=>{Pe(),P()}),St={status:Le.statusCode,statusText:Le.statusMessage,headers:new y3(Le.headers),config:t,request:Ct};if(s==="stream")St.data=Ae,tar(i,n,St);else{let at=[],Oe=0;Ae.on("data",function(bt){at.push(bt),Oe+=bt.length,t.maxContentLength>-1&&Oe>t.maxContentLength&&(g=!0,Ae.destroy(),n(new n_("maxContentLength size of "+t.maxContentLength+" exceeded",n_.ERR_BAD_RESPONSE,t,Ct)))}),Ae.on("aborted",function(){if(g)return;let bt=new n_("stream has been aborted",n_.ERR_BAD_RESPONSE,t,Ct);Ae.destroy(bt),n(bt)}),Ae.on("error",function(bt){O.destroyed||n(n_.from(bt,null,t,Ct))}),Ae.on("end",function(){try{let bt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=hs.stripBOM(bt))),St.data=bt}catch(bt){return n(n_.from(bt,null,t,St.request,St))}tar(i,n,St)})}m.once("abort",at=>{Ae.destroyed||(Ae.emit("error",at),Ae.destroy())})}),m.once("abort",me=>{n(me),O.destroy(me)}),O.on("error",function(Le){n(n_.from(Le,null,t,O))}),O.on("socket",function(Le){Le.setKeepAlive(!0,1e3*60)}),t.timeout){let me=parseInt(t.timeout,10);if(Number.isNaN(me)){n(new n_("error trying to parse `config.timeout` to int",n_.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(me,function(){if(b)return;let yt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||RWn;t.timeoutErrorMessage&&(yt=t.timeoutErrorMessage),n(new n_(yt,De.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,t,O)),D()})}if(hs.isStream(u)){let me=!1,Le=!1;u.on("end",()=>{me=!0}),u.once("error",yt=>{Le=!0,O.destroy(yt)}),u.on("close",()=>{!me&&!Le&&D(new ZAe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var VYp=iq.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,iq.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(iq.origin),iq.navigator&&/(msie|trident)/i.test(iq.navigator.userAgent)):()=>!0;var WYp=iq.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];hs.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),hs.isString(i)&&u.push("path="+i),hs.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var HYp=e=>e instanceof y3?{...e}:e;function VGt(e,t){t=t||{};let r={};function i(s,o,l,b){return hs.isPlainObject(s)&&hs.isPlainObject(o)?hs.merge.call({caseless:b},s,o):hs.isPlainObject(o)?hs.merge({},o):hs.isArray(o)?o.slice():o}function n(s,o,l,b){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s,l,b)}else return i(s,o,l,b)}function a(s,o){if(!hs.isUndefined(o))return i(void 0,o)}function u(s,o){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function c(s,o,l){if(l in t)return i(s,o);if(l in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:c,headers:(s,o,l)=>n(HYp(s),HYp(o),l,!0)};return hs.forEach(Object.keys({...e,...t}),function(o){let l=d[o]||n,b=l(e[o],t[o],o);hs.isUndefined(b)&&l!==c||(r[o]=b)}),r}var KGo=e=>{let t=VGt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:c}=t;t.headers=u=y3.from(u),t.url=xtn(Rtn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&u.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let d;if(hs.isFormData(r)){if(iq.hasStandardBrowserEnv||iq.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(iq.hasStandardBrowserEnv&&(i&&hs.isFunction(i)&&(i=i(t)),i||i!==!1&&VYp(t.url))){let s=n&&a&&WYp.read(a);s&&u.set(n,s)}return t};var PkD=typeof XMLHttpRequest<"u",$Yp=PkD&&function(e){return new Promise(function(r,i){let n=KGo(e),a=n.data,u=y3.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,o,l,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function D(){if(!P)return;let M=y3.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),T={data:!c||c==="text"||c==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};tar(function(G){r(G),m()},function(G){i(G),m()},T),P=null}"onloadend"in P?P.onloadend=D:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(D)},P.onabort=function(){P&&(i(new n_("Request aborted",n_.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new n_("Network Error",n_.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let E=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",T=n.transitional||RWn;n.timeoutErrorMessage&&(E=n.timeoutErrorMessage),i(new n_(E,T.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&hs.forEach(u.toJSON(),function(E,T){P.setRequestHeader(T,E)}),hs.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),c&&c!=="json"&&(P.responseType=n.responseType),s&&([b,O]=MOi(s,!0),P.addEventListener("progress",b)),d&&P.upload&&([l,g]=MOi(d),P.upload.addEventListener("progress",l),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new ZAe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=C7a(n.url);if(A&&iq.protocols.indexOf(A)===-1){i(new n_("Unsupported protocol "+A+":",n_.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var jkD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let o=s instanceof Error?s:this.reason;i.abort(o instanceof n_?o:new ZAe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new n_(`timeout ${t} of ms exceeded`,n_.ETIMEDOUT))},t),c=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>hs.asap(c),d}},GYp=jkD;var wkD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},SkD=async function*(e,t){for await(let r of DkD(e))yield*wkD(r,t)},DkD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},Apc=(e,t,r,i)=>{let n=SkD(e,t),a=0,u,c=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){c(),d.close();return}let l=o.byteLength;if(r){let b=a+=l;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var XGo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",JYp=XGo&&typeof ReadableStream=="function",EkD=XGo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),KYp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},MkD=JYp&&KYp(()=>{let e=!1,t=new Request(iq.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),QYp=64*1024,qpc=JYp&&KYp(()=>hs.isReadableStream(new Response("").body)),YGo={stream:qpc&&(e=>e.body)};XGo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!YGo[t]&&(YGo[t]=hs.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new n_(`Response type '${t}' is not supported`,n_.ERR_NOT_SUPPORT,i)})})})(new Response);var AkD=async e=>{if(e==null)return 0;if(hs.isBlob(e))return e.size;if(hs.isSpecCompliantForm(e))return(await new Request(iq.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(hs.isArrayBufferView(e)||hs.isArrayBuffer(e))return e.byteLength;if(hs.isURLSearchParams(e)&&(e=e+""),hs.isString(e))return(await EkD(e)).byteLength},qkD=async(e,t)=>{let r=hs.toFiniteNumber(e.getContentLength());return r??AkD(t)},YYp=XGo&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:c,onUploadProgress:d,responseType:s,headers:o,withCredentials:l="same-origin",fetchOptions:b}=KGo(e);s=s?(s+"").toLowerCase():"text";let g=GYp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&MkD&&r!=="get"&&r!=="head"&&(P=await qkD(o,i))!==0){let T=new Request(t,{method:"POST",body:i,duplex:"half"}),z;if(hs.isFormData(i)&&(z=T.headers.get("content-type"))&&o.setContentType(z),T.body){let[G,I]=LWn(P,MOi(UWn(d)));i=Apc(T.body,QYp,G,I)}}hs.isString(l)||(l=l?"include":"omit");let D="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:D?l:void 0});let A=await fetch(O,b),M=qpc&&(s==="stream"||s==="response");if(qpc&&(c||M&&m)){let T={};["status","statusText","headers"].forEach(R=>{T[R]=A[R]});let z=hs.toFiniteNumber(A.headers.get("content-length")),[G,I]=c&&LWn(z,MOi(UWn(c),!0))||[];A=new Response(Apc(A.body,QYp,G,()=>{I&&I(),m&&m()}),T)}s=s||"text";let E=await YGo[hs.findKey(YGo,s)||"text"](A,e);return!M&&m&&m(),await new Promise((T,z)=>{tar(T,z,{data:E,headers:y3.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(D){throw m&&m(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new n_("Network Error",n_.ERR_NETWORK,e,O),{cause:D.cause||D}):n_.from(D,D&&D.code,e,O)}});var Tpc={http:UYp,xhr:$Yp,fetch:YYp};hs.forEach(Tpc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var XYp=e=>`- ${e}`,TkD=e=>hs.isFunction(e)||e===null||e===!1,ZGo={getAdapter:e=>{e=hs.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!TkD(r)&&(i=Tpc[(u=String(r)).toLowerCase()],i===void 0))throw new n_(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1920,7 +1920,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
1920
1920
  2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
1921
1921
  For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n.executablePath}};V2a=new WeakMap;var Deu=class extends cQn{constructor(t){super(t,"chrome")}launch(t={}){var r;return((r=t.headless)!==null&&r!==void 0?r:!0)===!0&&(!this.puppeteer.configuration.logLevel||this.puppeteer.configuration.logLevel==="warn")&&!process.env.PUPPETEER_DISABLE_HEADLESS_WARNING&&console.warn(["\x1B[1m\x1B[43m\x1B[30m","Puppeteer old Headless deprecation warning:\x1B[0m\x1B[33m"," In the near feature `headless: true` will default to the new Headless mode"," for Chrome instead of the old Headless implementation. For more"," information, please see https://developer.chrome.com/articles/new-headless/.",' Consider opting in early by passing `headless: "new"` to `puppeteer.launch()`',` If you encounter any bugs, please report them to https://github.com/puppeteer/puppeteer/issues/new/choose.\x1B[0m
1922
1922
  `].join(`
1923
- `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:c}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(ul(!a,"Browser should be launched with either pipe or debugging port - not both."),d.push("--remote-debugging-pipe")):d.push(`--remote-debugging-port=${a||0}`));let s=!1,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,Ty_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let l=d[o].split("=",2)[1];ul(typeof l=="string","`--user-data-dir` is malformed");let b=c;return b||(ul(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}}defaultArgs(t={}){let r=["--allow-pre-commit-input","--disable-background-networking","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-breakpad","--disable-client-side-phishing-detection","--disable-component-extensions-with-background-pages","--disable-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${Cy_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(c=>c.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?vko({browser:Lq.CHROME,channel:pSE(t)}):this.resolveExecutablePath()}};function pSE(e){switch(e){case"chrome":return T6.STABLE;case"chrome-dev":return T6.DEV;case"chrome-beta":return T6.BETA;case"chrome-canary":return T6.CANARY}}var yPc=ui(require("fs"),1),Ain=require("fs/promises"),By_=ui(require("os"),1),Eeu=ui(require("path"),1);vB();nq();var Meu=class extends cQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:c=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&ul(c===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${c||0}`));let s,o=!0,l=d.findIndex(g=>["-profile","--profile"].includes(g));if(l!==-1){if(s=d[l+1],!s||!yPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,Ain.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await vOc(Lq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(ul(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}else try{await(0,Ain.unlink)(Eeu.default.join(t,"user.js"));let i=Eeu.default.join(t,"prefs.js.puppeteer");if(yPc.default.existsSync(i)){let n=Eeu.default.join(t,"prefs.js");await(0,Ain.unlink)(n),await(0,Ain.rename)(i,n)}}catch(i){fg(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(By_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(c=>c.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var Iy_=require("path");var H2a=Object.freeze({chromium:"1108766",firefox:"latest"});var vPc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},OQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},lQn,ymi,G2a,$2a,fQn=class extends R4a{constructor(t){let{configuration:r,...i}=t;switch(super(i),lQn.add(this),ymi.set(this,void 0),G2a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=H2a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=H2a.chromium;break}this.connect=this.connect.bind(this),this.launch=this.launch.bind(this),this.executablePath=this.executablePath.bind(this),this.defaultArgs=this.defaultArgs.bind(this),this.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return vPc(this,G2a,r,"f"),OQt(this,lQn,"a",$2a).launch(t)}executablePath(t){return OQt(this,lQn,"a",$2a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=OQt(this,ymi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,Iy_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=OQt(this,G2a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return OQt(this,lQn,"a",$2a).product}defaultArgs(t={}){return OQt(this,lQn,"a",$2a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new oko(t)}};ymi=new WeakMap,G2a=new WeakMap,lQn=new WeakSet,$2a=function(){if(OQt(this,ymi,"f")&&OQt(this,ymi,"f").product===this.lastLaunchedProduct)return OQt(this,ymi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=H2a.chromium,vPc(this,ymi,new Deu(this),"f");break;case"firefox":this.defaultBrowserRevision=H2a.firefox,vPc(this,ymi,new Meu(this),"f");break;default:throw new Error(`Unknown product: ${OQt(this,G2a,"f")}`)}return OQt(this,ymi,"f")};Gbc();eFa();var _SE=new fQn({isPuppeteerCore:!0}),{connect:D55,createBrowserFetcher:E55,defaultArgs:M55,executablePath:A55,launch:q55}=_SE;var s0_=require("os"),c0_=require("path"),l0_=ui(u0_(),1);function LME(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var f0_=()=>{var e,t,r,i,n,a,u,c,d,s,o,l,b,g,O,m,P,D,A,M,E,T,z,G,I,R,U,Y,J,X,ae,pe,de,me,Le,yt,De;let Ae=(0,l0_.cosmiconfigSync)("puppeteer").search(),Ct=Ae?Ae.config:{};if(Ct.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Ct.defaultProduct)!==null&&i!==void 0?i:"chrome",Ct.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Ct.executablePath,Ct.executablePath&&(Ct.skipDownload=!0),Ct.skipDownload=!!((b=(l=(o=(s=(d=(c=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&c!==void 0?c:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&l!==void 0?l:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Ct.skipDownload),Ct.skipDownload||(Ct.browserRevision=(P=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&P!==void 0?P:Ct.browserRevision,Ct.downloadHost=(M=(A=(D=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_host)!==null&&A!==void 0?A:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Ct.downloadHost,Ct.downloadPath=(z=(T=(E=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_path)!==null&&T!==void 0?T:process.env.npm_package_config_puppeteer_download_path)!==null&&z!==void 0?z:Ct.downloadPath),Ct.cacheDirectory=(U=(R=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&R!==void 0?R:Ct.cacheDirectory)!==null&&U!==void 0?U:(0,c0_.join)((0,s0_.homedir)(),".cache","puppeteer"),Ct.temporaryDirectory=(X=(J=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&J!==void 0?J:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Ct.temporaryDirectory,(ae=Ct.experiments)!==null&&ae!==void 0||(Ct.experiments={}),Ct.experiments.macArmChromiumEnabled=!!((me=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&me!==void 0?me:Ct.experiments.macArmChromiumEnabled),Ct.logLevel=(De=(yt=(Le=process.env.PUPPETEER_LOGLEVEL)!==null&&Le!==void 0?Le:process.env.npm_config_LOGLEVEL)!==null&&yt!==void 0?yt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Ct.logLevel,!LME(Ct.defaultProduct))throw new Error(`Unsupported product ${Ct.defaultProduct}`);return Ct};var UME=f0_(),VME=new fQn({isPuppeteerCore:!1,configuration:UME}),{connect:F95,createBrowserFetcher:L95,defaultArgs:U95,executablePath:V95,launch:d0_}=VME;var WME="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",HME={"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 u8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),u8a(e,t-1,r*i,i);throw n}}async function p0_(){try{return await d0_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function $ME(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(HME),await r.setUserAgent(WME),await r.setJavaScriptEnabled(!0),await u8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await u8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function GME(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 Sjc({url:e,browser:t}){try{let r;if(t?r=await $ME(t,e):r=await u8a(()=>GME(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function _0_(e){try{let t=await u8a(()=>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 QME=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function h0_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,gQn.join)(process.cwd(),"fern");try{let r=await JME(e,(0,gQn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function JME(e,t){let r=YME(e),i=(0,gQn.join)(t,r);if(!KME(r))throw new Error(`${r} - file extension not supported`);if((0,Xeu.existsSync)(i))return i;try{(0,Xeu.mkdirSync)((0,gQn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await _0_(e);return Cu_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function KME(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let i=r.toLowerCase();return!(i&&!QME.includes(i))}function YME(e){e.startsWith("http")&&(e=new URL(e).pathname);let t=e.split("#");if(t.length===0)return"image";let r=t[0];if(!r)return"image";let i=r.split("?");if(i.length===0)return"image";let n=i[0];return n&&decodeURIComponent(n.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function XME(e){let t=[];return If(e,"element",r=>{r.tagName==="img"&&Array.isArray(r.properties.className)&&r.properties.className.includes("rm-Logo-img")&&t.push(r)}),t.length>0?t:void 0}async function y0_(e,t){let r=NHn(e),i=XME(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await h0_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var v0_=28;async function b0_(e,t){e=new URL(e);let r=[];if(t){let n=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),n.push(await a.content()),await a.click(".rm-ThemeToggle"),n.push(await a.content())}catch{}await Promise.all(n.map(async a=>await y0_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=za.of(BJ(i[0]));return{light:n,dark:n,height:v0_}}if(i[0]!=null&&i[1]!=null){let n=za.of(BJ(i[0])),a=za.of(BJ(i[1]));return{light:n,dark:a,height:v0_}}}}var Zeu=class extends Qtn{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:Z7a});let i=await this.getHastForUrl(this.url),n=Hs_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let l=await this.scrapeTab({name:o.name,url:o.url});if(!l)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Bu(this.absolutePathToFernDirectory,za.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:l});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:l});for(let m of O)b.addItem({item:m})}let a=await p0_(),u=await b0_(this.url,a);u!=null&&r.setLogo({logo:u});let c=await _i_(i);r.setTitle({title:c});let d=await li_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),l=await fetch(d);if(l.ok){let b=Buffer.from(await l.arrayBuffer()),g=Bu(o,za.of("favicon"));await(0,VRi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:$ae(this.absolutePathToFernDirectory,g)})}}let s=await Gs_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Bu(this.absolutePathToFernDirectory,za.of("assets"));return await(0,VRi.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let i=new URL(r,this.url),n=await this.getHastForUrl(i),a=Us_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=Vs_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}catch(i){this.logger.error(`Failed to scrape tab ${t}: ${i instanceof Error?i.message:String(i)}`),i instanceof Error&&i.stack&&this.logger.error(`Stack trace: ${i.stack}`)}}async getHastForUrl(t){let r=await Sjc({url:t});return NHn(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let i of r){this.logger.debug(`Processing section: ${i.group}`);let n=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i});await(0,VRi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let c=await Sjc({url:u}),d=await Ls_({logger:this.logger,html:c,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,VRi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,l])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Bu(n,za.of(l)),m=zd(O);await(0,VRi.mkdir)(m,{recursive:!0}),await(0,VRi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.toString()}, skipping`)})),await Promise.all(i.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:n,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let i=[];for(let n of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let c of n.pages)if(c.type==="page")u.contents.push({page:c.page,path:$ae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Bu(t,za.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Bu(t,za.of(this.kebabCaseWithoutEmojis(r.group)))}kebabCaseWithoutEmojis(t){return t.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}};var g0_=require("fs/promises");async function Djc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new Jtn;a.setInstance({companyName:n}),await new Zeu({url:e,context:r,builder:a,absolutePathToFernDirectory:Bu($c.of(process.cwd()),za.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,g0_.writeFile)(Bu($c.of(t),za.of(PH),za.of(Lae)),JSON.stringify({version:i,organization:n},void 0,4))}var Ejc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!HZi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=$c.of(CI());await Djc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var O0_="0.0.0";var m0_={[$h.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,QB(e)])),[$h.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[$h.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[$h.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[$h.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[$h.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[$h.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[$h.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[$h.GenerationLanguage.SWIFT]:new Set([])};var kME=["go","ruby"];function Aee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=l=>({unsafeName:l,safeName:eAE({name:l,keywords:tAE({generationLanguage:e,keywords:t})})}),c=R_(n),d=QB(c),s=cZi(n),o=aZi(c);return r&&(!nAE(o)&&(e==null||kME.includes(e))&&(c=o.map((l,b)=>{if(b>0){let g=keu(l);if(g!=null)return g;if(etu(l))return l.toUpperCase()}return l}).join(""),d=QB(o.map((l,b)=>{let g=keu(l);return g??(etu(l)?l.toUpperCase():b===0?QB(l):l)}).join(""))),s=n.split(" ").map(l=>l.split(/(\d+)/).map(cZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??c),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function eAE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":iAE(e)?"_"+e:e}function tAE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return m0_[e]}var rAE=/^[0-9]/;function iAE(e){return rAE.test(e)}function nAE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=keu(i)!=null||etu(i),a=keu(t)!=null||etu(t);return n&&a})}function keu(e){return oAE.get(e.toUpperCase())}function etu(e){return aAE.has(e.toUpperCase())}var aAE=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"]),oAE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Mjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:qoe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return hen(e.auth,{single:i=>{let n=P0_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:qoe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:qoe.Any,schemes:i.map(n=>P0_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function P0_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return VRa(c,{header:d=>YA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>j0_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>ttu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return ttu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>ttu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return ttu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return j0_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function ttu({casingsGenerator:e,docs:t,rawScheme:r}){return YA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function j0_({casingsGenerator:e,docs:t,rawScheme:r}){return YA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function d7(e){let t=sAE(e),{value:r,done:i}=Ajc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...uAE(t)]}}function*uAE(e){let t;do{let{value:r}=Ajc(e,"}"),i=Ajc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*sAE(e){for(let t of e)yield t}function Ajc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function s8a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:sir(i,{singleBaseUrl:()=>lR.singleBaseUrl(cAE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>lR.multipleBaseUrls(lAE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,sir(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function cAE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>sir(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:w0_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function lAE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>sir(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Sd(a.urls,u=>w0_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function w0_(e){return e.endsWith("/")?e.slice(0,-1):e}function c8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Var({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function S0_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return War({containerType:t});switch(t.type){case"list":{let u=NT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:iP.literal({literal:t.literal._visit({boolean:u=>kd.boolean(u),string:u=>kd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=NT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=NT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=NT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||c.type==="failure"?War({containerType:t}):{type:"success",example:iP.map({map:[{key:u.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:c.jsonExample}}}default:Ao(t)}}function War({containerType:e}){switch(e.type){case"list":return{type:"success",example:iP.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:iP.literal({literal:e.literal._visit({boolean:t=>kd.boolean(t),string:t=>kd.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:iP.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:iP.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:iP.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:iP.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ao(e)}}function E0_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return hAE({fieldName:e,default_:fAE(t.v2),validation:dAE(t.v2)});case"BASE_64":return{type:"success",example:kd.base64(Hh.BASE64),jsonExample:Hh.BASE64};case"BOOLEAN":return{type:"success",example:kd.boolean(Hh.BOOLEAN),jsonExample:Hh.BOOLEAN};case"DATE":return{type:"success",example:kd.date(Hh.DATE),jsonExample:Hh.DATE};case"DATE_TIME":return{type:"success",example:kd.datetime({datetime:new Date(Hh.DATE_TIME),raw:Hh.DATE_TIME}),jsonExample:Hh.DATE_TIME};case"DOUBLE":return yAE({fieldName:e,validation:pAE(t.v2)});case"FLOAT":return{type:"success",example:kd.float(Hh.FLOAT),jsonExample:Hh.FLOAT};case"INTEGER":return vAE({fieldName:e,validation:_AE(t.v2)});case"UINT_64":return{type:"success",example:kd.uint64(Hh.INT64),jsonExample:Hh.INT64};case"UINT":return{type:"success",example:kd.uint(Hh.UINT),jsonExample:Hh.UINT};case"BIG_INTEGER":return{type:"success",example:kd.bigInteger(Hh.INT64.toString()),jsonExample:`${Hh.INT64}`};case"LONG":return{type:"success",example:kd.long(Hh.INT64),jsonExample:Hh.INT64};case"UUID":return{type:"success",example:kd.uuid(Hh.UUID),jsonExample:Hh.UUID};default:Ao(t.v1)}}function fAE(e){if(e?.type==="string")return e.default}function dAE(e){if(e?.type==="string")return e.validation}function pAE(e){if(e?.type==="double")return e.validation}function _AE(e){if(e?.type==="integer")return e.validation}function D0_(e){if(e<=Hh.SAMPLE_STRINGS.length){let t=Hh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Hh.SAMPLE_STRINGS[Hh.SAMPLE_STRINGS.length-1]+".".repeat(e-Hh.SAMPLE_STRINGS.length)}function hAE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:kd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=D0_(n);return{type:"success",example:kd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=D0_(a);return{type:"success",example:kd.string({original:u}),jsonExample:u}}}let i=e??Hh.STRING;return{type:"success",example:kd.string({original:i}),jsonExample:i}}function yAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.double(r),jsonExample:r};if(i)return{type:"success",example:kd.double(i),jsonExample:i}}return{type:"success",example:kd.double(Hh.DOUBLE),jsonExample:Hh.DOUBLE}}function vAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.integer(r),jsonExample:r};if(i)return{type:"success",example:kd.integer(i),jsonExample:i}}return{type:"success",example:kd.integer(Hh.INT),jsonExample:Hh.INT}}function OQn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=NT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:c,jsonExample:d}=u;return{type:"success",example:w1.alias({value:c}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:w1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let b=t[l.typeId];if(b==null)continue;let g=OQn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),c.push(...g.example.properties))}let d=bAE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:w1.object({properties:[...c,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let c of r.shape.members){let d=NT({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:w1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=NT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(c[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...c}}),samePropertiesAsObject:o=>{let l=t[o.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=OQn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.samePropertiesAsObject({typeId:l.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...c}}},singleProperty:o=>{let l=NT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:b,jsonExample:g}=l;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function bAE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=NT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Var({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:l,propertyAccess:s.propertyAccess}),c[s.name.wireValue]=b}return{type:"success",example:w1.object({properties:d}),jsonExample:c}}function NT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=OQn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:by.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=S0_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=War({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:by.container(s)},jsonExample:o}}let{example:c,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:by.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:c}=E0_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:by.primitive(c)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:by.unknown(u)},jsonExample:u}}}}function xin(e,t){let r=[];for(let i of e){let n=NT({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function mQn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function rtu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?t5.exploded():t5.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var qjc=ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});function PQn({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RC.ok(tI.body(void 0)),docs:void 0},c=xin(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointPathParameters=c.example;let d=xin(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=xin(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=rtu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let l=mQn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointHeaders=l.example;let b=mQn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let D=OQn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});D!=null&&D.type==="success"&&Object.assign(g,D.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=NT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Var({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:D,jsonExample:A}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:D}),g[m.name.wireValue]=A}u.request=rK.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=rK.reference(O);break}default:Ao(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1});break;default:Ao(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}case"text":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}default:Ao(t.response.body.value)}break}case"text":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ao(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RC.error({body:void 0,error:a.declaration.name});else{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:c8a(u),url:gAE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function gAE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function Tjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=xin(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=xin(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let c=rtu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=mQn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=mQn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(O=>O.origin==="client")[0];if(l!=null){let O=M0_({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:l.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=M0_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:OAE(t,n)},jsonExample:void 0}}function M0_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=NT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return VAe.reference(i.example)}function OAE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function jQn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function WRi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function A0_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);c!==void 0?n.pathParameters[u.name.originalName]=c:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.queryParameters[u.name.name.originalName]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.headers[u.name.wireValue]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function q0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=A0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},c={},d={endpoint:{method:e.method,path:mAE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}default:Ao(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:c,baseExample:d}}function mAE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=jQn(i.v2Examples),u=n??a,c;u==null?c=i.name.originalName:c=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function itu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:V4.json(l8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?l8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?l8a(o):o;n[s]={...a,body:V4.json(l)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?l8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?l8a(o):o;n[s]={...a,body:V4.json(l)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c))i[s]={...a,body:V4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:V4.stream([o])}}break}case"streamParameter":break;default:Ao(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function l8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var wQn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},PAE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function ntu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,PAE({exampleStore:n,key:e,example:u}),!0}return!1}function T0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:c,baseExample:d}=q0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],l=Object.keys(c)[0],b=Object.values(c)[0],g=jAE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:l,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(wAE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=itu({endpoint:e}),m=wQn(l??"base","base",void 0);ntu({key:m,displayName:l??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function jAE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:c,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],l=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:P}=itu({endpoint:e,responseObject:b}),D=Object.keys(m)[0],A=Object.values(m)[0];for(let[M,E]of Object.entries(O)){let T,z;t[M]?(z=t[M],l.add(M),T=wQn(M,M,b?.statusCode)):u&&a?(z=u,T=wQn(a,M,b?.statusCode)):(z=r,T=wQn("base",M,b?.statusCode)),ntu({key:T,displayName:M,request:z,response:E,exampleStore:s,userOrAutoStore:c})&&(g=!0)}if(!g){let M=R_(`${e.name.originalName}_example`);i&&n&&l.add(i);let E=wQn(i??a??"base",D??"base",b?.statusCode);ntu({key:E,displayName:i??a??M,request:n??u??r,response:A??P,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return l}function wAE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:c}=itu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],l=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=wQn(g,s??o??"base",d?d.statusCode:l?l.statusCode:c.statusCode);ntu({key:m,displayName:g,request:O,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function f8a({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){let u=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&u.push({example:c.example})}if(a.userSpecifiedExamples.filter(c=>c.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let c of a.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&u.push({example:s.example})}a.autogeneratedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Tjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function Cjc({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:u,autoFullExamples:c}=T0_({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(s=>s.request!=null||s.response!=null))continue;let d=Object.values(a.v2Examples.userSpecifiedExamples).filter(s=>s!=null).flatMap(s=>s.codeSamples??[]);for(let[s,o]of Object.entries(c))c[s]={...o,codeSamples:d};for(let[s,o]of Object.entries(u))u[s]={...o,codeSamples:d}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Tjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function B0_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y6.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?y6.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function P3({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:by.container(iP.list({...i,list:i.list.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:by.container(iP.set({...i,set:i.set.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?P3({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:by.container(iP.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?P3({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:by.container(iP.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:by.container(iP.map({...i,map:i.map.map(n=>{let a=P3({filteredIr:e,exampleTypeReference:n.key}),u=P3({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:by.named({...r,shape:w1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:by.named({...r,shape:w1.enum(i)})}),object:i=>({...t,shape:by.named({...r,shape:w1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=B0_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:by.named({...r,shape:w1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:by.named({...r,shape:w1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Bjc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function SAE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function C0_({filteredIr:e,headers:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function DAE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?rK.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function EAE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RC.ok(tI.body(i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RC.ok(tI.stream(i.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(yy))),sse:i=>RC.ok(tI.sse(i.map(({event:n,data:a})=>{let u=P3({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yy))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RC.error({error:r,body:i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Ijc({filteredIr:e,example:t}){return{...t,rootPathParameters:Bjc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Bjc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Bjc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:C0_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:C0_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:SAE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?DAE({filteredIr:e,requestBody:t.request}):void 0,response:EAE({filteredIr:e,response:t.response})}}function I0_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:w1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:w1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:P3({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=B0_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:w1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:w1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function zjc(e,t){if(t==null)return e;let r=sZi(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>I0_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(c,o.name.wireValue)&&s.push(o);return[c,{...d,shape:t0.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let l=o.id;return o.payload.type==="inlinedPayload"&&l!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(l,b.name.wireValue))}),o});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:sZi(e.errors,c=>t.hasError(c)),services:Sd(sZi(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:Ijc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?Ijc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:MAE(e.serviceTypeReferenceInfo,t)}}function MAE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function Rin(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function gqe(e){return e.allParts.map(t=>t.originalName).join("/")}var aP={generateTypeId:e=>`type_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${gqe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${gqe(e)}`,generateSubpackageId:e=>`subpackage_${gqe(e)}`,generateEndpointId:(e,t)=>{let r=gqe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${gqe(e)}`,generateWebhookId:(e,t)=>`webhooks_${gqe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${gqe(e)}`};function SQn(e){return e.type!=null}var atu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:c,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:l,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=aP.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=aP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=aP.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Nin=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=AAE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=aP.generateTypeId(t),c={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=c,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=aP.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=aP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&gR(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=aP.generateServiceId(t.name),a=r.id,u=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])gR(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])gR(s.valueType,u,d);for(let s of r.queryParameters)gR(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=Rin(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&XA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)otu(o,u,d);for(let o of s.properties)gR(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&kB(i.request.body)){let o=Rin(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{gR(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)W4._visit(o,{file:Ko,bodyProperty:({valueType:l})=>{gR(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&j1._visit(r.response.body,{fileDownload:Ko,json:s=>{gR(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&gR(s.nonStreamResponse.value.responseBodyType,u,d)},text:Ko,bytes:Ko,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(aP.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=aP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&HH._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)otu(d,a,u);for(let d of c.properties)gR(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!SQn(i.payload)){let d=Rin(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{gR(c,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let c of i.messages)YL._visit(c.body,{reference:({bodyType:d})=>{gR(d,a,u)},inlinedBody:d=>{for(let s of d.extends)otu(s,a,u);for(let s of d.properties)gR(s.valueType,a,u)},_other:()=>{}});for(let c of i.queryParameters)gR(c.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(b=>{s.add(b)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}u[c]=s.size>0?s:void 0}}return new atu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Ao(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(aP.generateSubpackageId(i))}}};function AAE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ao(e)}}function gR(e,t,r){ol._visit(e,{container:i=>{qAE(i,t,r)},named:i=>{otu(i,t,r)},primitive:Ko,unknown:Ko,_other:Ko})}function otu(e,t,r){t.add(aP.generateTypeId(e)),r.add(e.fernFilepath)}function qAE(e,t,r){Ky._visit(e,{list:i=>{gR(i,t,r)},map:i=>{gR(i.keyType,t,r),gR(i.valueType,t,r)},optional:i=>{gR(i,t,r)},nullable:i=>{gR(i,t,r)},set:i=>{gR(i,t,r)},literal:Ko,_other:Ko})}var TAE=[Hs.AvailabilityStatus.GeneralAvailability];function bmi(e){return e!==void 0&&!TAE.includes(e.status)}var xjc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},d8a=class{errors;constructor(){this.errors=new xjc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability)||(n.endpoints?.every(u=>bmi(u.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,c]of Object.entries(n)){if(bmi(c.availability))continue;let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}if(bmi(d.availability)){this.errors.add(`Endpoint "${u}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:u,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:Ao(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:u,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:Ao(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ao(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bmi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ao(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ao(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ao(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ao(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ao(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:Ao(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Fin(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=BAE(e.environments,t.environments,r),{services:u,websocketChannels:c}=IAE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:CAE(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function CAE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function BAE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=z0_(e),n=z0_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:lR.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,c=t.environments;if(u.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:u,s=i?u:c,o={},{deconflictedEnvironments2:l,changedBaseUrlIds2:b}=zAE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[{id:g,name:O},...l.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(l.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:c,s=u.type==="multipleBaseUrls"?u:c,{deconflictedEnvironments1:o,changedBaseUrlIds1:l}=xAE(d,s,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:l}}if(u.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=RAE(u,c,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(l=>({...o,urls:{...o.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function IAE(e,t,r,i){if(r!=null)for(let[u,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}if(i!=null)for(let[u,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}let n=e.services;for(let[u,c]of Object.entries(t.services))n[u]==null?n[u]=c:n[u]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[u].endpoints??[],...c.endpoints],pathParameters:[...n[u].pathParameters??[],...c.pathParameters??[]],headers:[...n[u].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[u].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function zAE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Rjc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:lR.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function xAE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=Rjc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:lR.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function RAE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Rjc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,l])=>[i[o]??o,l]))}));return{deconflictedEnvironments:lR.multipleBaseUrls({baseUrls:u,environments:c}),changedBaseUrlIds:i}}function z0_(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 Rjc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var f_=class e{breadcrumbs=[];context;static STRING=Hs.TypeReference.primitive({v1:"STRING",v2:Hs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Hs.TypeReference.container(Hs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var R0_=require("fs/promises");var Njc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:c,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},x0_=Njc;var gmi;(function(e){e.WARNING="warning",e.ERROR="error"})(gmi||(gmi={}));var HRi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new Fjc({logger:t,relativePathToFile:za.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||gmi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===gmi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gmi.WARNING&&!t))switch(r.level){case gmi.ERROR:if(this.logger.log(Sb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Sb.Error,` - at location (${n})`)}break}}},Fjc=class{logger;relativePathToFile;map=new x0_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,R0_.readFile)(this.relativePathToFile,"utf-8");xd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Sb.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var I6=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Aee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=R_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let l=await fetch(o);if(!l.ok)return{resolved:!1};try{let b=await l.text();try{a=JSON.parse(b),r=a}catch{a=xd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let c of t)u.push(await this.resolveNestedExternalReferences(c,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let c=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),c.resolved)return c.value}else{let c=`${n}${u}`;if(i.has(c))return t;i.add(c);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,c]of Object.entries(t))typeof c=="object"&&c!==null?a[u]=await this.resolveNestedExternalReferences(c,r,i,n):a[u]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return eir.ReadOnly;if(n)return eir.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new h$.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new h$.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:$L.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var lO=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var h$={};Na(h$,{AudienceExtension:()=>utu,FernAvailabilityExtension:()=>stu,FernEnumExtension:()=>ctu,FernIgnoreExtension:()=>Lin,FernOptionalExtension:()=>ltu,FernTypeExtension:()=>ptu,FernTypeNameExtension:()=>_tu,SdkGroupNameExtension:()=>ftu,SdkMethodNameExtension:()=>dtu});var utu=class extends lO{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var stu=class extends lO{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return $L.InDevelopment;case"PRE_RELEASE":case"BETA":return $L.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return $L.GeneralAvailability;case"DEPRECATED":return $L.Deprecated;default:return}}};var NAE=Yo.object({snake:Yo.string().optional(),camel:Yo.string().optional(),screamingSnake:Yo.string().optional(),pascal:Yo.string().optional()}),FAE=Yo.object({description:Yo.string().optional(),name:Yo.string().optional(),casing:NAE.optional()}),N0_=Yo.record(FAE);var ctu=class extends lO{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=N0_.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 Lin=class extends lO{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var ltu=class extends lO{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ftu=class extends lO{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var dtu=class extends lO{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ptu=class extends lO{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var _tu=class extends lO{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var mQt=class extends f_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Nin(i),this.ir={auth:{docs:void 0,requirement:Hs.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Hs.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Lin({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Lin({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=Cjc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=f8a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let c of a.endpoints)r.has(c.id)&&u.push(c);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=R_(n?.join(".")),u=R_(r),c=this.context.namespace?`${R_(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,u=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(u),this.addTypesToIr({...n,[u]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:d7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>R_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var vA={};Na(vA,{AbstractConverters:()=>Ujc,ExampleConverter:()=>s6e,SchemaConverters:()=>Ljc,ServersConverter:()=>Oqe});var Ujc={};Na(Ujc,{AbstractMediaTypeObjectConverter:()=>btu,AbstractParameterConverter:()=>gtu});var s6e=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING=Hh.STRING;EXAMPLE_NUMBER=Hh.DOUBLE;EXAMPLE_BOOLEAN=Hh.BOOLEAN;EXAMPLE_INTEGER=Hh.INT;EXAMPLE_DATE=Hh.DATE;EXAMPLE_DATE_TIME=Hh.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(c=>c?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(c=>c.validExample),errors:u?[]:a.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,l=!t.required?.includes(d);if(o&&l){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(l=>!s.has(l)).forEach(l=>{let g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:g})})}for(let{key:d,result:s}of c)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${c}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${c}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var Ljc={};Na(Ljc,{ArraySchemaConverter:()=>qQn,EnumSchemaConverter:()=>DQn,ObjectSchemaConverter:()=>EQn,OneOfSchemaConverter:()=>MQn,PrimitiveSchemaConverter:()=>AQn,SchemaConverter:()=>$Ri,SchemaOrReferenceConverter:()=>EK});function F0_(e){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ol.primitive({v1:"BASE_64",v2:Wd.base64({})});case"BOOLEAN":return ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:void 0})});case"DATE":return ol.primitive({v1:"DATE",v2:Wd.date({})});case"DATE_TIME":return ol.primitive({v1:"DATE_TIME",v2:Wd.dateTime({})});case"FLOAT":return ol.primitive({v1:"FLOAT",v2:Wd.float({})});case"DOUBLE":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:void 0,validation:void 0})});case"UINT":return ol.primitive({v1:"UINT",v2:Wd.uint({})});case"UINT_64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({})});case"INTEGER":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:void 0,validation:void 0})});case"LONG":return ol.primitive({v1:"LONG",v2:Wd.long({default:void 0})});case"STRING":return ol.primitive({v1:"STRING",v2:Wd.string({default:void 0,validation:void 0})});case"UUID":return ol.primitive({v1:"UUID",v2:Wd.uuid({})});case"BIG_INTEGER":return ol.primitive({v1:"BIG_INTEGER",v2:Wd.bigInteger({default:void 0})});default:return}},unknown:()=>ol.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ol.container(Ky.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ol.container(Ky.list(t))},optional:t=>{if(t!=null)return ol.container(Ky.optional(t))},nullable:t=>{if(t!=null)return ol.container(Ky.nullable(t))},set:t=>{if(t!=null)return ol.container(Ky.set(t))},literal:t=>ol.container(Ky.literal(t._visit({string:r=>KL.string(r),boolean:r=>KL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var DQn=class extends f_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],c=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:t0.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var htu=class extends f_{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()}));return{type:t0.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ol.container(Ky.map({keyType:f_.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function p8a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},c={},d=new Set;for(let[s,o]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let b=LAE(r,o,i)??i.convertBreadcrumbsToName(l),g="nullable"in o?o.nullable:!1,m=new EK({context:i,breadcrumbs:l,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])c[P]==null&&(c[P]=new Set),c[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:u,referencedTypes:d}}function LAE(e,t,r){return r.isReferenceObject(t)?void 0:new h$.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var EQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:t0.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=p8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[l,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",l.toString()],O;if(this.context.isReferenceObject(b)){let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(b)}`);continue}if(O=M,typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0),!d||Object.keys(O.properties??{}).every(E=>!this.schema.required?.includes(E))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:c});continue}}else O=b;typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0);let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:D,propertiesByAudience:A}=p8a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...A},D.forEach(M=>{c.add(M)})}for(let l of Object.keys(s))c.add(l);return{type:t0.object({properties:r,extends:u.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(yy),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var ytu=class extends lO{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var vtu;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let l=i(s.description);if(l)return l}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let l=a(s,o);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!l.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):l.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let l=s.properties;if(!l)return;let b=Object.keys(l);if(b.length===0)return;let g=u(s,o);if(g.length>0){let P=c(g).slice(0,1).map(D=>d(D));if(P.length>0)return P.join("")}let O=c(b);if(O.length>0)return O.slice(0,1).map(P=>d(P)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let l=s.properties;if(!l)return[];let b=new Set(Object.keys(l)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(P=>{g.add(P)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function c(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),P=0;for(let D of o)m===D?P+=15:m.includes(D)&&(P+=10);for(let D of l)m===D?P+=8:m.includes(D)&&(P+=5);for(let D of b)m===D?P+=3:m.includes(D)&&(P+=2);return P+=Math.max(0,5-O.length),{prop:O,score:P}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=c;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(vtu||(vtu={}));var MQn=class extends f_{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new ytu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new EK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let b=o.convert();if(b?.type!=null&&l!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:JL.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=p8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(l.ok){let g=this.context.typeReferenceToDeclaredTypeName(l.reference);g!=null&&c.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:t0.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let c=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=vtu.generateDisplayNameForInlinedObject({...u,typeName:d},n),l=new $Ri({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??u}).convert();if(l!=null){let b=l.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:t0.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ol.container(Ky.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var AQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ol.container(Ky.literal(KL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ol.primitive({v1:vy.Date,v2:Wd.date({})});if(this.schema.format==="date-time")return ol.primitive({v1:vy.DateTime,v2:Wd.dateTime({})})}return ol.primitive({v1:"STRING",v2:Wd.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ol.container(Ky.literal(KL.boolean(t))):ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var UAE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],$Ri=class e extends f_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new h$.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new DQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=Y2n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new AQn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new qQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new MQn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new htu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new EQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:ol.unknown(),resolvedType:ol.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new h$.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=F0_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...UAE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var EK=class extends f_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new $Ri({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ol.container(Ky.optional(t))}wrapInNullable(t){return ol.container(Ky.nullable(t))}};var qQn=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var btu=class extends f_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=R_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let c=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var gtu=class extends f_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??f_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var Otu=class extends lO{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var L0_="Base",Oqe=class e extends f_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(o=>o.id===c.id)===d),a=[i,...n],u=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:u[0]?.id,environments:lR.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(yy);return{value:{defaultEnvironment:t[0]?.id,environments:lR.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new Otu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,b]of Object.entries(r.variables??{}))l!==a&&(s[l]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(yy)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?L0_:e.getServerExtensionName({server:this.servers[0],context:this.context})??L0_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var _8a={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"},VAE=new Set(Object.values(_8a));var TQn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1923
+ `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:c}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(ul(!a,"Browser should be launched with either pipe or debugging port - not both."),d.push("--remote-debugging-pipe")):d.push(`--remote-debugging-port=${a||0}`));let s=!1,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,Ty_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let l=d[o].split("=",2)[1];ul(typeof l=="string","`--user-data-dir` is malformed");let b=c;return b||(ul(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}}defaultArgs(t={}){let r=["--allow-pre-commit-input","--disable-background-networking","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-breakpad","--disable-client-side-phishing-detection","--disable-component-extensions-with-background-pages","--disable-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${Cy_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(c=>c.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?vko({browser:Lq.CHROME,channel:pSE(t)}):this.resolveExecutablePath()}};function pSE(e){switch(e){case"chrome":return T6.STABLE;case"chrome-dev":return T6.DEV;case"chrome-beta":return T6.BETA;case"chrome-canary":return T6.CANARY}}var yPc=ui(require("fs"),1),Ain=require("fs/promises"),By_=ui(require("os"),1),Eeu=ui(require("path"),1);vB();nq();var Meu=class extends cQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:c=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&ul(c===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${c||0}`));let s,o=!0,l=d.findIndex(g=>["-profile","--profile"].includes(g));if(l!==-1){if(s=d[l+1],!s||!yPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,Ain.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await vOc(Lq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(ul(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await TGn(t)}catch(i){throw fg(i),i}else try{await(0,Ain.unlink)(Eeu.default.join(t,"user.js"));let i=Eeu.default.join(t,"prefs.js.puppeteer");if(yPc.default.existsSync(i)){let n=Eeu.default.join(t,"prefs.js");await(0,Ain.unlink)(n),await(0,Ain.rename)(i,n)}}catch(i){fg(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(By_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(c=>c.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var Iy_=require("path");var H2a=Object.freeze({chromium:"1108766",firefox:"latest"});var vPc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},OQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},lQn,ymi,G2a,$2a,fQn=class extends R4a{constructor(t){let{configuration:r,...i}=t;switch(super(i),lQn.add(this),ymi.set(this,void 0),G2a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=H2a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=H2a.chromium;break}this.connect=this.connect.bind(this),this.launch=this.launch.bind(this),this.executablePath=this.executablePath.bind(this),this.defaultArgs=this.defaultArgs.bind(this),this.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return vPc(this,G2a,r,"f"),OQt(this,lQn,"a",$2a).launch(t)}executablePath(t){return OQt(this,lQn,"a",$2a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=OQt(this,ymi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,Iy_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=OQt(this,G2a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return OQt(this,lQn,"a",$2a).product}defaultArgs(t={}){return OQt(this,lQn,"a",$2a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new oko(t)}};ymi=new WeakMap,G2a=new WeakMap,lQn=new WeakSet,$2a=function(){if(OQt(this,ymi,"f")&&OQt(this,ymi,"f").product===this.lastLaunchedProduct)return OQt(this,ymi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=H2a.chromium,vPc(this,ymi,new Deu(this),"f");break;case"firefox":this.defaultBrowserRevision=H2a.firefox,vPc(this,ymi,new Meu(this),"f");break;default:throw new Error(`Unknown product: ${OQt(this,G2a,"f")}`)}return OQt(this,ymi,"f")};Gbc();eFa();var _SE=new fQn({isPuppeteerCore:!0}),{connect:D55,createBrowserFetcher:E55,defaultArgs:M55,executablePath:A55,launch:q55}=_SE;var s0_=require("os"),c0_=require("path"),l0_=ui(u0_(),1);function LME(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var f0_=()=>{var e,t,r,i,n,a,u,c,d,s,o,l,b,g,O,m,P,D,A,M,E,T,z,G,I,R,U,Y,J,X,ae,pe,de,me,Le,yt,De;let Ae=(0,l0_.cosmiconfigSync)("puppeteer").search(),Ct=Ae?Ae.config:{};if(Ct.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Ct.defaultProduct)!==null&&i!==void 0?i:"chrome",Ct.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Ct.executablePath,Ct.executablePath&&(Ct.skipDownload=!0),Ct.skipDownload=!!((b=(l=(o=(s=(d=(c=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&c!==void 0?c:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&l!==void 0?l:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Ct.skipDownload),Ct.skipDownload||(Ct.browserRevision=(P=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&P!==void 0?P:Ct.browserRevision,Ct.downloadHost=(M=(A=(D=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_host)!==null&&A!==void 0?A:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Ct.downloadHost,Ct.downloadPath=(z=(T=(E=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_path)!==null&&T!==void 0?T:process.env.npm_package_config_puppeteer_download_path)!==null&&z!==void 0?z:Ct.downloadPath),Ct.cacheDirectory=(U=(R=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&R!==void 0?R:Ct.cacheDirectory)!==null&&U!==void 0?U:(0,c0_.join)((0,s0_.homedir)(),".cache","puppeteer"),Ct.temporaryDirectory=(X=(J=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&J!==void 0?J:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Ct.temporaryDirectory,(ae=Ct.experiments)!==null&&ae!==void 0||(Ct.experiments={}),Ct.experiments.macArmChromiumEnabled=!!((me=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&me!==void 0?me:Ct.experiments.macArmChromiumEnabled),Ct.logLevel=(De=(yt=(Le=process.env.PUPPETEER_LOGLEVEL)!==null&&Le!==void 0?Le:process.env.npm_config_LOGLEVEL)!==null&&yt!==void 0?yt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Ct.logLevel,!LME(Ct.defaultProduct))throw new Error(`Unsupported product ${Ct.defaultProduct}`);return Ct};var UME=f0_(),VME=new fQn({isPuppeteerCore:!1,configuration:UME}),{connect:F95,createBrowserFetcher:L95,defaultArgs:U95,executablePath:V95,launch:d0_}=VME;var WME="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",HME={"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 u8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),u8a(e,t-1,r*i,i);throw n}}async function p0_(){try{return await d0_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function $ME(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(HME),await r.setUserAgent(WME),await r.setJavaScriptEnabled(!0),await u8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await u8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function GME(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 Sjc({url:e,browser:t}){try{let r;if(t?r=await $ME(t,e):r=await u8a(()=>GME(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function _0_(e){try{let t=await u8a(()=>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 QME=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function h0_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,gQn.join)(process.cwd(),"fern");try{let r=await JME(e,(0,gQn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function JME(e,t){let r=YME(e),i=(0,gQn.join)(t,r);if(!KME(r))throw new Error(`${r} - file extension not supported`);if((0,Xeu.existsSync)(i))return i;try{(0,Xeu.mkdirSync)((0,gQn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await _0_(e);return Cu_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function KME(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let i=r.toLowerCase();return!(i&&!QME.includes(i))}function YME(e){e.startsWith("http")&&(e=new URL(e).pathname);let t=e.split("#");if(t.length===0)return"image";let r=t[0];if(!r)return"image";let i=r.split("?");if(i.length===0)return"image";let n=i[0];return n&&decodeURIComponent(n.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function XME(e){let t=[];return If(e,"element",r=>{r.tagName==="img"&&Array.isArray(r.properties.className)&&r.properties.className.includes("rm-Logo-img")&&t.push(r)}),t.length>0?t:void 0}async function y0_(e,t){let r=NHn(e),i=XME(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await h0_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var v0_=28;async function b0_(e,t){e=new URL(e);let r=[];if(t){let n=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),n.push(await a.content()),await a.click(".rm-ThemeToggle"),n.push(await a.content())}catch{}await Promise.all(n.map(async a=>await y0_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=za.of(BJ(i[0]));return{light:n,dark:n,height:v0_}}if(i[0]!=null&&i[1]!=null){let n=za.of(BJ(i[0])),a=za.of(BJ(i[1]));return{light:n,dark:a,height:v0_}}}}var Zeu=class extends Qtn{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:Z7a});let i=await this.getHastForUrl(this.url),n=Hs_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let l=await this.scrapeTab({name:o.name,url:o.url});if(!l)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Bu(this.absolutePathToFernDirectory,za.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:l});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:l});for(let m of O)b.addItem({item:m})}let a=await p0_(),u=await b0_(this.url,a);u!=null&&r.setLogo({logo:u});let c=await _i_(i);r.setTitle({title:c});let d=await li_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),l=await fetch(d);if(l.ok){let b=Buffer.from(await l.arrayBuffer()),g=Bu(o,za.of("favicon"));await(0,VRi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:$ae(this.absolutePathToFernDirectory,g)})}}let s=await Gs_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Bu(this.absolutePathToFernDirectory,za.of("assets"));return await(0,VRi.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let i=new URL(r,this.url),n=await this.getHastForUrl(i),a=Us_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=Vs_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}catch(i){this.logger.error(`Failed to scrape tab ${t}: ${i instanceof Error?i.message:String(i)}`),i instanceof Error&&i.stack&&this.logger.error(`Stack trace: ${i.stack}`)}}async getHastForUrl(t){let r=await Sjc({url:t});return NHn(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let i of r){this.logger.debug(`Processing section: ${i.group}`);let n=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i});await(0,VRi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let c=await Sjc({url:u}),d=await Ls_({logger:this.logger,html:c,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,VRi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,l])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Bu(n,za.of(l)),m=zd(O);await(0,VRi.mkdir)(m,{recursive:!0}),await(0,VRi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.toString()}, skipping`)})),await Promise.all(i.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:n,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let i=[];for(let n of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let c of n.pages)if(c.type==="page")u.contents.push({page:c.page,path:$ae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Bu(t,za.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Bu(t,za.of(this.kebabCaseWithoutEmojis(r.group)))}kebabCaseWithoutEmojis(t){return t.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}};var g0_=require("fs/promises");async function Djc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new Jtn;a.setInstance({companyName:n}),await new Zeu({url:e,context:r,builder:a,absolutePathToFernDirectory:Bu($c.of(process.cwd()),za.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,g0_.writeFile)(Bu($c.of(t),za.of(PH),za.of(Lae)),JSON.stringify({version:i,organization:n},void 0,4))}var Ejc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!HZi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=$c.of(CI());await Djc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var O0_="0.0.0";var m0_={[$h.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,QB(e)])),[$h.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[$h.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[$h.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[$h.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[$h.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[$h.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[$h.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[$h.GenerationLanguage.SWIFT]:new Set([])};var kME=["go","ruby"];function Aee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=l=>({unsafeName:l,safeName:eAE({name:l,keywords:tAE({generationLanguage:e,keywords:t})})}),c=R_(n),d=QB(c),s=cZi(n),o=aZi(c);return r&&(!nAE(o)&&(e==null||kME.includes(e))&&(c=o.map((l,b)=>{if(b>0){let g=keu(l);if(g!=null)return g;if(etu(l))return l.toUpperCase()}return l}).join(""),d=QB(o.map((l,b)=>{let g=keu(l);return g??(etu(l)?l.toUpperCase():b===0?QB(l):l)}).join(""))),s=n.split(" ").map(l=>l.split(/(\d+)/).map(cZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??c),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function eAE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":iAE(e)?"_"+e:e}function tAE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return m0_[e]}var rAE=/^[0-9]/;function iAE(e){return rAE.test(e)}function nAE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=keu(i)!=null||etu(i),a=keu(t)!=null||etu(t);return n&&a})}function keu(e){return oAE.get(e.toUpperCase())}function etu(e){return aAE.has(e.toUpperCase())}var aAE=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"]),oAE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Mjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:qoe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return hen(e.auth,{single:i=>{let n=P0_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:qoe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:qoe.Any,schemes:i.map(n=>P0_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function P0_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return VRa(c,{header:d=>YA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>j0_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>ttu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return ttu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>ttu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return ttu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return j0_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function ttu({casingsGenerator:e,docs:t,rawScheme:r}){return YA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function j0_({casingsGenerator:e,docs:t,rawScheme:r}){return YA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function d7(e){let t=sAE(e),{value:r,done:i}=Ajc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...uAE(t)]}}function*uAE(e){let t;do{let{value:r}=Ajc(e,"}"),i=Ajc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*sAE(e){for(let t of e)yield t}function Ajc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function s8a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:sir(i,{singleBaseUrl:()=>lR.singleBaseUrl(cAE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>lR.multipleBaseUrls(lAE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,sir(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function cAE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>sir(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:w0_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function lAE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>sir(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:Sd(a.urls,u=>w0_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function w0_(e){return e.endsWith("/")?e.slice(0,-1):e}function c8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Var({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function S0_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return War({containerType:t});switch(t.type){case"list":{let u=NT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:iP.literal({literal:t.literal._visit({boolean:u=>kd.boolean(u),string:u=>kd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return War({containerType:t});let u=NT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=NT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?War({containerType:t}):{type:"success",example:iP.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=NT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=NT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||c.type==="failure"?War({containerType:t}):{type:"success",example:iP.map({map:[{key:u.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:c.jsonExample}}}default:Ao(t)}}function War({containerType:e}){switch(e.type){case"list":return{type:"success",example:iP.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:iP.literal({literal:e.literal._visit({boolean:t=>kd.boolean(t),string:t=>kd.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:iP.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:iP.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:iP.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:iP.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ao(e)}}function E0_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return hAE({fieldName:e,default_:fAE(t.v2),validation:dAE(t.v2)});case"BASE_64":return{type:"success",example:kd.base64(Hh.BASE64),jsonExample:Hh.BASE64};case"BOOLEAN":return{type:"success",example:kd.boolean(Hh.BOOLEAN),jsonExample:Hh.BOOLEAN};case"DATE":return{type:"success",example:kd.date(Hh.DATE),jsonExample:Hh.DATE};case"DATE_TIME":return{type:"success",example:kd.datetime({datetime:new Date(Hh.DATE_TIME),raw:Hh.DATE_TIME}),jsonExample:Hh.DATE_TIME};case"DOUBLE":return yAE({fieldName:e,validation:pAE(t.v2)});case"FLOAT":return{type:"success",example:kd.float(Hh.FLOAT),jsonExample:Hh.FLOAT};case"INTEGER":return vAE({fieldName:e,validation:_AE(t.v2)});case"UINT_64":return{type:"success",example:kd.uint64(Hh.INT64),jsonExample:Hh.INT64};case"UINT":return{type:"success",example:kd.uint(Hh.UINT),jsonExample:Hh.UINT};case"BIG_INTEGER":return{type:"success",example:kd.bigInteger(Hh.INT64.toString()),jsonExample:`${Hh.INT64}`};case"LONG":return{type:"success",example:kd.long(Hh.INT64),jsonExample:Hh.INT64};case"UUID":return{type:"success",example:kd.uuid(Hh.UUID),jsonExample:Hh.UUID};default:Ao(t.v1)}}function fAE(e){if(e?.type==="string")return e.default}function dAE(e){if(e?.type==="string")return e.validation}function pAE(e){if(e?.type==="double")return e.validation}function _AE(e){if(e?.type==="integer")return e.validation}function D0_(e){if(e<=Hh.SAMPLE_STRINGS.length){let t=Hh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Hh.SAMPLE_STRINGS[Hh.SAMPLE_STRINGS.length-1]+".".repeat(e-Hh.SAMPLE_STRINGS.length)}function hAE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:kd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=D0_(n);return{type:"success",example:kd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=D0_(a);return{type:"success",example:kd.string({original:u}),jsonExample:u}}}let i=e??Hh.STRING;return{type:"success",example:kd.string({original:i}),jsonExample:i}}function yAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.double(r),jsonExample:r};if(i)return{type:"success",example:kd.double(i),jsonExample:i}}return{type:"success",example:kd.double(Hh.DOUBLE),jsonExample:Hh.DOUBLE}}function vAE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:kd.integer(r),jsonExample:r};if(i)return{type:"success",example:kd.integer(i),jsonExample:i}}return{type:"success",example:kd.integer(Hh.INT),jsonExample:Hh.INT}}function OQn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=NT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:c,jsonExample:d}=u;return{type:"success",example:w1.alias({value:c}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:w1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let b=t[l.typeId];if(b==null)continue;let g=OQn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),c.push(...g.example.properties))}let d=bAE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:w1.object({properties:[...c,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let c of r.shape.members){let d=NT({fieldName:e,typeReference:c.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:w1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=NT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(c[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...c}}),samePropertiesAsObject:o=>{let l=t[o.typeId];if(l==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=OQn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:l,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.samePropertiesAsObject({typeId:l.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...c}}},singleProperty:o=>{let l=NT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:b,jsonExample:g}=l;return{type:"success",example:w1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y6.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function bAE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=NT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Var({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:l,propertyAccess:s.propertyAccess}),c[s.name.wireValue]=b}return{type:"success",example:w1.object({properties:d}),jsonExample:c}}function NT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=OQn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:by.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=S0_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=War({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:by.container(s)},jsonExample:o}}let{example:c,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:by.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:c}=E0_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:by.primitive(c)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:by.unknown(u)},jsonExample:u}}}}function xin(e,t){let r=[];for(let i of e){let n=NT({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function mQn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function rtu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Var({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=NT({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?t5.exploded():t5.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var qjc=ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});function PQn({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RC.ok(tI.body(void 0)),docs:void 0},c=xin(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointPathParameters=c.example;let d=xin(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=xin(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=rtu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let l=mQn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointHeaders=l.example;let b=mQn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let D=OQn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});D!=null&&D.type==="success"&&Object.assign(g,D.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=NT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Var({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:D,jsonExample:A}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:D}),g[m.name.wireValue]=A}u.request=rK.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=rK.reference(O);break}default:Ao(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1});break;default:Ao(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}case"text":{if(g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.stream([{...O,jsonExample:m}]));break}default:Ao(t.response.body.value)}break}case"text":{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qjc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RC.ok(tI.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ao(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RC.error({body:void 0,error:a.declaration.name});else{let g=NT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:c8a(u),url:gAE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function gAE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function Tjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=xin(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=xin(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let c=rtu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=mQn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=mQn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(O=>O.origin==="client")[0];if(l!=null){let O=M0_({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:l.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=M0_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:OAE(t,n)},jsonExample:void 0}}function M0_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=NT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return VAe.reference(i.example)}function OAE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function jQn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function WRi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function A0_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);c!==void 0?n.pathParameters[u.name.originalName]=c:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.queryParameters[u.name.name.originalName]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:c,autoExample:d}=jQn(u.v2Examples);if(c!==void 0)n.headers[u.name.wireValue]=c;else if(d!==void 0){if(r&&Var({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function q0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=A0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},c={},d={endpoint:{method:e.method,path:mAE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=WRi(e.requestBody.v2Examples);for(let[l,b]of Object.entries(s))u[l]={...d,requestBody:b};for(let[l,b]of Object.entries(o))c[l]={...d,requestBody:b};break}default:Ao(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:c,baseExample:d}}function mAE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=jQn(i.v2Examples),u=n??a,c;u==null?c=i.name.originalName:c=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function itu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:V4.json(l8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?l8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?l8a(o):o;n[s]={...a,body:V4.json(l)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c)){let l=e.source?.type==="openrpc"?l8a(o):o;i[s]={...a,body:V4.json(l)}}for(let[s,o]of Object.entries(d)){let l=e.source?.type==="openrpc"?l8a(o):o;n[s]={...a,body:V4.json(l)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:c,autoExamples:d}=WRi(u.v2Examples);for(let[s,o]of Object.entries(c))i[s]={...a,body:V4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:V4.stream([o])}}break}case"streamParameter":break;default:Ao(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function l8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var wQn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},PAE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function ntu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,PAE({exampleStore:n,key:e,example:u}),!0}return!1}function T0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:c,baseExample:d}=q0_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],l=Object.keys(c)[0],b=Object.values(c)[0],g=jAE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:l,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(wAE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=itu({endpoint:e}),m=wQn(l??"base","base",void 0);ntu({key:m,displayName:l??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function jAE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:c,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],l=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:P}=itu({endpoint:e,responseObject:b}),D=Object.keys(m)[0],A=Object.values(m)[0];for(let[M,E]of Object.entries(O)){let T,z;t[M]?(z=t[M],l.add(M),T=wQn(M,M,b?.statusCode)):u&&a?(z=u,T=wQn(a,M,b?.statusCode)):(z=r,T=wQn("base",M,b?.statusCode)),ntu({key:T,displayName:M,request:z,response:E,exampleStore:s,userOrAutoStore:c})&&(g=!0)}if(!g){let M=R_(`${e.name.originalName}_example`);i&&n&&l.add(i);let E=wQn(i??a??"base",D??"base",b?.statusCode);ntu({key:E,displayName:i??a??M,request:n??u??r,response:A??P,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return l}function wAE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:c}=itu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],l=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=wQn(g,s??o??"base",d?d.statusCode:l?l.statusCode:c.statusCode);ntu({key:m,displayName:g,request:O,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function f8a({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){let u=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&u.push({example:c.example})}if(a.userSpecifiedExamples.filter(c=>c.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let c of a.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=PQn({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&u.push({example:s.example})}a.autogeneratedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Tjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function Cjc({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:u,autoFullExamples:c}=T0_({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(s=>s.request!=null||s.response!=null))continue;let d=Object.values(a.v2Examples.userSpecifiedExamples).filter(s=>s!=null).flatMap(s=>s.codeSamples??[]);for(let[s,o]of Object.entries(c))c[s]={...o,codeSamples:d};for(let[s,o]of Object.entries(u))u[s]={...o,codeSamples:d}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=u}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Tjc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:u}=a;n.examples=[...n.examples,u]}return e}function B0_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y6.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?y6.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function P3({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:by.container(iP.list({...i,list:i.list.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:by.container(iP.set({...i,set:i.set.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?P3({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:by.container(iP.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?P3({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:by.container(iP.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:by.container(iP.map({...i,map:i.map.map(n=>{let a=P3({filteredIr:e,exampleTypeReference:n.key}),u=P3({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:by.named({...r,shape:w1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:by.named({...r,shape:w1.enum(i)})}),object:i=>({...t,shape:by.named({...r,shape:w1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:P3({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=B0_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:by.named({...r,shape:w1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=P3({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:by.named({...r,shape:w1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Bjc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function SAE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function C0_({filteredIr:e,headers:t}){return t.map(r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function DAE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=P3({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=P3({filteredIr:e,exampleTypeReference:r});return i!==void 0?rK.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function EAE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RC.ok(tI.body(i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RC.ok(tI.stream(i.map(n=>P3({filteredIr:e,exampleTypeReference:n})).filter(yy))),sse:i=>RC.ok(tI.sse(i.map(({event:n,data:a})=>{let u=P3({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yy))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RC.error({error:r,body:i!=null?P3({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Ijc({filteredIr:e,example:t}){return{...t,rootPathParameters:Bjc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Bjc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Bjc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:C0_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:C0_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:SAE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?DAE({filteredIr:e,requestBody:t.request}):void 0,response:EAE({filteredIr:e,response:t.response})}}function I0_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:w1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:w1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:P3({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=B0_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:w1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=P3({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:w1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function zjc(e,t){if(t==null)return e;let r=sZi(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>I0_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(c,o.name.wireValue)&&s.push(o);return[c,{...d,shape:t0.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let l=o.id;return o.payload.type==="inlinedPayload"&&l!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(l,b.name.wireValue))}),o});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:sZi(e.errors,c=>t.hasError(c)),services:Sd(sZi(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:Ijc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?Ijc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:MAE(e.serviceTypeReferenceInfo,t)}}function MAE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function Rin(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function gqe(e){return e.allParts.map(t=>t.originalName).join("/")}var aP={generateTypeId:e=>`type_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${gqe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${gqe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${gqe(e)}`,generateSubpackageId:e=>`subpackage_${gqe(e)}`,generateEndpointId:(e,t)=>{let r=gqe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${gqe(e)}`,generateWebhookId:(e,t)=>`webhooks_${gqe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${gqe(e)}`};function SQn(e){return e.type!=null}var atu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:c,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:l,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=aP.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=aP.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=aP.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var Nin=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=AAE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=aP.generateTypeId(t),c={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=c,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=aP.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=aP.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&gR(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=aP.generateServiceId(t.name),a=r.id,u=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])gR(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])gR(s.valueType,u,d);for(let s of r.queryParameters)gR(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=Rin(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&XA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)otu(o,u,d);for(let o of s.properties)gR(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&kB(i.request.body)){let o=Rin(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{gR(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)W4._visit(o,{file:Ko,bodyProperty:({valueType:l})=>{gR(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&j1._visit(r.response.body,{fileDownload:Ko,json:s=>{gR(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>gR(o.payload,u,d),json:o=>gR(o.payload,u,d),text:Ko,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&gR(s.nonStreamResponse.value.responseBodyType,u,d)},text:Ko,bytes:Ko,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(aP.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=aP.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&HH._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)otu(d,a,u);for(let d of c.properties)gR(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!SQn(i.payload)){let d=Rin(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{gR(c,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let c of i.messages)YL._visit(c.body,{reference:({bodyType:d})=>{gR(d,a,u)},inlinedBody:d=>{for(let s of d.extends)otu(s,a,u);for(let s of d.properties)gR(s.valueType,a,u)},_other:()=>{}});for(let c of i.queryParameters)gR(c.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(b=>{s.add(b)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(b=>{s.add(b)})}u[c]=s.size>0?s:void 0}}return new atu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Ao(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(aP.generateSubpackageId(i))}}};function AAE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ao(e)}}function gR(e,t,r){ol._visit(e,{container:i=>{qAE(i,t,r)},named:i=>{otu(i,t,r)},primitive:Ko,unknown:Ko,_other:Ko})}function otu(e,t,r){t.add(aP.generateTypeId(e)),r.add(e.fernFilepath)}function qAE(e,t,r){Ky._visit(e,{list:i=>{gR(i,t,r)},map:i=>{gR(i.keyType,t,r),gR(i.valueType,t,r)},optional:i=>{gR(i,t,r)},nullable:i=>{gR(i,t,r)},set:i=>{gR(i,t,r)},literal:Ko,_other:Ko})}var TAE=[Hs.AvailabilityStatus.GeneralAvailability];function bmi(e){return e!==void 0&&!TAE.includes(e.status)}var xjc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},d8a=class{errors;constructor(){this.errors=new xjc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(bmi(n.availability)||(n.endpoints?.every(u=>bmi(u.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(bmi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,c]of Object.entries(n)){if(bmi(c.availability))continue;let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}if(bmi(d.availability)){this.errors.add(`Endpoint "${u}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:u,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,c])=>[u,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,c])=>[u,c.valueType]))});for(let[u,c]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:Ao(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:u,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:Ao(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ao(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return bmi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ao(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ao(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ao(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ao(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ao(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:Ao(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Fin(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=BAE(e.environments,t.environments,r),{services:u,websocketChannels:c}=IAE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:CAE(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function CAE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function BAE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=z0_(e),n=z0_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:lR.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,c=t.environments;if(u.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:u,s=i?u:c,o={},{deconflictedEnvironments2:l,changedBaseUrlIds2:b}=zAE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[{id:g,name:O},...l.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(l.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:c,s=u.type==="multipleBaseUrls"?u:c,{deconflictedEnvironments1:o,changedBaseUrlIds1:l}=xAE(d,s,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:l}}if(u.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=RAE(u,c,r);return{environments:{defaultEnvironment:a,environments:lR.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(l=>({...o,urls:{...o.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function IAE(e,t,r,i){if(r!=null)for(let[u,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}if(i!=null)for(let[u,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=c),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?c:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=c)}let n=e.services;for(let[u,c]of Object.entries(t.services))n[u]==null?n[u]=c:n[u]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[u].endpoints??[],...c.endpoints],pathParameters:[...n[u].pathParameters??[],...c.pathParameters??[]],headers:[...n[u].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[u].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function zAE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Rjc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:lR.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function xAE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=Rjc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:lR.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function RAE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=Rjc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,l])=>[i[o]??o,l]))}));return{deconflictedEnvironments:lR.multipleBaseUrls({baseUrls:u,environments:c}),changedBaseUrlIds:i}}function z0_(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 Rjc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var f_=class e{breadcrumbs=[];context;static STRING=Hs.TypeReference.primitive({v1:"STRING",v2:Hs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Hs.TypeReference.container(Hs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var R0_=require("fs/promises");var Njc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:c,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},x0_=Njc;var gmi;(function(e){e.WARNING="warning",e.ERROR="error"})(gmi||(gmi={}));var HRi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new Fjc({logger:t,relativePathToFile:za.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||gmi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===gmi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===gmi.WARNING&&!t))switch(r.level){case gmi.ERROR:if(this.logger.log(Sb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Sb.Error,` - at location (${n})`)}break}}},Fjc=class{logger;relativePathToFile;map=new x0_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,R0_.readFile)(this.relativePathToFile,"utf-8");xd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Sb.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var I6=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Aee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=R_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:gmi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let l=await fetch(o);if(!l.ok)return{resolved:!1};try{let b=await l.text();try{a=JSON.parse(b),r=a}catch{a=xd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let c of t)u.push(await this.resolveNestedExternalReferences(c,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let c=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),c.resolved)return c.value}else{let c=`${n}${u}`;if(i.has(c))return t;i.add(c);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,c]of Object.entries(t))typeof c=="object"&&c!==null?a[u]=await this.resolveNestedExternalReferences(c,r,i,n):a[u]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return eir.ReadOnly;if(n)return eir.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new h$.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new h$.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:$L.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var lO=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var h$={};Na(h$,{AudienceExtension:()=>utu,FernAvailabilityExtension:()=>stu,FernEnumExtension:()=>ctu,FernIgnoreExtension:()=>Lin,FernOptionalExtension:()=>ltu,FernTypeExtension:()=>ptu,FernTypeNameExtension:()=>_tu,SdkGroupNameExtension:()=>ftu,SdkMethodNameExtension:()=>dtu});var utu=class extends lO{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var stu=class extends lO{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return $L.InDevelopment;case"PRE_RELEASE":case"BETA":return $L.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return $L.GeneralAvailability;case"DEPRECATED":return $L.Deprecated;default:return}}};var NAE=Yo.object({snake:Yo.string().optional(),camel:Yo.string().optional(),screamingSnake:Yo.string().optional(),pascal:Yo.string().optional()}),FAE=Yo.object({description:Yo.string().optional(),name:Yo.string().optional(),casing:NAE.optional()}),N0_=Yo.record(FAE);var ctu=class extends lO{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=N0_.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 Lin=class extends lO{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var ltu=class extends lO{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ftu=class extends lO{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var dtu=class extends lO{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ptu=class extends lO{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var _tu=class extends lO{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var mQt=class extends f_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Nin(i),this.ir={auth:{docs:void 0,requirement:Hs.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Hs.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Lin({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Lin({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=Cjc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=f8a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let c of a.endpoints)r.has(c.id)&&u.push(c);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=R_(n?.join(".")),u=R_(r),c=this.context.namespace?`${R_(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,u=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(u),this.addTypesToIr({...n,[u]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:d7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>R_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var vA={};Na(vA,{AbstractConverters:()=>Ujc,ExampleConverter:()=>s6e,SchemaConverters:()=>Ljc,ServersConverter:()=>Oqe});var Ujc={};Na(Ujc,{AbstractMediaTypeObjectConverter:()=>btu,AbstractParameterConverter:()=>gtu});var s6e=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING=Hh.STRING;EXAMPLE_NUMBER=Hh.DOUBLE;EXAMPLE_BOOLEAN=Hh.BOOLEAN;EXAMPLE_INTEGER=Hh.INT;EXAMPLE_DATE=Hh.DATE;EXAMPLE_DATE_TIME=Hh.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.default;return typeof i=="number"?{isValid:!0,coerced:!1,validExample:i,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:i,maximum:n,exclusiveMinimum:a,exclusiveMaximum:u}=r,c;a!=null?typeof a=="boolean"?c=i!=null?i+Math.max(Number.EPSILON,Math.abs(i)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):i!=null&&(c=i);let d;return u!=null?typeof u=="boolean"?d=n!=null?n-Math.max(Number.EPSILON,Math.abs(n)*Number.EPSILON):void 0:d=u-Math.max(Number.EPSILON,Math.abs(u)*Number.EPSILON):n!=null&&(d=n),c!==void 0&&d!==void 0?(t<c||t>d)&&(t=c+(d-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):d!==void 0&&t>d&&(t=d-Math.abs(d*.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,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(c=>c?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(c=>c.validExample),errors:u?[]:a.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,l=!t.required?.includes(d);if(o&&l){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,l])=>l!==void 0))}}let c=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(l=>!s.has(l)).forEach(l=>{let g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:l,result:g})})}for(let{key:d,result:s}of c)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${c}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,c)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${c}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(c=>!c.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var Ljc={};Na(Ljc,{ArraySchemaConverter:()=>qQn,EnumSchemaConverter:()=>DQn,ObjectSchemaConverter:()=>EQn,OneOfSchemaConverter:()=>MQn,PrimitiveSchemaConverter:()=>AQn,SchemaConverter:()=>$Ri,SchemaOrReferenceConverter:()=>EK});function F0_(e){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ol.primitive({v1:"BASE_64",v2:Wd.base64({})});case"BOOLEAN":return ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:void 0})});case"DATE":return ol.primitive({v1:"DATE",v2:Wd.date({})});case"DATE_TIME":return ol.primitive({v1:"DATE_TIME",v2:Wd.dateTime({})});case"FLOAT":return ol.primitive({v1:"FLOAT",v2:Wd.float({})});case"DOUBLE":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:void 0,validation:void 0})});case"UINT":return ol.primitive({v1:"UINT",v2:Wd.uint({})});case"UINT_64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({})});case"INTEGER":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:void 0,validation:void 0})});case"LONG":return ol.primitive({v1:"LONG",v2:Wd.long({default:void 0})});case"STRING":return ol.primitive({v1:"STRING",v2:Wd.string({default:void 0,validation:void 0})});case"UUID":return ol.primitive({v1:"UUID",v2:Wd.uuid({})});case"BIG_INTEGER":return ol.primitive({v1:"BIG_INTEGER",v2:Wd.bigInteger({default:void 0})});default:return}},unknown:()=>ol.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ol.container(Ky.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ol.container(Ky.list(t))},optional:t=>{if(t!=null)return ol.container(Ky.optional(t))},nullable:t=>{if(t!=null)return ol.container(Ky.nullable(t))},set:t=>{if(t!=null)return ol.container(Ky.set(t))},literal:t=>ol.container(Ky.literal(t._visit({string:r=>KL.string(r),boolean:r=>KL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var DQn=class extends f_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],c=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:t0.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var htu=class extends f_{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()}));return{type:t0.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ol.container(Ky.map({keyType:f_.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function p8a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},c={},d=new Set;for(let[s,o]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let b=LAE(r,o,i)??i.convertBreadcrumbsToName(l),g="nullable"in o?o.nullable:!1,m=new EK({context:i,breadcrumbs:l,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])c[P]==null&&(c[P]=new Set),c[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:u,referencedTypes:d}}function LAE(e,t,r){return r.isReferenceObject(t)?void 0:new h$.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var EQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:t0.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=p8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[l,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",l.toString()],O;if(this.context.isReferenceObject(b)){let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(b)}`);continue}if(O=M,typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0),!d||Object.keys(O.properties??{}).every(E=>!this.schema.required?.includes(E))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:c});continue}}else O=b;typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0);let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:D,propertiesByAudience:A}=p8a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...A},D.forEach(M=>{c.add(M)})}for(let l of Object.keys(s))c.add(l);return{type:t0.object({properties:r,extends:u.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(yy),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var ytu=class extends lO{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var vtu;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let l=i(s.description);if(l)return l}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let l=a(s,o);if(l)return l}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let l=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!l.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),l=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):l.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let l=s.properties;if(!l)return;let b=Object.keys(l);if(b.length===0)return;let g=u(s,o);if(g.length>0){let P=c(g).slice(0,1).map(D=>d(D));if(P.length>0)return P.join("")}let O=c(b);if(O.length>0)return O.slice(0,1).map(P=>d(P)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let l=s.properties;if(!l)return[];let b=new Set(Object.keys(l)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(P=>{g.add(P)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function c(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],l=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),P=0;for(let D of o)m===D?P+=15:m.includes(D)&&(P+=10);for(let D of l)m===D?P+=8:m.includes(D)&&(P+=5);for(let D of b)m===D?P+=3:m.includes(D)&&(P+=2);return P+=Math.max(0,5-O.length),{prop:O,score:P}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=c;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(vtu||(vtu={}));var MQn=class extends f_{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new ytu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new EK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let b=o.convert();if(b?.type!=null&&l!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:JL.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=p8a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(l.ok){let g=this.context.typeReferenceToDeclaredTypeName(l.reference);g!=null&&c.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:t0.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let c=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=vtu.generateDisplayNameForInlinedObject({...u,typeName:d},n),l=new $Ri({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??u}).convert();if(l!=null){let b=l.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:ol.container(Ky.map({keyType:f_.STRING,valueType:ol.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new EK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:t0.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ol.container(Ky.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var AQn=class extends f_{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ol.container(Ky.literal(KL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ol.primitive({v1:vy.Date,v2:Wd.date({})});if(this.schema.format==="date-time")return ol.primitive({v1:vy.DateTime,v2:Wd.dateTime({})})}return ol.primitive({v1:"STRING",v2:Wd.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ol.primitive({v1:"DOUBLE",v2:Wd.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ol.primitive({v1:"FLOAT",v2:Wd.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ol.primitive({v1:"LONG",v2:Wd.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return ol.primitive({v1:"UINT",v2:Wd.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ol.primitive({v1:"UINT_64",v2:Wd.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ol.primitive({v1:"INTEGER",v2:Wd.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ol.container(Ky.literal(KL.boolean(t))):ol.primitive({v1:"BOOLEAN",v2:Wd.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var UAE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],$Ri=class e extends f_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new h$.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new DQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=Y2n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new AQn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new qQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new MQn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new htu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new EQn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:ol.unknown(),resolvedType:ol.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new h$.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=F0_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...UAE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var EK=class extends f_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new $Ri({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ol.container(Ky.optional(t))}wrapInNullable(t){return ol.container(Ky.nullable(t))}};var qQn=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var btu=class extends f_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new EK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=R_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let c=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var gtu=class extends f_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??f_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??f_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new s6e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var Otu=class extends lO{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var L0_="Base",Oqe=class e extends f_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(o=>o.id===c.id)===d),a=[i,...n],u=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:u[0]?.id,environments:lR.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(yy);return{value:{defaultEnvironment:t[0]?.id,environments:lR.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new Otu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,b]of Object.entries(r.variables??{}))l!==a&&(s[l]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(yy)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?L0_:e.getServerExtensionName({server:this.servers[0],context:this.context})??L0_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var _8a={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"},VAE=new Set(Object.values(_8a));var TQn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1924
1924
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Sb.Trace,...t)}debug(...t){this.write(Sb.Debug,...t)}info(...t){this.write(Sb.Info,...t)}warn(...t){this.write(Sb.Warn,...t)}error(...t){this.write(Sb.Error,...t)}log(t,...r){this.write(t,...r)}};var PQt={FILE:{NAME:1,PACKAGE:2,DEPENDENCY:3,MESSAGE_TYPE:4,ENUM_TYPE:5,SERVICE:6,EXTENSION:7,OPTIONS:8,SOURCE_CODE_INFO:9,PUBLIC_DEPENDENCY:10,WEAK_DEPENDENCY:11,SYNTAX:12},MESSAGE:{NAME:1,FIELD:2,NESTED_TYPE:3,ENUM_TYPE:4,EXTENSION_RANGE:5,EXTENSION:6,OPTIONS:7,ONEOF_DECL:8,RESERVED_RANGE:9,RESERVED_NAME:10},ENUM:{NAME:1,VALUE:2,OPTIONS:3,RESERVED_RANGE:4,RESERVED_NAME:5},SERVICE:{NAME:1,METHOD:2,OPTIONS:3},METHOD:{NAME:1,INPUT_TYPE:2,OUTPUT_TYPE:3,OPTIONS:4,CLIENT_STREAMING:5,SERVER_STREAMING:6}},mtu={MESSAGE:4,ENUM:5,SERVICE:6};var Ptu=class extends f_{enum;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,enum:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.enum=i,this.sourceCodeInfoPath=n}convert(){let t=this.enum.value.map((r,i)=>{let n=r.name;return{name:{name:this.context.casingsGenerator.generateName(n),wireValue:n},docs:this.context.getCommentForPath([...this.sourceCodeInfoPath,PQt.ENUM.VALUE,i]),availability:void 0}});return{type:t0.enum({default:void 0,values:t})}}};function U0_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var V0_=new Set([Gg.DOUBLE,Gg.FLOAT,Gg.INT64,Gg.UINT64,Gg.INT32,Gg.FIXED64,Gg.FIXED32,Gg.BOOL,Gg.STRING,Gg.BYTES,Gg.UINT32,Gg.SFIXED32,Gg.SFIXED64,Gg.SINT32,Gg.SINT64]);var jtu=class e extends f_{static LIST_UNKNOWN=ol.container(Ky.list(ol.unknown()));field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){if(this.field.label===3){let r=new GRi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:M2n.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:ol.container(Ky.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var wtu=class extends f_{field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){switch(this.field.type){case Gg.STRING:return ol.primitive({v1:vy.String,v2:Wd.string({default:void 0,validation:void 0})});case Gg.DOUBLE:return ol.primitive({v1:vy.Double,v2:Wd.double({default:void 0,validation:void 0})});case Gg.FLOAT:return ol.primitive({v1:vy.Float,v2:Wd.float({})});case Gg.INT32:return ol.primitive({v1:vy.Integer,v2:Wd.integer({default:void 0,validation:void 0})});case Gg.INT64:return ol.primitive({v1:vy.Long,v2:Wd.long({default:void 0})});case Gg.UINT32:return ol.primitive({v1:vy.Uint,v2:Wd.uint({default:void 0})});case Gg.UINT64:return ol.primitive({v1:vy.Uint64,v2:Wd.uint64({default:void 0})});case Gg.BOOL:return ol.primitive({v1:vy.Boolean,v2:Wd.boolean({default:void 0})});default:return ol.unknown()}}};var GRi=class extends f_{field;wrapAsOptional;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,wrapAsOptional:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.field=i,this.wrapAsOptional=n??!0,this.sourceCodeInfoPath=a}convert(){if(this.field.label===3){let i=new jtu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i.typeReference):i.typeReference,inlinedTypes:i.inlinedTypes}}if(V0_.has(this.field.type)){let i=new wtu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i):i,inlinedTypes:{}}}if((this.field.type===Gg.MESSAGE||this.field.type===Gg.ENUM)&&this.field.typeName!=null){let r=this.context.convertGrpcReferenceToTypeReference({typeName:this.field.typeName,displayNameOverride:this.field.name});if(r.ok)return{type:this.wrapAsOptional?this.wrapInOptional(r.reference):r.reference,inlinedTypes:{}}}}wrapInOptional(t){return ol.container(Ky.optional(t))}};function W0_({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},u=new Set,c={};for(let[d,s]of e.entries()){let l=new GRi({context:r,breadcrumbs:[...t,"fields",s.name],field:s,sourceCodeInfoPath:[...i,PQt.MESSAGE.FIELD,d]}).convert();if(l!=null){let b={name:r.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:l.type,docs:r.getCommentForPath([...i,PQt.MESSAGE.FIELD,d]),availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null){c[s.oneofIndex]==null&&(c[s.oneofIndex]=[]),c[s.oneofIndex].push(s);continue}n.push(b)}}return{convertedFields:n,referencedTypes:u,propertiesByAudience:a,oneOfFields:c}}var Stu=class extends f_{oneOfFields;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,oneOfFields:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.oneOfFields=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let r of this.oneOfFields){let n=new GRi({context:this.context,breadcrumbs:this.breadcrumbs,field:r,wrapAsOptional:!1,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();n!=null&&t.push({type:n.type,docs:void 0})}return{type:t0.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var Dtu=class extends f_{message;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,message:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.message=i,this.sourceCodeInfoPath=n}convert(){let t={},r=new Set,{convertedFields:i,referencedTypes:n,propertiesByAudience:a,oneOfFields:u}=W0_({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let c of n)r.add(c);for(let[c,d]of this.message.nestedType.entries()){let o=new QRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.NESTED_TYPE,c],schemaIndex:c}).convert();if(o!=null){for(let l of o.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([l,b])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.enumType.entries()){let o=new QRi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.ENUM_TYPE,c],schemaIndex:c}).convert();if(o!=null){for(let l of o.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([l,b])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.oneofDecl.entries()){let o=new Stu({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[c]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.MESSAGE.ONEOF_DECL,c]}).convert();if(o!=null){for(let g of o.referencedTypes)r.add(g);let l={typeDeclaration:this.createTypeDeclaration({shape:o.type,referencedTypes:o.referencedTypes,typeName:this.prependParentMessageName(U0_(d.name))}),audiences:[],propertiesByAudience:{}},b=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(l.typeDeclaration.name.typeId)});b.ok===!0&&(i.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:b.reference,docs:void 0,availability:void 0,propertyAccess:void 0,v2Examples:void 0}),t={...t,[l.typeDeclaration.name.typeId]:l})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:t0.object({properties:i,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath)}),audiences:[],propertiesByAudience:a},inlinedTypes:t}}createTypeDeclaration({shape:t,referencedTypes:r,typeName:i,docs:n}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:n,referencedTypes:r,source:void 0,inline:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}convertDeclaredTypeName(t){let r=this.context.maybePrependPackageName(t);return{typeId:r,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(r),displayName:t}}prependDelimitedParentMessageName(t,r="."){return`${this.message.name}${r}${t}`}prependParentMessageName(t){return`${this.message.name}${t}`}};var QRi=class extends f_{schema;audiences;sourceCodeInfoPath;schemaIndex;constructor({context:t,breadcrumbs:r,schema:i,sourceCodeInfoPath:n,schemaIndex:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.sourceCodeInfoPath=n,this.schemaIndex=a,this.audiences=[]}convert(){let t=this.tryConvertGrpcEnum();if(t!=null)return t;let r=this.tryConvertGrpcMessage();if(r!=null)return r}tryConvertGrpcEnum(){if(this.schema.$typeName==="google.protobuf.EnumDescriptorProto"){let r=new Ptu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],enum:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:new Set,docs:this.context.getCommentForPath(this.sourceCodeInfoPath)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new Dtu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],message:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:r.convertedSchema,inlinedTypes:r.inlinedTypes}}}createTypeDeclaration({shape:t,referencedTypes:r,docs:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:i,referencedTypes:r,source:void 0,inline:void 0,v2Examples:void 0}}convertDeclaredTypeName(){let t=this.context.maybePrependPackageName(this.schema.name);return{typeId:t,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.schema.name}}};var CQn=class extends I6{comments;codeGeneratorRequest;constructor({comments:t,codeGeneratorRequest:r,...i}){super(i),this.comments=t,this.codeGeneratorRequest=r}resolveTypeIdToProtoFile(t){if(t.startsWith(this.spec.package)){for(let r of this.spec.messageType)if(`${this.spec.package}.${r.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:r,protoFileName:this.spec.name}}for(let r of this.codeGeneratorRequest.protoFile.filter(i=>i.name!==this.spec.name))if(t.startsWith(r.package)){for(let i of r.messageType)if(`${r.package}.${i.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:i,protoFileName:r.name}}return{ok:!1}}getCodeGeneratorRequest(){return this.codeGeneratorRequest}maybePrependPackageName(t){return this.maybeRemoveLeadingPeriod(t).startsWith(this.spec.package)?t:this.spec.package+"."+t}convertReferenceToTypeReference({reference:t}){return{ok:!1}}convertGrpcReferenceToTypeReference({typeName:t,displayNameOverride:r}){return{ok:!0,reference:ol.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(this.maybeRemoveLeadingPeriod(t)),typeId:this.maybeRemoveLeadingPeriod(t),default:void 0,inline:!1,displayName:r})}}maybeRemoveLeadingPeriod(t){return t.startsWith(".")?t.slice(1):t}maybeRemoveGrpcPackagePrefix(t){let r=t.split(".").filter(n=>n!==""),i=this.spec.package.split(".").filter(n=>n!=="");for(;r.length>0&&i.length>0;){if(r[0]!==i[0])return t;r.shift(),i.shift()}return r.length===0?t:r.join(".")}updateTypeId(t,r){return{...t,typeDeclaration:{...t.typeDeclaration,name:{...t.typeDeclaration.name,typeId:r}}}}getCommentForPath(t){if(!t||t.length===0)return;let r=t[0];if(!(r in this.comments))return;let i=this.comments[r];for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0||!i)return;i=i[a]}return i?._comment}};function Vjc(){return{4:{},5:{},6:{}}}function H0_(e){let t=Vjc();return e.package?.startsWith("google.protobuf")||e.sourceCodeInfo?.location.forEach(r=>{let i=r.path;if(!i||i.length===0)return;let n=i[0];if(!(n in t))return;let a=r.leadingComments||r.trailingComments||"";if(!a)return;let u=t[n];for(let c=1;c<i.length;c++){let d=i[c];d!=null&&(d in u||(u[d]={}),u=u[d])}u._comment=a.trim()}),t}var h8a=class e extends f_{MAX_DEPTH=12;EXAMPLE_STRING="example";EXAMPLE_NUMBER=42;EXAMPLE_BOOL=!0;EXAMPLE_BYTES="bytes";message;type;depth;seenMessages;constructor({breadcrumbs:t,context:r,message:i,type:n,depth:a=0,seenMessages:u=new Set}){super({context:r,breadcrumbs:t}),this.message=i,this.type=n,this.depth=a,this.seenMessages=u}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:{},errors:[]};let t=this.getFullyQualifiedMessageName(this.message);if(this.seenMessages.has(t))return{isValid:!0,coerced:!1,validExample:{},errors:[]};let r=new Set(this.seenMessages);r.add(t);try{return this.convertMessage(r)}catch(i){return{isValid:!1,coerced:!1,validExample:{},errors:[`Failed to convert message ${t}: ${i}`]}}}getFullyQualifiedMessageName(t){let r=this.context.spec.package||"",i=t.name||"";return r?`${r}.${i}`:i}convertMessage(t){let r=new Map,i=new Map,n=new Map;this.message.oneofDecl&&this.message.oneofDecl.forEach((o,l)=>{o.name&&n.set(l,o.name)});for(let o of this.message.field)Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&(i.has(o.oneofIndex)||i.set(o.oneofIndex,o));for(let o of this.message.field){let l=o.name??"";if(!(!l||Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&i.get(o.oneofIndex)!==o))try{let g=this.convertField({field:o,seenMessages:t,fieldName:l});r.set(l,{field:o,result:g})}catch(g){r.set(l,{field:o,result:{isValid:!1,coerced:!1,validExample:null,errors:[`Error converting field ${l}: ${g}`]}})}}let a=Array.from(r.values()),u=a.every(({result:o})=>o.isValid),c=a.flatMap(({result:o})=>o.errors),d={},s=new Map;for(let[o,{field:l,result:b}]of r.entries()){if(!b.isValid||b.validExample===null||b.validExample===void 0)continue;if(Object.hasOwn(l,"oneofIndex")&&l.oneofIndex!=null&&n.has(l.oneofIndex)){let O=n.get(l.oneofIndex)??void 0;O!=null&&s.set(O,{fieldName:o,value:b.validExample})}else d[o]=b.validExample}for(let[o,{fieldName:l,value:b}]of s.entries())d[o]={[l]:b};return{isValid:u,coerced:!1,validExample:d,errors:c}}convertField({field:t,seenMessages:r,fieldName:i}){return t.label===M2n.REPEATED?this.convertRepeatedField({field:t,seenMessages:r,fieldName:i}):this.convertSingleField({field:t,seenMessages:r,fieldName:i})}convertRepeatedField({field:t,seenMessages:r,fieldName:i}){let n=this.convertSingleField({field:t,seenMessages:r,fieldName:i});return{isValid:n.isValid,coerced:!1,validExample:n.isValid?[n.validExample]:[],errors:n.errors}}convertSingleField({field:t,seenMessages:r,fieldName:i}){switch(t.type){case Gg.DOUBLE:case Gg.FLOAT:case Gg.INT64:case Gg.UINT64:case Gg.INT32:case Gg.FIXED64:case Gg.FIXED32:case Gg.UINT32:case Gg.SFIXED32:case Gg.SFIXED64:case Gg.SINT32:case Gg.SINT64:return this.convertNumber();case Gg.BOOL:return this.convertBoolean();case Gg.STRING:return this.convertString(this.EXAMPLE_STRING);case Gg.BYTES:return this.convertBytes();case Gg.ENUM:return this.convertEnum(t);case Gg.MESSAGE:return this.convertMessage_Field(t,r,i);default:return{isValid:!1,coerced:!1,validExample:null,errors:[`Unsupported field type: ${t.type}`]}}}convertNumber(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_NUMBER,errors:[]}}convertBoolean(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BOOL,errors:[]}}convertString(t){return{isValid:!0,coerced:!1,validExample:t,errors:[]}}convertBytes(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BYTES,errors:[]}}convertEnum(t){let r=t.typeName??"",i=this.context.maybeRemoveLeadingPeriod(r),n=this.findEnumType(i);return n?n.value.length===0?{isValid:!0,coerced:!1,validExample:0,errors:[]}:{isValid:!0,coerced:!1,validExample:n.value[0]?.number??0,errors:[]}:{isValid:!1,coerced:!1,validExample:0,errors:[`Enum type ${t.typeName} not found`]}}convertMessage_Field(t,r,i){let n=t.typeName;if(!n)return{isValid:!1,coerced:!1,validExample:null,errors:[`Missing type name for message field ${i}`]};let a=this.context.maybeRemoveLeadingPeriod(n),u,c;if(this.context.getCodeGeneratorRequest())for(let s of this.context.getCodeGeneratorRequest().protoFile){let o=this.context.resolveTypeIdToProtoFile(a);if(o.ok){u=o.message,o.protoFileName!==this.context.spec.name?c=new CQn({...this.context,comments:Vjc(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:s,logger:new TQn}):c=this.context;break}}return!u||!c?{isValid:!0,coerced:!1,validExample:null,errors:[`Could not find message type ${a}`]}:new e({context:c,breadcrumbs:[...this.breadcrumbs,i],message:u,type:this.type,depth:this.depth+1,seenMessages:r}).convert()}findEnumType(t){let r=this.findEnumInFile(t,this.context.spec);if(!r&&this.context.getCodeGeneratorRequest()){for(let i of this.context.getCodeGeneratorRequest().protoFile)if(r=this.findEnumInFile(t,i),r!=null)break}return r}findEnumInFile(t,r){let i=r.package||"";for(let n of r.enumType)if((i?`${i}.${n.name}`:n.name||"")===t||n.name===t)return n;for(let n of r.messageType){let a=this.findEnumInMessage(t,n,i);if(a!=null)return a}}findEnumInMessage(t,r,i){let n=i?`${i}.${r.name}`:r.name||"";for(let a of r.enumType)if(`${n}.${a.name}`===t||a.name===t)return a;for(let a of r.nestedType){let u=this.findEnumInMessage(t,a,n);if(u!=null)return u}}};var Etu=class extends f_{operation;serviceName;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,operation:i,serviceName:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.serviceName=n,this.sourceCodeInfoPath=a}convert(){let t=this.context.spec.package,r=this.convertRequestBody(),i=this.convertResponseBody();return{group:[t,this.serviceName],endpoint:{id:this.operation.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),name:this.context.casingsGenerator.generateName(this.context.maybePrependPackageName(this.operation.name)),requestBody:r?.requestBody,v2RequestBodies:void 0,response:i?.responseBody,v2Responses:void 0,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:eI.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:{}},path:{head:this.operation.name,parts:[]},pathParameters:[],queryParameters:[],headers:[],sdkRequest:void 0,errors:[],auth:!1,availability:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:!1,basePath:void 0,fullPath:{head:this.operation.name,parts:[]},allPathParameters:[],pagination:void 0,transport:void 0,source:eK.proto({methodType:this.getGrpcMethodType()}),audiences:[]}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?lGt.BidirectionalStream:this.operation.clientStreaming?lGt.ClientStream:this.operation.serverStreaming?lGt.ServerStream:lGt.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:XA.reference({contentType:"application/proto",docs:void 0,requestBodyType:t.reference,v2Examples:void 0}),requestExample:void 0}:{requestBody:void 0,requestExample:void 0}}convertResponseBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.outputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.outputType)});return t.ok?{responseBody:{body:j1.json(GL.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var Mtu=class extends f_{service;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,service:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.service=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let[r,i]of this.service.method.entries()){let a=new Etu({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,PQt.SERVICE.METHOD,r]}).convert();a!=null&&t.push(a)}return{endpoints:t,serviceName:this.context.maybePrependPackageName(this.service.name),serviceDisplayName:this.service.name,inlinedTypes:{}}}};function $0_(){return{displayName:void 0,request:{endpoint:{method:Xrr.Post,path:""},baseUrl:void 0,environment:void 0,auth:void 0,headers:void 0,docs:void 0,pathParameters:void 0,queryParameters:void 0,requestBody:void 0},response:{statusCode:200,body:Hs.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var Atu=class extends mQt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}convert(){return this.convertOptions(),this.convertEnumsAndMessages(),this.convertServices(),this.generateExamplesForServices(),this.finalizeIr()}convertOptions(){}convertEnumsAndMessages(){for(let[t,r]of this.context.spec.enumType.entries()){let n=new QRi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[mtu.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...G0_(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new QRi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[mtu.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...G0_(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new Mtu({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[mtu.SERVICE,t]}).convert();if(n!=null)for(let a of n.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:n.serviceName,endpointGroupDisplayName:n.serviceDisplayName})}}generateExamplesForServices(){for(let[t,r]of Object.entries(this.ir.services))for(let[i,n]of Object.entries(r.endpoints)){let a=$0_(),u=this.constructRequestBodyExample(n),c=this.constructResponseBodyExample(n);u!=null&&a.request!=null&&(a.request.requestBody=u),c!=null&&a.response!=null&&(a.response.body=V4.json(c)),n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{[i]:a}}}}constructRequestBodyExample(t){let r=t.requestBody.requestBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new h8a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"request"}).convert().validExample}constructResponseBodyExample(t){let r=(t.response?.body).value.responseBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new h8a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"response"}).convert().validExample}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...u].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${u.map(l=>R_(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let o=this.ir.services[c.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:a,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}finalizeIr(){return{...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0}}};function G0_(e,t){return Object.fromEntries(Object.entries(e).map(([r,i])=>[t(r),i]))}function Q0_({req:e,options:t}){let r,i=Aee({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let c=new Atu({context:new CQn({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new HRi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new TQn,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:H0_(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();c!=null&&(r=r===void 0?c:Fin(r,c,i))}let n=Up.IntermediateRepresentation.json(r,{allowUnrecognizedEnumValues:!0,skipValidation:!0});return n.ok?{name:"ir.json",content:JSON.stringify(n.value,null,2)}:{name:"ir.json",content:JSON.stringify(n.errors,null,2)}}function J0_(e){return{}}var Wjc=WAE({name:"protoc-gen-fern",version:`v${String(O0_)}`,run:Q0_});function WAE({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=J0_(i.parameter),a=r({req:i,options:n});return HAE([a],Rxd,Nxd)}}}function HAE(e,t,r){return EIa(qMo,{supportedFeatures:BC.parse(IIa.PROTO3_OPTIONAL|IIa.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var X0_=ui(require("net"),1),Z0_=ui(require("os"),1),qtu=class extends Error{constructor(t){super(`${t} is locked`)}},BQn={old:new Set,young:new Set},$AE=1e3*15;var y8a,GAE=()=>{let e=Z0_.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let i of r)t.add(i.address);return t},K0_=e=>new Promise((t,r)=>{let i=X0_.default.createServer();i.unref(),i.on("error",r),i.listen(e,()=>{let{port:n}=i.address();i.close(()=>{t(n)})})}),Y0_=async(e,t)=>{if(e.host||e.port===0)return K0_(e);for(let r of t)try{await K0_({port:e.port,host:r})}catch(i){if(!["EADDRNOTAVAIL","EINVAL"].includes(i.code))throw i}return e.port},QAE=function*(e){e&&(yield*e),yield 0};async function IQn(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let n=e.exclude;if(typeof n[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of n){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(n)}y8a===void 0&&(y8a=setTimeout(()=>{y8a=void 0,BQn.old=BQn.young,BQn.young=new Set},$AE),y8a.unref&&y8a.unref());let i=GAE();for(let n of QAE(t))try{if(r.has(n))continue;let a=await Y0_({...e,port:n},i);for(;BQn.old.has(a)||BQn.young.has(a);){if(n!==0)throw new qtu(n);a=await Y0_({...e,port:n},i)}return BQn.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof qtu))throw a}throw new Error("No available ports found")}var Uin=class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function k0_(){return JAE()?0:1}function JAE(){return KAE()&&!process.defaultApp}function KAE(){return!!process.versions.electron}function Hjc(e){return e.slice(k0_()+1)}function eg_(){return process.argv[k0_()]}var Ttu=require("assert");var rg_=require("util"),ig_=require("fs"),ng_=require("url");var jQt=require("path");var kAE={},YAE="require is not supported by ESM",tg_="loading a directory of commands is not supported yet for ESM",v8a;try{v8a=(0,ng_.fileURLToPath)(kAE.url)}catch{v8a=process.cwd()}var XAE=v8a.substring(0,v8a.lastIndexOf("node_modules")),ZAE={assert:{notStrictEqual:Ttu.notStrictEqual,strictEqual:Ttu.strictEqual},cliui:s2a,findUp:Dko,getEnv:e=>process.env[e],inspect:rg_.inspect,getCallerFile:()=>{throw new Uin(tg_)},getProcessArgvBin:eg_,mainFilename:XAE||process.cwd(),Parser:xGn,path:{basename:jQt.basename,dirname:jQt.dirname,extname:jQt.extname,relative:jQt.relative,resolve:jQt.resolve},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:ig_.readFileSync,require:()=>{throw new Uin(YAE)},requireDirectory:()=>{throw new Uin(tg_)},stringWidth:e=>[...e].length,y18n:Eko({directory:(0,jQt.resolve)(v8a,"../../../locales"),updateFiles:!1})};var Ng_=ui(Rg_(),1),{applyExtends:dqE,cjsPlatformShim:pqE,Parser:_qE,processArgv:hqE,Yargs:Htu}=Ng_.default;Htu.applyExtends=(e,t,r)=>dqE(e,t,r,pqE);Htu.hideBin=hqE.hideBin;Htu.Parser=_qE;var Fg_=Htu;var Lg_=require("fs/promises");var Ug_=require("path"),Vg_=ui(Gk(),1);async function Wg_({url:e,logger:t}){try{let r=await yqE({url:e,logger:t}),i=await Vg_.default.dir(),n=(0,Ug_.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,Lg_.writeFile)(n,r),{status:"success",filePath:n}}catch(r){return t.debug(`Encountered an error while loading OpenAPI spec: ${JSON.stringify(r)}`),{status:"failure",errorMessage:`Failed to load OpenAPI spec from ${e}`}}}async function yqE({url:e,logger:t}){let r=await o7.get(e),i=r.headers["content-type"]??"";return i.includes("json")||e.endsWith(".json")?typeof r.data=="string"?r.data:JSON.stringify(r.data,null,2):i.includes("yaml")||e.endsWith(".yml")||e.endsWith(".yaml")?typeof r.data=="string"?r.data:zBo(r.data):(t.warn(`Unrecognized Content-Type "${i}" from endpoint ${e}. Please ensure you're pointing to a URL that returns JSON or YAML and not HTML (e.g. Swagger UI webpage)`),zBo(r.data))}var w8a=ui(igi(),1);function dwc(e,t){if(e=w8a.default.parse(e),t=w8a.default.parse(t),!(w8a.default.compareBuild(e,t)>=0))return w8a.default.diff(e,t)||"build"}var vqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,bqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,gqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,OqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,mqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,PqE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function Zin(e){let t=e.match(mqE);if(t!=null){let[c,d,s,o,l]=t,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:b,minor:g,patch:O,index:m}}let r=e.match(PqE);if(r!=null){let[c,d,s,o,l]=r,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:b,minor:g,patch:O,index:m}}let i=e.match(vqE);if(i!=null){let[c,d,s,o,l]=i,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:b,minor:g,patch:O,commitIndex:m}}let n=e.match(gqE);if(n!=null){let[c,d,s,o,l]=n,b=OR(d),g=OR(s),O=OR(o),m=OR(l);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:b,minor:g,patch:O,releaseCandidateIndex:m}}let a=e.match(bqE);if(a!=null){let[c,d,s,o,l,b]=a,g=OR(d),O=OR(s),m=OR(o),P=OR(l),D=OR(b);if(g==null||O==null||m==null||P==null||D==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:g,minor:O,patch:m,releaseCandidateIndex:P,commitIndex:D}}let u=e.match(OqE);if(u!=null){let[c,d,s,o]=u,l=OR(d),b=OR(s),g=OR(o);if(l==null||b==null||g==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:l,minor:b,patch:g}}throw new Error("Failed to parse version: "+e)}function OR(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function Aue(e,t){if(e===t)return!1;let r=Zin(e),i=Zin(t);if(r.major!==i.major||r.minor!==i.minor||r.patch!==i.patch)return dwc(Hg_(r),Hg_(i))==null;if(r.type==="post-release-commit")return i.type!=="post-release-commit"||r.commitIndex>i.commitIndex;if(r.type==="release")return i.type!=="post-release-commit";if(r.type==="rc"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}return r.releaseCandidateIndex!==i.releaseCandidateIndex&&r.releaseCandidateIndex>i.releaseCandidateIndex}if(r.type==="post-rc-commit"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}if(i.type==="post-rc-commit")return r.releaseCandidateIndex!==i.releaseCandidateIndex?r.releaseCandidateIndex>i.releaseCandidateIndex:r.commitIndex>i.commitIndex}if(r.type==="beta"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1;case"alpha":return!0}return r.index>i.index}if(r.type==="alpha"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1}return r.index>i.index}return!Aue(t,e)}function Hg_(e){return`${e.major}.${e.minor}.${e.patch}`}var MK=e=>e.name==="up",wqe=e=>e.name==="down",$g_=e=>e.name==="space",UQn=e=>e.name==="backspace",XRi=e=>e.name==="tab",$tu=e=>"1234567890".includes(e.name),o2=e=>e.name==="enter"||e.name==="return";var Gtu=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},Qtu=class extends Error{name="CancelPromptError";message="Prompt was canceled"},S8a=class extends Error{name="ExitPromptError"},Jtu=class extends Error{name="HookError"},Gar=class extends Error{name="ValidationError"};var Kg_=require("async_hooks");var Ktu=require("async_hooks");var Gg_=new Ktu.AsyncLocalStorage;function jqE(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Qg_(e,t){let r=jqE(e);return Gg_.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function kin(){let e=Gg_.getStore();if(!e)throw new Jtu("[Inquirer] Hook functions can only be called from within a prompt");return e}function pwc(){return kin().rl}function _wc(e){let t=(...r)=>{let i=kin(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return Ktu.AsyncResource.bind(t)}function VQn(e){let t=kin(),{index:r}=t,i={get(){return t.hooks[r]},set(a){t.hooks[r]=a},initialized:r in t.hooks},n=e(i);return t.index++,n}function Jg_(){kin().handleChange()}var enn={queue(e){let t=kin(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(pwc());if(i!=null&&typeof i!="function")throw new Gar("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=kin();_wc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=kin();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function ng(e){return VQn(t=>{let r=Kg_.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),Jg_())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function Sqe(e,t){VQn(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&enn.queue(e),r.set(t)})}var p6e=ui(u5(),1);var Yg_={prefix:{idle:p6e.default.blue("?"),done:p6e.default.green(Q4.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>p6e.default.yellow(e))},style:{answer:p6e.default.cyan,message:p6e.default.bold,error:e=>p6e.default.red(`> ${e}`),defaultAnswer:e=>p6e.default.dim(`(${e})`),help:p6e.default.dim,highlight:p6e.default.cyan,key:e=>p6e.default.cyan(p6e.default.bold(`<${e}>`))}};function Xg_(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 Zg_(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=Xg_(a)&&Xg_(n)?Zg_(a,n):n}return t}function j3(...e){let t=[Yg_,...e.filter(r=>r!=null)];return Zg_(...t)}function R6({status:e="idle",theme:t}){let[r,i]=ng(!1),[n,a]=ng(0),{prefix:u,spinner:c}=j3(t);return Sqe(()=>{if(e==="loading"){let s,o=-1,l=setTimeout(()=>{i(!0),s=setInterval(()=>{o=o+1,a(o%c.frames.length)},c.interval)},300);return()=>{clearTimeout(l),clearInterval(s)}}else i(!1)},[e]),r?c.frames[n]:typeof u=="string"?u:u[e==="loading"?"idle":e]??u.idle}function que(e,t){return VQn(r=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,a)=>n!==t[a])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function _6e(e){return ng({current:e})[0]}function N6(e){let t=_6e(e);t.current=e,Sqe(r=>{let i=!1,n=_wc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var kg_=ui(alc(),1),eO_=ui(plc(),1);function D8a(e,t){return e.split(`
1925
1925
  `).flatMap(r=>(0,eO_.default)(r,t,{trim:!1,hard:!0}).split(`
1926
1926
  `).map(i=>i.trimEnd())).join(`
@@ -1962,7 +1962,7 @@ ${E}${A}${T}${gm_.default.cursorHide}`});function Sru({message:e,error:t,logger:
1962
1962
  Run ${Bs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1963
1963
  Run ${Bs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),WWn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function tSc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Vm_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of u)n+=`
1964
1964
  ${await KTE(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Bs.dim(c.currentVersion)+Bs.reset(" \u2192 ")+Bs.green(c.latestVersion);return n+=`
1965
- `,i?WWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function KTE(e){let r=await new Um_.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 YTE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let b=_Ii(o.name,l),g=await Qrr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=_Ii(s.name,o),b=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await bGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function $m_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Aue(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Aru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await YTE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...$m_(s,d,t.logger));else u.push(...$m_(c.versions,void 0,t.logger))}return u}var U8a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var KQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var rSc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Gm_=typeof globalThis.AbortController=="function",Qm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Jm_=typeof globalThis.ReadableStream=="function",Km_=typeof globalThis.FormData=="function",qru=["get","post","put","patch","head","delete"],XTE=()=>{};XTE();var Ym_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Tru=2147483647,Xm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Cru=Symbol("stop"),Zm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},km_={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 ZTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Xm_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},eP_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:c,value:d}=await a.read();if(c){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},tP_=(e,t,r)=>{let i=ZTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var YQn=e=>e!==null&&typeof e=="object";var V8a=(...e)=>{for(let t of e)if((!YQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return aSc({},...e)},iSc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Bru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:aSc(e[r]??[],t[r]??[])}var nSc=(e={},t={})=>({beforeRequest:Bru(e,t,"beforeRequest"),beforeRetry:Bru(e,t,"beforeRetry"),afterResponse:Bru(e,t,"afterResponse"),beforeError:Bru(e,t,"beforeError")}),aSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(YQn(n)){for(let[a,u]of Object.entries(n))YQn(u)&&a in t&&(u=aSc(t[a],u)),t={...t,[a]:u};YQn(n.hooks)&&(i=nSc(i,n.hooks),t.hooks=i),YQn(n.headers)&&(r=iSc(r,n.headers),t.headers=r)}return t};var iP_=e=>qru.includes(e)?e.toUpperCase():e,kTE=["get","put","head","delete","options","trace"],eCE=[408,413,429,500,502,503,504],tCE=[413,429,503],rP_={limit:2,methods:kTE,statusCodes:eCE,afterStatusCodes:tCE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP_=(e={})=>{if(typeof e=="number")return{...rP_,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{...rP_,...e}};async function oSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new KQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function uSc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var aP_=(e,t)=>{let r={};for(let i in t)!(i in km_)&&!(i in Zm_)&&!(i in e)&&(r[i]=t[i]);return r},oP_=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 W8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Tru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Tru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new U8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Jm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return eP_(c.clone(),i._options.onDownloadProgress)}return c},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[c,d]of Object.entries(Ym_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:iSc(this._input.headers,r.headers),hooks:nSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:iP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:nP_(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(Gm_&&Qm_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(rSc&&(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),oP_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Km_&&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(!rSc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=tP_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof KQn)throw t;if(t instanceof U8a){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Tru);if(this._retryCount<1)throw r;await uSc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Cru)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=aP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):oSc(r,t,this.abortController,this._options)}};var sSc=e=>{let t=(r,i)=>W8a.create(r,V8a(e,i));for(let r of qru)t[r]=(i,n)=>W8a.create(i,V8a(e,n,{method:r}));return t.create=r=>sSc(V8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),sSc(V8a(e,r))),t.stop=Cru,t},rCE=sSc(),uP_=rCE;var qP_=ui(AP_(),1);function pSc(e){let t=(0,qP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var wj_=ui(jj_(),1),Sj_=ui(igi(),1),DSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},ESc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function MSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??pSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,wj_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await uP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new DSc(e):l}if(t.allVersions)return s;let o=new ESc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Sj_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function K8a(e,t){let{version:r}=await MSc(e.toLowerCase(),t);return r}async function r3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:K8a(e.packageName,{version:t?"prerelease":"latest"})}var Dj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$ru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Mru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.71.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,Sru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IWn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Wm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1965
+ `,i?WWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function KTE(e){let r=await new Um_.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 YTE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let b=_Ii(o.name,l),g=await Qrr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=_Ii(s.name,o),b=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await bGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function $m_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Aue(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Aru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await YTE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...$m_(s,d,t.logger));else u.push(...$m_(c.versions,void 0,t.logger))}return u}var U8a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var KQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var rSc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Gm_=typeof globalThis.AbortController=="function",Qm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Jm_=typeof globalThis.ReadableStream=="function",Km_=typeof globalThis.FormData=="function",qru=["get","post","put","patch","head","delete"],XTE=()=>{};XTE();var Ym_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Tru=2147483647,Xm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Cru=Symbol("stop"),Zm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},km_={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 ZTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Xm_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},eP_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:c,value:d}=await a.read();if(c){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},tP_=(e,t,r)=>{let i=ZTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var YQn=e=>e!==null&&typeof e=="object";var V8a=(...e)=>{for(let t of e)if((!YQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return aSc({},...e)},iSc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Bru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:aSc(e[r]??[],t[r]??[])}var nSc=(e={},t={})=>({beforeRequest:Bru(e,t,"beforeRequest"),beforeRetry:Bru(e,t,"beforeRetry"),afterResponse:Bru(e,t,"afterResponse"),beforeError:Bru(e,t,"beforeError")}),aSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(YQn(n)){for(let[a,u]of Object.entries(n))YQn(u)&&a in t&&(u=aSc(t[a],u)),t={...t,[a]:u};YQn(n.hooks)&&(i=nSc(i,n.hooks),t.hooks=i),YQn(n.headers)&&(r=iSc(r,n.headers),t.headers=r)}return t};var iP_=e=>qru.includes(e)?e.toUpperCase():e,kTE=["get","put","head","delete","options","trace"],eCE=[408,413,429,500,502,503,504],tCE=[413,429,503],rP_={limit:2,methods:kTE,statusCodes:eCE,afterStatusCodes:tCE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP_=(e={})=>{if(typeof e=="number")return{...rP_,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{...rP_,...e}};async function oSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new KQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function uSc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var aP_=(e,t)=>{let r={};for(let i in t)!(i in km_)&&!(i in Zm_)&&!(i in e)&&(r[i]=t[i]);return r},oP_=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 W8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Tru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Tru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new U8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Jm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return eP_(c.clone(),i._options.onDownloadProgress)}return c},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[c,d]of Object.entries(Ym_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:iSc(this._input.headers,r.headers),hooks:nSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:iP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:nP_(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(Gm_&&Qm_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(rSc&&(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),oP_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Km_&&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(!rSc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=tP_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof KQn)throw t;if(t instanceof U8a){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Tru);if(this._retryCount<1)throw r;await uSc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Cru)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=aP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):oSc(r,t,this.abortController,this._options)}};var sSc=e=>{let t=(r,i)=>W8a.create(r,V8a(e,i));for(let r of qru)t[r]=(i,n)=>W8a.create(i,V8a(e,n,{method:r}));return t.create=r=>sSc(V8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),sSc(V8a(e,r))),t.stop=Cru,t},rCE=sSc(),uP_=rCE;var qP_=ui(AP_(),1);function pSc(e){let t=(0,qP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var wj_=ui(jj_(),1),Sj_=ui(igi(),1),DSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},ESc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function MSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??pSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,wj_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await uP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new DSc(e):l}if(t.allVersions)return s;let o=new ESc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Sj_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function K8a(e,t){let{version:r}=await MSc(e.toLowerCase(),t);return r}async function r3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:K8a(e.packageName,{version:t?"prerelease":"latest"})}var Dj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$ru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Mru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.71.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,Sru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await IWn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Wm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1966
1966
  `)||(r+=`
1967
1967
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=DHs(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new z8a(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new H8}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await IWn()).sendEvent(t)}logger=utr((t,...r)=>this.log(t,...r));stderr=utr((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Ej_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Ej_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Dj_[this.numTasks++%Dj_.length],u=Bs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===BI.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>DBi.indexOf(n.level)>=DBi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Sb.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await r3i({cliEnvironment:this.environment,includePreReleases:t}),i=Aue(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Aru({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await L1c({message:t,default:r})}async getInput(t){return await U1c({message:t.message,default:t.default})}};function Ej_(e){return`[${e}]:`}var DQt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var Eqe=class extends DQt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var jmi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1};function Y8a({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??jmi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??jmi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??jmi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??jmi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??jmi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??jmi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??jmi.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??jmi.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??jmi.respectForwardCompatibleEnums}}var TK={openapi:e=>({...e,type:"openapi",_visit:function(t){return TK._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return TK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var iJn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return iJn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var jU={basic:e=>({...e,type:"basic",_visit:function(t){return jU._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return jU._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return jU._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return jU._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return jU._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var Yg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Yg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Yg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Yg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Yg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Yg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Yg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Yg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Yg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var D_={int:e=>({value:e,type:"int",_visit:function(t){return D_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return D_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return D_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return D_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return D_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return D_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return D_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return D_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return D_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return D_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return D_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var i3i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return i3i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return i3i._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 n3i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return n3i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return n3i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var b$={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case b$.GenerallyAvailable:return t.generallyAvailable();case b$.Beta:return t.beta();case b$.Deprecated:return t.deprecated();default:return t._other()}}};var O6e={cursor:e=>({...e,type:"cursor",_visit:function(t){return O6e._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return O6e._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return O6e._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var wmi={language:e=>({...e,type:"language",_visit:function(t){return wmi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return wmi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var g$={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case g$.Curl:return t.curl();case g$.Python:return t.python();case g$.Javascript:return t.javascript();case g$.Typescript:return t.typescript();case g$.Go:return t.go();case g$.Ruby:return t.ruby();case g$.Csharp:return t.csharp();case g$.Java:return t.java();case g$.Js:return t.js();case g$.Node:return t.node();case g$.Ts:return t.ts();case g$.Nodets:return t.nodets();case g$.Golang:return t.golang();case g$.Dotnet:return t.dotnet();case g$.Jvm:return t.jvm();default:return t._other()}}};var EQt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return EQt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return EQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var MQt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return MQt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return MQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var O$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case O$.Get:return t.get();case O$.Post:return t.post();case O$.Put:return t.put();case O$.Patch:return t.patch();case O$.Delete:return t.delete();case O$.Head:return t.head();case O$.Options:return t.options();case O$.Trace:return t.trace();default:return t._other()}}};var Yar={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Yar._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Yar._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Yar._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Yar._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var Smi={file:e=>({...e,type:"file",_visit:function(t){return Smi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Smi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var CK={file:e=>({...e,type:"file",_visit:function(t){return CK._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return CK._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return CK._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return CK._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return CK._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return CK._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return CK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Ov={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ov._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ov._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ov._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ov._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ov._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ov._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ov._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ov._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ov._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ov._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ov._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var xw={int:e=>({...e,type:"int",_visit:function(t){return xw._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return xw._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return xw._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return xw._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return xw._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return xw._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return xw._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return xw._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return xw._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return xw._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return xw._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var _x={boolean:e=>({value:e,type:"boolean",_visit:function(t){return _x._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return _x._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Dmi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Dmi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Dmi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var Tee={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Tee._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Tee._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Tee._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Tee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var OB={file:e=>({...e,type:"file",_visit:function(t){return OB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return OB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return OB._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return OB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return OB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return OB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return OB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Nl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Nl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Nl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Nl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Nl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Nl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Nl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Nl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Nl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Nl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Nl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Nl._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Cee={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Cee._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Cee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var vp={int:e=>({...e,type:"int",_visit:function(t){return vp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return vp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return vp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return vp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return vp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return vp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return vp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return vp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return vp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return vp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return vp._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Av={};Na(Av,{AllOfPropertyConflict:()=>DJn,ArraySchema:()=>snu,ArraySchemaWithExample:()=>Fnu,Availability:()=>tiu,Base64WithExample:()=>Inu,BasicSecurityScheme:()=>niu,BearerSecurityScheme:()=>aiu,BooleanSchema:()=>rnu,BooleanWithExample:()=>znu,BytesResponse:()=>vJn,CasingOverrides:()=>siu,CommonProperty:()=>ynu,CommonPropertyWithExample:()=>Jnu,CursorPagination:()=>Fiu,CustomCodeSample:()=>Riu,CustomCodeSampleLanguage:()=>Iiu,CustomCodeSampleSdk:()=>xiu,CustomPagination:()=>Uiu,DateWithExample:()=>Bnu,DatetimeWithExample:()=>Cnu,DiscriminatedOneOfSchema:()=>_nu,DiscriminatedOneOfSchemaWithExample:()=>Gnu,DoubleSchema:()=>enu,DoubleWithExample:()=>qnu,Encoding:()=>eiu,Endpoint:()=>Viu,EndpointExample:()=>mJn,EndpointResponseExample:()=>Biu,EndpointSdkName:()=>kar,EndpointWithExample:()=>iw_,EnumSchema:()=>uJn,EnumSchemaWithExample:()=>Rnu,EnumValue:()=>u3i,ErrorExample:()=>Miu,FernExample:()=>qiu,FileResponse:()=>hJn,FileSchema:()=>Oiu,FloatWithExample:()=>Anu,FormUrlEncodedRequest:()=>Siu,FullEndpointExample:()=>Niu,FullExample:()=>LT,FullObjectExample:()=>hiu,FullOneOfExample:()=>viu,GlobalHeader:()=>nnu,Header:()=>c3i,HeaderExample:()=>OJn,HeaderSecurityScheme:()=>oiu,HeaderWithExample:()=>d3i,HttpEndpointServer:()=>bJn,HttpError:()=>Aiu,HttpErrorWithExample:()=>wnu,HttpMethod:()=>lJn,IdempotencyHeader:()=>anu,Int64WithExample:()=>Dnu,IntSchema:()=>Ziu,IntWithExample:()=>Snu,JsonRequest:()=>wiu,JsonRequestWithExample:()=>Onu,JsonResponse:()=>yJn,JsonResponseWithExample:()=>AJn,KeyValuePair:()=>yiu,LiteralExample:()=>_iu,LiteralSchema:()=>SJn,LiteralSchemaValue:()=>onu,LongSchema:()=>kiu,MapSchema:()=>cnu,MapSchemaWithExample:()=>Lnu,MultipartRequest:()=>_Jn,MultipartRequestProperty:()=>jiu,MultipartRequestPropertyEncoding:()=>Piu,MultipartSchema:()=>miu,NamedFullExample:()=>P6e,Namespace:()=>ciu,NamespaceId:()=>piu,NullableSchema:()=>fnu,NullableSchemaWithExample:()=>Vnu,OauthSecurityScheme:()=>fiu,ObjectProperty:()=>pnu,ObjectPropertyConflictInfo:()=>EJn,ObjectPropertyWithExample:()=>$nu,ObjectSchema:()=>unu,ObjectSchemaWithExample:()=>Wnu,OctetStreamRequest:()=>pJn,OffsetPagination:()=>Liu,OneOfSchema:()=>dnu,OneOfSchemaWithExample:()=>Hnu,OpenApiIntermediateRepresentation:()=>tw_,OpenApiSource:()=>Yru,OptionalSchema:()=>lnu,OptionalSchemaWithExample:()=>Unu,Pagination:()=>PJn,ParseFormUrlEncodedRequest:()=>mnu,ParseMultipartRequest:()=>gnu,ParseOctetStreamRequest:()=>bnu,PathParameter:()=>fJn,PathParameterExample:()=>Tiu,PathParameterWithExample:()=>vnu,PrimitiveExample:()=>cJn,PrimitiveSchema:()=>f3i,PrimitiveSchemaValue:()=>inu,PrimitiveSchemaValueWithExample:()=>xnu,PrimitiveSchemaWithExample:()=>qJn,PropertyKey:()=>sJn,ProtobufEncoding:()=>kru,ProtobufSource:()=>Xru,QueryParameter:()=>dJn,QueryParameterExample:()=>gJn,QueryParameterWithExample:()=>MJn,QuerySecurityScheme:()=>uiu,ReferencedSchema:()=>eor,Request:()=>Diu,RequestWithExample:()=>Pnu,Response:()=>Eiu,ResponseWithExample:()=>jnu,Schema:()=>tm,SchemaId:()=>Bee,SchemaWithExample:()=>xM,Schemas:()=>Xiu,SdkGroup:()=>liu,SdkGroupInfo:()=>biu,SdkGroupName:()=>s3i,SecurityScheme:()=>diu,SecuritySchemeId:()=>iiu,Server:()=>e5a,Source:()=>Zru,StatusCode:()=>Xar,StreamingResponseExample:()=>Ciu,StringSchema:()=>tnu,StringSchemaWithExample:()=>Tnu,SupportedSdkLanguage:()=>ziu,Tag:()=>riu,TagId:()=>Iee,Tags:()=>giu,TextResponse:()=>l3i,Uint64WithExample:()=>Mnu,UintWithExample:()=>Enu,UnDiscriminatedOneOfSchema:()=>hnu,UnDiscriminatedOneOfSchemaWithExample:()=>Qnu,UnknownSchemaWithExample:()=>Nnu,Webhook:()=>Wiu,WebhookExampleCall:()=>wJn,WebhookHttpMethod:()=>jJn,WebhookWithExample:()=>nw_,WebsocketChannel:()=>Yiu,WebsocketHandshake:()=>Hiu,WebsocketHandshakeWithExample:()=>rw_,WebsocketMessageExample:()=>Jiu,WebsocketMessageOrigin:()=>$iu,WebsocketMessageSchema:()=>Giu,WebsocketServer:()=>Qiu,WebsocketSessionExample:()=>Kiu,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Cue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>Zar,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um,commons:()=>BSc,example:()=>ISc,finalIr:()=>zSc,parseIr:()=>xSc});var BSc={};Na(BSc,{BasicSecurityScheme:()=>niu,BearerSecurityScheme:()=>aiu,Encoding:()=>eiu,HeaderSecurityScheme:()=>oiu,Namespace:()=>ciu,NamespaceId:()=>piu,OauthSecurityScheme:()=>fiu,OpenApiSource:()=>Yru,ProtobufEncoding:()=>kru,ProtobufSource:()=>Xru,QuerySecurityScheme:()=>uiu,SchemaId:()=>Bee,SdkGroup:()=>liu,SdkGroupName:()=>s3i,SecurityScheme:()=>diu,SecuritySchemeId:()=>iiu,Server:()=>e5a,Source:()=>Zru,StatusCode:()=>Xar,Tag:()=>riu,TagId:()=>Iee,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Cue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>Zar,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um});var gt={};Na(gt,{JsonError:()=>nJn,ParseError:()=>aJn,any:()=>Vj_,bigint:()=>Aj_,boolean:()=>Wj_,booleanLiteral:()=>Uj_,date:()=>qj_,discriminant:()=>Zj_,enum_:()=>Qru,getObjectLikeUtils:()=>AQt,getObjectUtils:()=>ynn,getSchemaUtils:()=>FT,isProperty:()=>o3i,lazy:()=>Tj_,lazyObject:()=>Nj_,list:()=>Kru,number:()=>Hj_,object:()=>Jru,objectWithoutOptionalProperties:()=>Rj_,optional:()=>ASc,property:()=>Bj_,record:()=>Jj_,set:()=>Kj_,string:()=>$j_,stringLiteral:()=>Lj_,transform:()=>qSc,undiscriminatedUnion:()=>Xj_,union:()=>ew_,unknown:()=>Gj_,withParsedProperties:()=>CSc});var fw={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function uq(e,t){return`Expected ${t}. Received ${sBE(e)}.`}function sBE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function wU(e){return{...e,json:Mj_(e.json),parse:Mj_(e.parse)}}function Mj_(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1968
1968
  `)),{ok:!0,value:t}):i}}function Gru(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var nJn=class e extends Error{errors;constructor(t){super(t.map(Gru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var aJn=class e extends Error{errors;constructor(t){super(t.map(Gru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function FT(e){return{optional:()=>ASc(e),transform:t=>qSc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new aJn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new nJn(i.errors)}}}function ASc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>fw.OPTIONAL};return{...t,...FT(t)}}function qSc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...FT(r)}}function Aj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:uq(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:uq(t,"bigint")}]},getType:()=>fw.BIGINT};return{...wU(e),...FT(e)}}var cBE=/^([+-]?\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 qj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:uq(t,"string")}]}:cBE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:uq(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:uq(t,"Date object")}]},getType:()=>fw.DATE};return{...wU(e),...FT(e)}}function BK(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...wU(r),...FT(r)}}}function Qru(e){let t=new Set(e);return BK(fw.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:uq(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:uq(i,"enum")}]}:{ok:!0,value:i})()}function Tj_(e){let t=TSc(e);return{...t,...FT(t)}}function TSc(e){return{parse:(t,r)=>oJn(e).parse(t,r),json:(t,r)=>oJn(e).json(t,r),getType:()=>oJn(e).getType()}}function oJn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function X8a(e){return Object.entries(e)}function Z8a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function a3i(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 k8a(e){return Object.keys(e)}function Cj_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function AQt(e){return{withParsedProperties:t=>CSc(e,t)}}function CSc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!a3i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uq(i,"object")}]};let a=new Set(Object.keys(t)),u=Z8a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...FT(r),...AQt(r)}}function Bj_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function o3i(e){return e.isProperty}function Jru(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>o3i(i)?i.rawKey:r),_getParsedProperties:()=>k8a(e),parse:(r,i)=>{let n={},a=[];for(let[u,c]of X8a(e)){let d=o3i(c)?c.rawKey:u,s=o3i(c)?c.valueSchema:c,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,xj_(s)&&a.push(d)}return Ij_({value:r,requiredKeys:a,getProperty:u=>{let c=n[u];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of X8a(e)){let c=o3i(u)?u.valueSchema:u;xj_(c)&&n.push(a)}return Ij_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return o3i(u)?{transformedKey:u.rawKey,transform:c=>u.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>u.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>fw.OBJECT};return{...wU(t),...FT(t),...AQt(t),...ynn(t)}}function Ij_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!a3i(e))return{ok:!1,errors:[{path:a,message:uq(e,"object")}]};let u=new Set(t),c=[],d={};for(let[s,o]of Object.entries(e)){let l=r(s);if(l!=null){u.delete(s);let b=l.transform(o);b.ok?d[l.transformedKey]=b.value:(d[s]=o,c.push(...b.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return c.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function ynn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>zj_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>zj_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>fw.OBJECT};return{...r,...FT(r),...AQt(r),...ynn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>fw.OBJECT};return{...t,...FT(t),...AQt(t),...ynn(t)}}}}function zj_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=Cj_(k8a(t),s=>n.has(s)),c=r(Z8a(t,u)),d=i(Z8a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function xj_(e){return!lBE(e)}function lBE(e){switch(e.getType()){case fw.ANY:case fw.UNKNOWN:case fw.OPTIONAL:return!0;default:return!1}}function Rj_(e){return Jru(e)}function Nj_(e){let t={...TSc(e),_getRawProperties:()=>oJn(e)._getRawProperties(),_getParsedProperties:()=>oJn(e)._getParsedProperties()};return{...t,...FT(t),...AQt(t),...ynn(t)}}function Kru(e){let t={parse:(r,i)=>Fj_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>Fj_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>fw.LIST};return{...wU(t),...FT(t)}}function Fj_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:uq(e,"list"),path:[]}]}}function Lj_(e){return BK(fw.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uq(r,`"${e}"`)}]})()}function Uj_(e){return BK(fw.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uq(r,`${e.toString()}`)}]})()}var Vj_=BK(fw.ANY,e=>({ok:!0,value:e}));var Wj_=BK(fw.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"boolean")}]});var Hj_=BK(fw.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"number")}]});var $j_=BK(fw.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uq(e,"string")}]});var Gj_=BK(fw.UNKNOWN,e=>({ok:!0,value:e}));function Jj_(e,t){let r={parse:(i,n)=>Qj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Qj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>fw.RECORD};return{...wU(r),...FT(r)}}function Qj_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return a3i(e)?X8a(e).reduce((a,[u,c])=>{if(c==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),l=i(c,s);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),l.ok||b.push(...l.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:uq(e,"object")}]}}function Kj_(e){let t=Kru(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uq(i,"Set")}]},getType:()=>fw.SET};return{...wU(r),...FT(r)}}function Xj_(e){let t={parse:(r,i)=>Yj_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>Yj_((n,a)=>n.json(r,a),e,i),getType:()=>fw.UNDISCRIMINATED_UNION};return{...wU(t),...FT(t)}}function Yj_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let c of u.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function Zj_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function ew_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Qru(k8a(t)),a={parse:(u,c)=>kj_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(u,c)=>kj_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>fw.UNION};return{...wU(a),...FT(a),...AQt(a)}}function kj_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:c=[]}){if(!a3i(e))return{ok:!1,errors:[{path:c,message:uq(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=n(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let b=u(s,l);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var Um=gt.objectWithoutOptionalProperties({title:gt.string().optional()});var Yru=gt.objectWithoutOptionalProperties({file:gt.string()});var Xru=gt.objectWithoutOptionalProperties({file:gt.string()});var Zru=gt.union("type",{openapi:Yru,protobuf:Xru}).transform({transform:e=>{switch(e.type){case"openapi":return TK.openapi(e);case"protobuf":return TK.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ch=gt.objectWithoutOptionalProperties({source:Zru.optional()});var kru=gt.objectWithoutOptionalProperties({typeName:gt.string()});var eiu=gt.union("type",{protobuf:kru}).transform({transform:e=>{switch(e.type){case"protobuf":return iJn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Cue=gt.objectWithoutOptionalProperties({encoding:eiu.optional()});var Of=gt.objectWithoutOptionalProperties({description:gt.string().optional()});var tiu=gt.enum_(["GenerallyAvailable","Beta","Deprecated"]);var oy=gt.objectWithoutOptionalProperties({availability:tiu.optional()});var Xar=gt.number();var m6e=gt.objectWithoutOptionalProperties({statusCode:Xar.optional()});var pg=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string()});var zM=gt.objectWithoutOptionalProperties({inline:gt.boolean().optional()});var Bee=gt.string();var Iee=gt.string();var riu=gt.objectWithoutOptionalProperties({id:Iee}).extend(Of);var iiu=gt.string();var niu=gt.objectWithoutOptionalProperties({usernameVariableName:gt.string().optional(),usernameEnvVar:gt.string().optional(),passwordVariableName:gt.string().optional(),passwordEnvVar:gt.string().optional()});var aiu=gt.objectWithoutOptionalProperties({tokenVariableName:gt.string().optional(),tokenEnvVar:gt.string().optional()});var oiu=gt.objectWithoutOptionalProperties({headerName:gt.string(),prefix:gt.string().optional(),headerVariableName:gt.string().optional(),headerEnvVar:gt.string().optional()});var uiu=gt.objectWithoutOptionalProperties({queryParameterName:gt.string()});var siu=gt.objectWithoutOptionalProperties({snake:gt.string().optional(),camel:gt.string().optional(),screamingSnake:gt.string().optional(),pascal:gt.string().optional()});var u3i=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string(),value:gt.string(),casing:siu.optional()}).extend(Of).extend(oy);var ciu=gt.objectWithoutOptionalProperties({type:gt.stringLiteral("namespace"),name:gt.string()});var liu=gt.undiscriminatedUnion([gt.string(),ciu]);var s3i=gt.list(liu);var Vm=gt.objectWithoutOptionalProperties({groupName:s3i.optional()});var x0=gt.objectWithoutOptionalProperties({namespace:gt.string().optional()});var uJn=gt.objectWithoutOptionalProperties({default:u3i.optional(),values:gt.list(u3i)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var fiu=gt.objectWithoutOptionalProperties({scopesEnum:uJn.optional()});var diu=gt.union("type",{basic:niu,bearer:aiu,header:oiu,query:uiu,oauth:fiu}).transform({transform:e=>{switch(e.type){case"basic":return jU.basic(e);case"bearer":return jU.bearer(e);case"header":return jU.header(e);case"query":return jU.query(e);case"oauth":return jU.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var e5a=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string(),audiences:gt.list(gt.string()).optional()}).extend(Of);var piu=gt.string();var Zar=gt.objectWithoutOptionalProperties({sdkMethodName:gt.string().optional()});var ISc={};Na(ISc,{FullExample:()=>LT,FullObjectExample:()=>hiu,FullOneOfExample:()=>viu,KeyValuePair:()=>yiu,LiteralExample:()=>_iu,PrimitiveExample:()=>cJn,PropertyKey:()=>sJn});var sJn=gt.string();var cJn=gt.union("type",{int:gt.object({value:gt.number()}),int64:gt.object({value:gt.number()}),uint:gt.object({value:gt.number()}),uint64:gt.object({value:gt.number()}),float:gt.object({value:gt.number()}),double:gt.object({value:gt.number()}),string:gt.object({value:gt.string()}),datetime:gt.object({value:gt.string()}),date:gt.object({value:gt.string()}),base64:gt.object({value:gt.string()}),boolean:gt.object({value:gt.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return D_.int(e.value);case"int64":return D_.int64(e.value);case"uint":return D_.uint(e.value);case"uint64":return D_.uint64(e.value);case"float":return D_.float(e.value);case"double":return D_.double(e.value);case"string":return D_.string(e.value);case"datetime":return D_.datetime(e.value);case"date":return D_.date(e.value);case"base64":return D_.base64(e.value);case"boolean":return D_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var _iu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return i3i.boolean(e.value);case"string":return i3i.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var LT=gt.union("type",{primitive:gt.object({value:cJn}),object:gt.lazyObject(()=>hiu),array:gt.object({value:gt.list(gt.lazy(()=>LT))}),map:gt.object({value:gt.list(gt.lazyObject(()=>yiu))}),enum:gt.object({value:gt.string()}),literal:gt.object({value:_iu}),oneOf:gt.object({value:gt.lazy(()=>viu)}),unknown:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"primitive":return Yg.primitive(e.value);case"object":return Yg.object(e);case"array":return Yg.array(e.value);case"map":return Yg.map(e.value);case"enum":return Yg.enum(e.value);case"literal":return Yg.literal(e.value);case"oneOf":return Yg.oneOf(e.value);case"unknown":return Yg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var hiu=gt.objectWithoutOptionalProperties({properties:gt.record(sJn,gt.lazy(()=>LT))});var yiu=gt.objectWithoutOptionalProperties({key:cJn,value:gt.lazy(()=>LT)});var viu=gt.union("type",{discriminated:gt.object({value:gt.record(sJn,gt.lazy(()=>LT))}),undiscriminated:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"discriminated":return n3i.discriminated(e.value);case"undiscriminated":return n3i.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var zSc={};Na(zSc,{AllOfPropertyConflict:()=>DJn,ArraySchema:()=>snu,Availability:()=>tiu,BooleanSchema:()=>rnu,BytesResponse:()=>vJn,CasingOverrides:()=>siu,CommonProperty:()=>ynu,CursorPagination:()=>Fiu,CustomCodeSample:()=>Riu,CustomCodeSampleLanguage:()=>Iiu,CustomCodeSampleSdk:()=>xiu,CustomPagination:()=>Uiu,DiscriminatedOneOfSchema:()=>_nu,DoubleSchema:()=>enu,Endpoint:()=>Viu,EndpointExample:()=>mJn,EndpointResponseExample:()=>Biu,EndpointSdkName:()=>kar,EnumSchema:()=>uJn,EnumValue:()=>u3i,ErrorExample:()=>Miu,FernExample:()=>qiu,FileResponse:()=>hJn,FileSchema:()=>Oiu,FormUrlEncodedRequest:()=>Siu,FullEndpointExample:()=>Niu,GlobalHeader:()=>nnu,Header:()=>c3i,HeaderExample:()=>OJn,HttpEndpointServer:()=>bJn,HttpError:()=>Aiu,HttpMethod:()=>lJn,IdempotencyHeader:()=>anu,IntSchema:()=>Ziu,JsonRequest:()=>wiu,JsonResponse:()=>yJn,LiteralSchema:()=>SJn,LiteralSchemaValue:()=>onu,LongSchema:()=>kiu,MapSchema:()=>cnu,MultipartRequest:()=>_Jn,MultipartRequestProperty:()=>jiu,MultipartRequestPropertyEncoding:()=>Piu,MultipartSchema:()=>miu,NullableSchema:()=>fnu,ObjectProperty:()=>pnu,ObjectPropertyConflictInfo:()=>EJn,ObjectSchema:()=>unu,OctetStreamRequest:()=>pJn,OffsetPagination:()=>Liu,OneOfSchema:()=>dnu,OpenApiIntermediateRepresentation:()=>tw_,OptionalSchema:()=>lnu,Pagination:()=>PJn,PathParameter:()=>fJn,PathParameterExample:()=>Tiu,PrimitiveSchema:()=>f3i,PrimitiveSchemaValue:()=>inu,QueryParameter:()=>dJn,QueryParameterExample:()=>gJn,ReferencedSchema:()=>eor,Request:()=>Diu,Response:()=>Eiu,Schema:()=>tm,Schemas:()=>Xiu,SdkGroupInfo:()=>biu,StreamingResponseExample:()=>Ciu,StringSchema:()=>tnu,SupportedSdkLanguage:()=>ziu,Tags:()=>giu,TextResponse:()=>l3i,UnDiscriminatedOneOfSchema:()=>hnu,Webhook:()=>Wiu,WebhookExampleCall:()=>wJn,WebhookHttpMethod:()=>jJn,WebsocketChannel:()=>Yiu,WebsocketHandshake:()=>Hiu,WebsocketMessageExample:()=>Jiu,WebsocketMessageOrigin:()=>$iu,WebsocketMessageSchema:()=>Giu,WebsocketServer:()=>Qiu,WebsocketSessionExample:()=>Kiu});var biu=gt.objectWithoutOptionalProperties({summary:gt.string().optional(),description:gt.string().optional()});var giu=gt.objectWithoutOptionalProperties({tagsById:gt.record(Iee,riu),orderedTagIds:gt.list(Iee).optional()});var lJn=gt.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var fJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var dJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var c3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var kar=gt.objectWithoutOptionalProperties({groupName:s3i,methodName:gt.string()});var pJn=gt.objectWithoutOptionalProperties({contentType:gt.string().optional()}).extend(Of).extend(Ch);var Oiu=gt.objectWithoutOptionalProperties({isOptional:gt.boolean(),isArray:gt.boolean()}).extend(Of);var miu=gt.union("type",{file:Oiu,json:gt.object({value:gt.lazy(()=>tm)})}).transform({transform:e=>{switch(e.type){case"file":return Smi.file(e);case"json":return Smi.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Piu=gt.enum_(["json","form"]);var jiu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:miu,contentType:gt.string().optional(),exploded:gt.boolean().optional(),encoding:Piu.optional()}).extend(Of);var _Jn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),properties:gt.list(jiu)}).extend(Of).extend(Ch);var wiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var Siu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var Diu=gt.union("type",{octetStream:pJn,multipart:_Jn,json:wiu,formUrlEncoded:Siu}).transform({transform:e=>{switch(e.type){case"octetStream":return Yar.octetStream(e);case"multipart":return Yar.multipart(e);case"json":return Yar.json(e);case"formUrlEncoded":return Yar.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var hJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var yJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),responseProperty:gt.string().optional()}).extend(Of).extend(Ch).extend(m6e);var l3i=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var vJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var Eiu=gt.union("type",{file:hJn,json:yJn,text:l3i,bytes:vJn,streamingSse:yJn,streamingText:l3i,streamingJson:yJn}).transform({transform:e=>{switch(e.type){case"file":return CK.file(e);case"json":return CK.json(e);case"text":return CK.text(e);case"bytes":return CK.bytes(e);case"streamingSse":return CK.streamingSse(e);case"streamingText":return CK.streamingText(e);case"streamingJson":return CK.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Miu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),description:gt.string().optional(),example:gt.lazy(()=>LT)});var Aiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm).optional(),examples:gt.list(Miu).optional()}).extend(Of).extend(pg).extend(Ch);var bJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string().optional(),audiences:gt.list(gt.string()).optional()});var qiu=gt.unknown();var Tiu=gt.objectWithoutOptionalProperties({name:gt.string(),parameterNameOverride:gt.string().optional(),value:gt.lazy(()=>LT)});var gJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>LT)});var OJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>LT)});var Ciu=gt.objectWithoutOptionalProperties({sse:gt.boolean(),events:gt.list(gt.lazy(()=>LT))});var Biu=gt.union("type",{withStreaming:Ciu,withoutStreaming:gt.object({value:gt.lazy(()=>LT)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return MQt.withStreaming(e);case"withoutStreaming":return MQt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Iiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),language:gt.string(),code:gt.string(),install:gt.string().optional()}).extend(Of);var ziu=gt.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var xiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),sdk:ziu,code:gt.string()}).extend(Of);var Riu=gt.union("type",{language:Iiu,sdk:xiu}).transform({transform:e=>{switch(e.type){case"language":return wmi.language(e);case"sdk":return wmi.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Niu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),pathParameters:gt.list(Tiu).optional(),queryParameters:gt.list(gJn).optional(),headers:gt.list(OJn).optional(),request:gt.lazy(()=>LT).optional(),response:Biu.optional(),codeSamples:gt.list(Riu)}).extend(Of);var mJn=gt.union("type",{unknown:gt.object({value:qiu}),full:Niu}).transform({transform:e=>{switch(e.type){case"unknown":return EQt.unknown(e.value);case"full":return EQt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fiu=gt.objectWithoutOptionalProperties({cursor:gt.string(),nextCursor:gt.property("next_cursor",gt.string()),results:gt.string()});var Liu=gt.objectWithoutOptionalProperties({offset:gt.string(),results:gt.string(),step:gt.string().optional(),hasNextPage:gt.string().optional()});var Uiu=gt.objectWithoutOptionalProperties({results:gt.string()});var PJn=gt.union("type",{cursor:Fiu,offset:Liu,custom:Uiu}).transform({transform:e=>{switch(e.type){case"cursor":return O6e.cursor(e);case"offset":return O6e.offset(e);case"custom":return O6e.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var Viu=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:lJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Iee),pathParameters:gt.list(fJn),queryParameters:gt.list(dJn),headers:gt.list(c3i),sdkName:kar.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Diu.optional(),response:Eiu.optional(),errors:gt.record(Xar,Aiu),servers:gt.list(bJn),examples:gt.list(mJn),pagination:PJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var jJn=gt.enum_(["GET","POST"]);var wJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),payload:gt.lazy(()=>LT)}).extend(Of);var Wiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:kar.optional(),method:jJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Iee),headers:gt.list(c3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>tm),examples:gt.list(wJn)}).extend(Of).extend(Ch).extend(x0);var Hiu=gt.objectWithoutOptionalProperties({queryParameters:gt.list(dJn),headers:gt.list(c3i),pathParameters:gt.list(fJn)});var $iu=gt.enum_(["client","server"]);var Giu=gt.objectWithoutOptionalProperties({name:gt.string(),origin:$iu,body:gt.lazy(()=>tm)});var Qiu=gt.objectWithoutOptionalProperties({name:gt.string(),url:gt.string()});var Jiu=gt.objectWithoutOptionalProperties({messageType:gt.string(),payload:gt.lazy(()=>LT)}).extend(Of);var Kiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),queryParameters:gt.list(gJn).optional(),headers:gt.list(OJn).optional(),messages:gt.list(Jiu)}).extend(Of);var Yiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),path:gt.string(),groupName:s3i,summary:gt.string().optional(),handshake:Hiu,messages:gt.list(Giu),servers:gt.list(Qiu),examples:gt.list(Kiu)}).extend(Of).extend(Ch);var Xiu=gt.objectWithoutOptionalProperties({rootSchemas:gt.record(Bee,gt.lazy(()=>tm)),namespacedSchemas:gt.record(piu,gt.record(Bee,gt.lazy(()=>tm)))});var Ziu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var kiu=gt.objectWithoutOptionalProperties({default:gt.number().optional()});var enu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var tnu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional()});var rnu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional()});var inu=gt.union("type",{int:Ziu,int64:kiu,uint:gt.object({}),uint64:gt.object({}),float:gt.object({}),double:enu,string:tnu,datetime:gt.object({}),date:gt.object({}),base64:gt.object({}),boolean:rnu}).transform({transform:e=>{switch(e.type){case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();case"float":return xw.float();case"double":return xw.double(e);case"string":return xw.string(e);case"datetime":return xw.datetime();case"date":return xw.date();case"base64":return xw.base64();case"boolean":return xw.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var f3i=gt.objectWithoutOptionalProperties({schema:inu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var nnu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),optional:gt.boolean().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var anu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var tw_=gt.objectWithoutOptionalProperties({apiVersion:gt.unknown().optional(),title:gt.string().optional(),description:gt.string().optional(),basePath:gt.string().optional(),servers:gt.list(e5a),websocketServers:gt.list(e5a),groups:gt.record(gt.string(),biu),tags:giu,hasEndpointsMarkedInternal:gt.boolean(),endpoints:gt.list(Viu),webhooks:gt.list(Wiu),channels:gt.record(gt.string(),Yiu),groupedSchemas:Xiu,variables:gt.record(gt.string(),f3i),nonRequestReferencedSchemas:gt.set(Bee),securitySchemes:gt.record(iiu,diu),globalHeaders:gt.list(nnu).optional(),idempotencyHeaders:gt.list(anu).optional()});var eor=gt.objectWithoutOptionalProperties({schema:Bee}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um);var onu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return _x.boolean(e.value);case"string":return _x.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var SJn=gt.objectWithoutOptionalProperties({value:onu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var tm=gt.union("type",{primitive:f3i,object:gt.lazyObject(()=>unu),array:gt.lazyObject(()=>snu),map:gt.lazyObject(()=>cnu),optional:gt.lazyObject(()=>lnu),enum:uJn,reference:eor,literal:SJn,oneOf:gt.object({value:gt.lazy(()=>dnu)}),nullable:gt.lazyObject(()=>fnu),unknown:pg}).transform({transform:e=>{switch(e.type){case"primitive":return Ov.primitive(e);case"object":return Ov.object(e);case"array":return Ov.array(e);case"map":return Ov.map(e);case"optional":return Ov.optional(e);case"enum":return Ov.enum(e);case"reference":return Ov.reference(e);case"literal":return Ov.literal(e);case"oneOf":return Ov.oneOf(e.value);case"nullable":return Ov.nullable(e);case"unknown":return Ov.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var DJn=gt.objectWithoutOptionalProperties({propertyKey:gt.string(),allOfSchemaIds:gt.list(Bee),conflictingTypeSignatures:gt.boolean()});var unu=gt.objectWithoutOptionalProperties({allOf:gt.list(eor),properties:gt.list(gt.lazyObject(()=>pnu)),allOfPropertyConflicts:gt.list(DJn),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var EJn=gt.objectWithoutOptionalProperties({differentSchema:gt.boolean()});var pnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),conflict:gt.record(Bee,EJn),generatedName:gt.string(),nameOverride:gt.string().optional(),audiences:gt.list(gt.string())}).extend(oy);var snu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var cnu=gt.objectWithoutOptionalProperties({key:f3i,value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Um).extend(zM);var lnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var fnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var dnu=gt.union("type",{discriminated:gt.lazyObject(()=>_nu),undiscriminated:gt.lazyObject(()=>hnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Dmi.discriminated(e);case"undiscriminated":return Dmi.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var _nu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>ynu)),schemas:gt.record(gt.string(),gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Ch).extend(Um).extend(zM);var ynu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm)});var hnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Ch).extend(Um).extend(zM);var xSc={};Na(xSc,{ArraySchemaWithExample:()=>Fnu,Base64WithExample:()=>Inu,BooleanWithExample:()=>znu,CommonPropertyWithExample:()=>Jnu,DateWithExample:()=>Bnu,DatetimeWithExample:()=>Cnu,DiscriminatedOneOfSchemaWithExample:()=>Gnu,DoubleWithExample:()=>qnu,EndpointWithExample:()=>iw_,EnumSchemaWithExample:()=>Rnu,FloatWithExample:()=>Anu,HeaderWithExample:()=>d3i,HttpErrorWithExample:()=>wnu,Int64WithExample:()=>Dnu,IntWithExample:()=>Snu,JsonRequestWithExample:()=>Onu,JsonResponseWithExample:()=>AJn,MapSchemaWithExample:()=>Lnu,NamedFullExample:()=>P6e,NullableSchemaWithExample:()=>Vnu,ObjectPropertyWithExample:()=>$nu,ObjectSchemaWithExample:()=>Wnu,OneOfSchemaWithExample:()=>Hnu,OptionalSchemaWithExample:()=>Unu,ParseFormUrlEncodedRequest:()=>mnu,ParseMultipartRequest:()=>gnu,ParseOctetStreamRequest:()=>bnu,PathParameterWithExample:()=>vnu,PrimitiveSchemaValueWithExample:()=>xnu,PrimitiveSchemaWithExample:()=>qJn,QueryParameterWithExample:()=>MJn,RequestWithExample:()=>Pnu,ResponseWithExample:()=>jnu,SchemaWithExample:()=>xM,StringSchemaWithExample:()=>Tnu,Uint64WithExample:()=>Mnu,UintWithExample:()=>Enu,UnDiscriminatedOneOfSchemaWithExample:()=>Qnu,UnknownSchemaWithExample:()=>Nnu,WebhookWithExample:()=>nw_,WebsocketHandshakeWithExample:()=>rw_});var P6e=gt.objectWithoutOptionalProperties({name:gt.string().optional(),value:gt.unknown()}).extend(Of);var MJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var d3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var rw_=gt.objectWithoutOptionalProperties({queryParameters:gt.list(MJn),headers:gt.list(d3i)});var vnu=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var bnu=gt.objectWithoutOptionalProperties({}).extend(pJn).extend(Zar);var gnu=gt.objectWithoutOptionalProperties({}).extend(_Jn).extend(Zar);var Onu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(Zar);var mnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(Zar);var Pnu=gt.union("type",{octetStream:bnu,multipart:gnu,json:Onu,formUrlEncoded:mnu}).transform({transform:e=>{switch(e.type){case"octetStream":return Tee.octetStream(e);case"multipart":return Tee.multipart(e);case"json":return Tee.json(e);case"formUrlEncoded":return Tee.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var AJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),responseProperty:gt.string().optional(),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(Ch).extend(m6e);var jnu=gt.union("type",{file:hJn,json:AJn,text:l3i,bytes:vJn,streamingSse:AJn,streamingText:l3i,streamingJson:AJn}).transform({transform:e=>{switch(e.type){case"file":return OB.file(e);case"json":return OB.json(e);case"text":return OB.text(e);case"bytes":return OB.bytes(e);case"streamingSse":return OB.streamingSse(e);case"streamingText":return OB.streamingText(e);case"streamingJson":return OB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var wnu=gt.objectWithoutOptionalProperties({statusCode:Xar,schema:gt.lazy(()=>xM),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(pg).extend(Ch);var iw_=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:lJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Iee),pathParameters:gt.list(vnu),queryParameters:gt.list(MJn),headers:gt.list(d3i),sdkName:kar.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Pnu.optional(),response:jnu.optional(),errors:gt.record(Xar,wnu),servers:gt.list(bJn),examples:gt.list(mJn),pagination:PJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var nw_=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:kar.optional(),method:jJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Iee),headers:gt.list(d3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>xM),examples:gt.list(wJn)}).extend(Of).extend(Ch).extend(x0);var Snu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Dnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Enu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Mnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Anu=gt.objectWithoutOptionalProperties({example:gt.number().optional()});var qnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Tnu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional(),example:gt.string().optional()});var Cnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Bnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Inu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var znu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional(),example:gt.boolean().optional()});var xnu=gt.union("type",{int:Snu,int64:Dnu,uint:Enu,uint64:Mnu,float:Anu,double:qnu,string:Tnu,datetime:Cnu,date:Bnu,base64:Inu,boolean:znu}).transform({transform:e=>{switch(e.type){case"int":return vp.int(e);case"int64":return vp.int64(e);case"uint":return vp.uint(e);case"uint64":return vp.uint64(e);case"float":return vp.float(e);case"double":return vp.double(e);case"string":return vp.string(e);case"datetime":return vp.datetime(e);case"date":return vp.date(e);case"base64":return vp.base64(e);case"boolean":return vp.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var qJn=gt.objectWithoutOptionalProperties({schema:xnu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var Rnu=gt.objectWithoutOptionalProperties({default:u3i.optional(),values:gt.list(u3i),example:gt.string().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var Nnu=gt.objectWithoutOptionalProperties({example:gt.unknown()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var xM=gt.union("type",{primitive:qJn,object:gt.lazyObject(()=>Wnu),array:gt.lazyObject(()=>Fnu),map:gt.lazyObject(()=>Lnu),optional:gt.lazyObject(()=>Unu),enum:Rnu,reference:eor,literal:SJn,oneOf:gt.object({value:gt.lazy(()=>Hnu)}),nullable:gt.lazyObject(()=>Vnu),unknown:Nnu}).transform({transform:e=>{switch(e.type){case"primitive":return Nl.primitive(e);case"object":return Nl.object(e);case"array":return Nl.array(e);case"map":return Nl.map(e);case"optional":return Nl.optional(e);case"enum":return Nl.enum(e);case"reference":return Nl.reference(e);case"literal":return Nl.literal(e);case"oneOf":return Nl.oneOf(e.value);case"nullable":return Nl.nullable(e);case"unknown":return Nl.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM),example:gt.list(gt.unknown()).optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Lnu=gt.objectWithoutOptionalProperties({key:qJn,value:gt.lazy(()=>xM),example:gt.unknown().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Um).extend(zM);var Unu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Vnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Wnu=gt.objectWithoutOptionalProperties({allOf:gt.list(eor),properties:gt.list(gt.lazyObject(()=>$nu)),allOfPropertyConflicts:gt.list(DJn),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var $nu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),audiences:gt.list(gt.string()),conflict:gt.record(Bee,EJn),nameOverride:gt.string().optional(),generatedName:gt.string()}).extend(oy);var Hnu=gt.union("type",{discriminated:gt.lazyObject(()=>Gnu),undiscriminated:gt.lazyObject(()=>Qnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Cee.discriminated(e);case"undiscriminated":return Cee.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Gnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>Jnu)),schemas:gt.record(gt.string(),gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Ch).extend(Um).extend(zM);var Jnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM)});var Qnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Cue).extend(Ch).extend(Um).extend(zM);var aw_=/^(\d+)/,TJn=/^[a-zA-Z][a-zA-Z0-9_]*$/,ow_={"<":"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 p3i(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),c=e%10;return c===0?i[u]:`${i[u]}_${t[c]}`}if(e<1e3){let u=Math.floor(e/100),c=e%100;return c===0?`${t[u]}_hundred`:`${t[u]}_hundred_${p3i(c)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${p3i(a)}`}function t5a(e){let t=e.match(aw_);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=p3i(n);return i.length>0?`${a}_${i}`:a}}}function CJn(e){let t=t5a(e),r=ow_[e];return t!=null?QB(R_(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":QB(R_(e)))}function Bue(e,t){return e.type==="primitive"&&t.type==="primitive"?uw_(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?fBE(e.values,t.values):e.type==="array"&&t.type==="array"?Bue(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"?Bue(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?dBE(e.value,t.value):e.type==="object"&&t.type==="object"?pBE(e,t):e.type==="map"&&t.type==="map"?uw_(e.key.schema,t.key.schema)&&Bue(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function uw_(e,t){return e.type===t.type}function fBE(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return W8(r,i)}function dBE(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:Bue(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:Bue(r,n)}):!1}function pBE(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:Bue(a,n.schema)})}function PR(e){switch(e){case b$.Deprecated:return"deprecated";case b$.Beta:return"pre-release";case b$.GenerallyAvailable:return"generally-available";default:return}}function _BE(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function sw_(e){let t=e?_BE(e):void 0;if(t==null||t.length===0)return PZi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(R_(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(R_(n.name)):r.push(n.name,PZi);break}default:Ao(n.type)}else Ao(n);return r.join("/")}function _3i(e){return wy.of(`${sw_(e)}.yml`)}function RSc({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?PZi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,sw_(r))}function cw_({sdkName:e,namespaceOverride:t}){return wy.of(`${RSc({sdkName:e,namespaceOverride:t})}.yml`)}function lw_({location:e,namespaceOverride:t}){return t!=null?GN(wy.of(t),e):e}function Knu(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Ao(e.type)}}function BJn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Ao(e)}}function sq(e){return typeof e=="string"?e:e.type}function IJn(e){if(typeof e!="string")return e.docs}function r5a(e){if(typeof e!="string")return e.default}function NSc(e){if(typeof e!="string")return e.validation}var hBE=-2147483648,yBE=2147483647,vBE=-17976931348623157e292,bBE=17976931348623157e292;function Xg({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return Ynu(e);case"array":return USc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return VSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return LSc({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return HSc();case"optional":return Xnu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return WSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return EBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,$Sc(e);case"object":return MBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return ABE({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Ao(e)}}function Ynu(e){switch(e.schema.type){case"string":return mBE({description:e.description,schema:e.schema});case"int":return PBE({description:e.description,schema:e.schema});case"float":return jBE({description:e.description,schema:e.schema});case"double":return wBE({description:e.description,schema:e.schema});case"boolean":return gBE({description:e.description,schema:e.schema});case"int64":return OBE({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function gBE({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function OBE({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function mBE({description:e,schema:t}){let r="string",i=SBE(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function PBE({description:e,schema:t}){let r="integer",i=dw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function jBE({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function wBE({description:e,schema:t}){let r="double",i=dw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function SBE(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=DBE(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function DBE(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 dw_(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=FSc(r,t),i=FSc(i,t),n=FSc(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function FSc(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[hBE,yBE]:[vBE,bBE];return e<r||e>i?void 0:e}function LSc({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=qBE(n)??e.schema,u=BJn(n),c=TBE(n),d=Znu({context:r,fileContainingReference:t,declarationFile:_3i(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&c==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function USc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=`list<${sq(u)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{},type:c}}function VSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ynu(e.key),c=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?Knu(e.encoding):void 0,s=`map<${sq(u)}, ${sq(c)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=PR(e.availability)),o}function WSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return Xnu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=sq(u),d=IJn(u),s=r5a(u),o=NSc(u),l=c.startsWith("nullable<")?c:`nullable<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return fw_({typeReference:l,itemType:c});let b={type:l};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=PR(e.availability)),fw_({typeReference:b,itemType:c})}function Xnu({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=sq(u),d=IJn(u),s=r5a(u),o=NSc(u),l=c.startsWith("optional<")?c:`optional<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return l;let b={type:l};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=PR(e.availability)),b}function HSc(){return"unknown"}function $Sc(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ao(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function EBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=i5a(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let c=Znu({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return c;let d={type:c};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=PR(e.availability)),d}function MBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=GSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Znu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function ABE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=QSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Znu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:PR(e.availability)}:{}}}function Znu({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function qBE(e){return Ov._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function TBE(e){return Ov._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function fw_({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var v5;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(v5||(v5={}));function Emi(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ao(e)}}function _w_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=IBE(e);break;case"array":a=CBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=BBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=zBE({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=RBE(e.nameOverride,e.generatedName);break;case"optional":a=hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=xBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=i5a(e,n);break;case"literal":a=NBE(e,e.nameOverride,e.generatedName);break;case"object":a=GSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=QSc({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Ao(e)}return a}function GSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(v5.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,c={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([E,T])=>!T.differentSchema))continue;Object.entries(g.conflict).forEach(([E])=>{JSc({property:g.key,schemaId:E,context:t,namespace:i}).forEach(z=>{d.add(z)})})}let O=Xg({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,P=g.nameOverride,D=PR(g.availability),A=VBE(g);c[g.key]=UBE({typeReference:O,audiences:m,name:P,availability:D,propertyAccess:A})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=yw_({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=Xg({schema:Ov.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(sq(m))}for(let g of d){let O=KSc(t,g,i);for(let m of O.properties)c[m.key]==null&&(s.has(m.key)&&(c[m.key]="unknown"),c[m.key]=Xg({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let P=Xg({schema:Ov.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(sq(P))}}let l={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(c).map(([g,O])=>LBE(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(l.extends=o),e.additionalProperties&&(l["extra-properties"]=!0),e.availability!=null&&(l.availability=PR(e.availability)),e.source!=null&&(l.source=Emi(e.source)),l.inline=YSc(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:l}}function JSc({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return JSc({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=KSc(r,t,i),c=a.some(s=>s.key===e),d=[...u.flatMap(s=>JSc({property:e,context:r,schemaId:s.schema,namespace:i}))];if(c||d.length>0)return[t,...d]}return[]}function KSc(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return KSc(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function CBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:USc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function BBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:VSc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function IBE(e){let t=Ynu(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function pw_(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function i5a(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,c=a.value;if(u===c&&a.description==null&&(a.casing==null||pw_(a.casing)))return u;let d={value:a.value};if(u!==c&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!pw_(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=YSc(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?Emi(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function zBE({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:LSc({schema:e,context:t,fileContainingReference:r,namespace:i})}}function xBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:WSc({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:Xnu({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function RBE(e,t){return{name:e??t,schema:HSc()}}function NBE(e,t,r){return{name:t??r,schema:$Sc(e)}}function QSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?Knu(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let s of e.commonProperties)c[s.key]=Xg({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=Xg({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?PR(e.availability):void 0,union:d,encoding:a,source:e.source!=null?Emi(e.source):void 0}}}let u=[];for(let c of e.schemas)u.push(Xg({schema:c,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?Emi(e.source):void 0,inline:YSc(e,n)}}}var FBE=/^[0-9]/;function LBE(e){return FBE.test(e)}function yw_({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?yw_({context:t,schema:i.schema,namespace:r}):e}function UBE({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function YSc(e,t){return e.inline===!0||t>0?!0:void 0}function VBE(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return ZN.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return ZN.ObjectPropertyAccess.WriteOnly}}function vw_(e){let t=e.replace(/^x-|^X-/,"");return R_(t)}var bw_="BasicAuthScheme",knu="BearerAuthScheme";function gw_(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:bw_,schema:n}),t||(e.builder.setAuth(bw_),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:knu,schema:n}),t||(e.builder.setAuth(knu),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??vw_(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:knu,schema:n}),t||(e.builder.setAuth(knu),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(wy.of("__package__.yml"),{name:"OauthScope",schema:i5a(i.scopesEnum,0).schema})}}function tor({header:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=sq(n),u=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:R_(u);if(e.description==null&&e.name===c&&e.env==null&&e.availability==null)return a;let d={type:a};return c!==e.name&&(d.name=c),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=PR(e.availability)),d}function eau({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return sq(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:sq(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=PR(e.availability)),a}function rau({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=XSc({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=sq(n.value),u=r5a(n.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let c={type:a};return u!=null&&(c.default=u),n.allowMultiple&&(c["allow-multiple"]=!0),e.description!=null&&(c.docs=e.description),e.parameterNameOverride!=null&&(c.name=e.parameterNameOverride),e.availability!=null&&(c.availability=PR(e.availability)),WBE(n.value)&&n.value.validation!==void 0&&(c.validation=n.value.validation),c.default==null&&c["allow-multiple"]==null&&c.docs==null&&c.name==null&&c.availability==null&&c.validation==null?a:c}function XSc({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:wy.of(SS),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[],u=!1;for(let[c,d]of Object.entries(n.value.schemas))d.type==="primitive"&&d.schema.type==="string"&&(u=!0),d.type==="literal"&&d.value.type==="string"&&(TJn.test(d.value.value)?a.push(d.value.value):a.push({value:d.value.value,name:CJn(d.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),u&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[c,d]=n.value.schemas;if(c!=null&&d!=null&&tau({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:d,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(c!=null&&d!=null&&tau({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[c,d]of Object.entries(n.value.schemas))return XSc({schema:d,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[],a=!1;for(let[u,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(a=!0),c.type==="literal"&&c.value.type==="string"&&(TJn.test(c.value.value)?n.push(c.value.value):n.push({value:c.value.value,name:CJn(c.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),a&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[u,c]=e.value.value.schemas;if(u!=null&&c!=null&&tau({array:u,primitive:c}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&c!=null&&tau({array:c,primitive:u}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1};for(let[u,c]of Object.entries(e.value.value.schemas))return XSc({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function tau({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function WBE(e){return e.type!=null}function Ow_({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"]=HBE(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=$BE({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=h3i(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function HBE(e){let t={};return e.forEach(r=>{let i=h3i(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function $BE({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=h3i(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function h3i(e){switch(e.type){case"primitive":return mw_(e.value);case"object":return Pw_(e.properties);case"array":return GBE(e.value);case"map":return QBE(e.value);case"oneOf":return JBE(e.value);case"enum":return e.value;case"literal":return KBE(e.value);case"unknown":return h3i(e.value);default:Ao(e)}}function mw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function Pw_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,h3i(r)]))}function GBE(e){return e.map(t=>h3i(t))}function QBE(e){return Object.fromEntries(e.map(t=>[mw_(t.key),h3i(t.value)]))}function JBE(e){return e.type==="discriminated"?Pw_(e.value):h3i(e.value)}function KBE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function Mmi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function iau(e,t){return t??(e?.groupName!=null?Mmi(e.groupName):void 0)}function jw_({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary),e.description!=null&&(i.docs=e.description);let n=Mmi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=eau({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=rau({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let c={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=tor({header:d,context:t,fileContainingReference:r,namespace:n});c[d.name]=s}Object.keys(c).length>0&&(i.headers=c),t.builder.addChannel(r,{channel:i});for(let d of e.messages)t.builder.addChannelMessage(r,{messageId:d.name,message:{origin:d.origin,body:Xg({schema:d.body,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=Ow_({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var Ami="Base",YBE="Default";function y3i(e){return Object.entries(e).reduce((t,[r,i])=>(zLn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function ww_(e){if(e.environmentOverrides!=null){for(let[g,O]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:g,schema:O});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let g of e.ir.servers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){r.push(O);continue}t[g.name]=O}let i={},n=[];for(let g of e.ir.endpoints)for(let O of g.servers){if(O.url==null)continue;let m=O.audiences?{url:O.url,audiences:O.audiences}:O.url;if(O.name==null){n.push(m);continue}i[O.name]=m}let a={},u=[];for(let g of e.ir.websocketServers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){u.push(O);continue}a[g.name]=O}let c=Object.keys(t).length,d=c>0,s=Object.keys(i).length>0,o=Object.keys(a).length>0;if(!d&&!s&&o&&e.ir.servers.length===0){for(let[g,O]of Object.entries(a))e.builder.addEnvironment({name:g,schema:O});e.builder.setDefaultEnvironment(Object.keys(a)[0]),e.builder.setDefaultUrl(Ami);return}if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),!d){let g=e.ir.servers[0]?.url,O=e.ir.servers[0]?.audiences;if(g!=null){let m=O?{url:g,audiences:O}:g;t[YBE]=m}}let l=Object.values(t).map(g=>typeof g=="string"?g:g.url),b=r.filter(g=>{let O=typeof g=="string"?g:g.url;return!l.includes(O)});if(b.length>0&&e.logger.error(`Skipping top level servers ${b.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),s)if(c===1){let g=Object.keys(t)[0],O=Object.values(t)[0],m=typeof O=="string"?O:O.url;e.builder.addEnvironment({name:g,schema:{urls:{[Ami]:m,...y3i(i),...y3i(a)}}}),e.builder.setDefaultEnvironment(g),e.builder.setDefaultUrl(Ami)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...y3i(i),...y3i(a)}}}),e.builder.setDefaultEnvironment(O),g=!1):e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...y3i(i),...y3i(a)}}});e.builder.setDefaultUrl(Ami)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(o?e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...y3i(a)}}}):e.builder.addEnvironment({name:O,schema:m}),e.builder.setDefaultEnvironment(O),g=!1):o?e.builder.addEnvironment({name:O,schema:{urls:{[Ami]:typeof m=="string"?m:m.url,...y3i(a)}}}):e.builder.addEnvironment({name:O,schema:m});o&&e.builder.setDefaultUrl(Ami)}}function nau(e){return sq(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var ZSc=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},XBE=.75,ZBE=new Set("authorization");function Sw_(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?BJn(i.schema):void 0,u=a!=null?Mmi(a):void 0,c=wy.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?sq(Xg({schema:i.schema,context:e,fileContainingReference:u?GN(wy.of(R_(u)),c):c,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(ZBE.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let c=t[a.name],d=tor({header:{...a,schema:c?.schema??a.schema,name:c?.name??a.name},fileContainingReference:wy.of(n6),context:e,namespace:void 0});u=new ZSc(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*XBE;for(let[n,a]of Object.entries(r)){let u=t[n],c=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(c?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:nau(a.schema)}))}}}function Dw_(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?BJn(t.schema):void 0,i=r!=null?Mmi(r):void 0,n=tor({header:{...t,schema:t.schema??Ov.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:xw.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:wy.of(n6),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:nau(n)})}}function IK(e){switch(e.type){case"primitive":return Mw_(e.value);case"object":return Aw_(e.properties);case"array":return qw_(e.value);case"map":return eIE(e.value);case"oneOf":return tIE(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return rIE(e.value);case"unknown":return IK(e.value);default:Ao(e)}}function Ew_(e){switch(e.type){case"withStreaming":return e.sse?{stream:kBE(e.events)}:{stream:qw_(e.events)};case"withoutStreaming":return{body:IK(e.value)};default:Ao(e)}}function Mw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function Aw_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,IK(r)]))}function kBE(e){return e.map(t=>({event:"",data:IK(t)}))}function qw_(e){return e.map(t=>IK(t))}function eIE(e){return Object.fromEntries(e.map(t=>[Mw_(t.key),IK(t.value)]))}function tIE(e){return e.type==="discriminated"?Aw_(e.value):IK(e.value)}function rIE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function Tw_({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"]=iIE(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=nIE(e.queryParameters));let i=e.headers!=null&&e.headers.length>0,n=t.builder.getGlobalHeaders(),a=Object.keys(n).length>0,u=new Set(e.headers?.map(c=>c.name)??[]);if(i||a){let c=[];if(e.headers!=null)for(let d of e.headers)d.name!==t.builder.getAuthHeaderName()&&c.push(d);for(let[d,s]of Object.entries(n))if(!u.has(d))if(s!=null&&typeof s=="object"&&s.type!=null){let o=b6({type:s.type,_default:void 0,validation:void 0,visitor:{primitive:l=>l.toString(),map:l=>l.toString(),list:l=>l,optional:l=>l,nullable:l=>l,set:l=>l,named:l=>l,literal:l=>{if(l.type==="string")return l.string;if(l.type==="boolean")return l.boolean.toString()},unknown:Ko}});o!=null&&c.push({name:d,value:Yg.literal(i3i.string(o))})}else c.push({name:d,value:Yg.primitive(D_.string(d))});r.headers=aIE({context:t,namedFullExamples:c})}return e.request!=null&&(r.request=IK(e.request)),e.response!=null&&(r.response=Ew_(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(c=>c.type==="language"?{name:c.name??void 0,docs:c.description??void 0,language:c.language,code:c.code,install:c.install??void 0}:{name:c.name??void 0,docs:c.description??void 0,sdk:c.sdk,code:c.code}).filter(yy)),r}function iIE(e){let t={};return e.forEach(r=>{let i=IK(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function nIE(e){let t={};return e.forEach(r=>{let i=IK(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function aIE({context:e,namedFullExamples:t}){let r={};return t.forEach(i=>{let n=IK(i.value);n!=null&&(r[i.name]=n)}),r}function Cw_(e){return O$._visit(e,{get:()=>ZN.HttpMethodSchema.Get,post:()=>ZN.HttpMethodSchema.Post,put:()=>ZN.HttpMethodSchema.Put,patch:()=>ZN.HttpMethodSchema.Patch,delete:()=>ZN.HttpMethodSchema.Delete,head:()=>ZN.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function Bw_(e){return e==="POST"||e==="PUT"||e==="PATCH"}function Iw_({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,c=iau(e.sdkName,e.namespace),d={};for(let P of e.pathParameters)P.parameterNameOverride&&(u=u.replace(P.name,P.parameterNameOverride)),d[P.parameterNameOverride??P.name]=eau({pathParameter:P,context:r,fileContainingReference:t,namespace:c}),a.add(P.name);let s={};for(let P of e.queryParameters){let D=rau({queryParameter:P,context:r,fileContainingReference:t,namespace:c});D!=null&&(s[P.name]=D,a.add(P.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:Ao(e.pagination)}let l={path:u,method:Cw_(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?Emi(e.source):void 0};!sIE({context:r,request:e.request})&&Object.keys(d).length>0&&(l["path-parameters"]=d),e.summary!=null&&(l["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=r.builder.getAuthHeaderName();O!=null&&g.add(O);let m=e.headers.filter(P=>!g.has(P.name));for(let P of m){let D=tor({header:P,context:r,fileContainingReference:t,namespace:c});b[P.name]=D,a.add(typeof D=="string"?P.name:D.name??P.name)}if(e.request!=null){r.setInState(v5.Request);let P=uIE({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:c});l.request=P.value,n=[...n,...P.schemaIdsToExclude??[]],r.unsetInState(v5.Request)}else{let P=r.inlinePathParameters&&Object.keys(d).length>0,D=Object.keys(s).length>0,A=Object.keys(b).length>0,M={};(P||D||A)&&(M.name=e.requestNameOverride??e.generatedRequestName),P&&(M["path-parameters"]=d),D&&(M["query-parameters"]=s),A&&(M.headers=b),Object.keys(M).length>0&&(l.request=M)}if(e.response!=null&&e.response._visit({json:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l.response={docs:P.description??void 0,type:sq(D)},P.statusCode!=null&&(l.response["status-code"]=P.statusCode),P.responseProperty!=null&&(l.response.property=P.responseProperty)},streamingJson:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:sq(D),format:"json"}},streamingSse:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:sq(D),format:"sse"}},file:P=>{l.response={docs:P.description??void 0,type:"file","status-code":P.statusCode}},bytes:P=>{l.response={docs:P.description??void 0,type:"bytes","status-code":P.statusCode}},streamingText:P=>{l["response-stream"]={docs:P.description??void 0,type:"text"}},text:P=>{l.response={docs:P.description??void 0,type:"text","status-code":P.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let P=r.getDefaultServerName(),D=e.servers[0];D==null?P!=null&&(l.url=P):l.url=D.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=PR(e.availability)),Object.entries(e.errors).forEach(([P,D])=>{let A=D.generatedName,M=wy.of(SS);r.builder.enableUniqueErrorsPerEndpoint&&(A=`${e.generatedRequestName}${D.generatedName}`,D.schema!=null&&(D.schema.type!=="reference"&&D.schema.type!=="oneOf"?D.schema.generatedName=`${e.generatedRequestName}${D.schema.generatedName}`:D.schema.type==="oneOf"&&(D.schema.value.generatedName=`${e.generatedRequestName}${D.schema.value.generatedName}`)));let E={"status-code":parseInt(P)},T=lw_({location:zw_,namespaceOverride:c});if(D.schema!=null){let I=Xg({schema:D.schema,context:r,fileContainingReference:T,declarationFile:T,namespace:c,declarationDepth:0});E.type=sq(I),E.docs=D.description}r.builder.addError(T,{name:A,schema:r.isErrorUnknownSchema(parseInt(P))?{...E,type:"unknown"}:E}),l.errors==null&&(l.errors=[]);let z=r.builder.addImport({file:t,fileToImport:T});l.errors.push(z!=null?`${z}.${A}`:A),E.type!=null&&D.examples?.forEach(I=>{let R={value:IK(I.example),name:I.name,docs:I.description};r.builder.addErrorExample(T,{name:A,example:R})})}),e.examples.length>0&&(l.examples=oIE({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[kSc,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:n}}function oIE({endpointExamples:e,context:t}){return e.map(r=>{try{return Tw_({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function uIE({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:c,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:l}){if(i.type==="json"||i.type==="formUrlEncoded"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,l):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=Xg({schema:i.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),M={schemaIdsToExclude:[],value:{body:A}},E=Object.keys(u??{}).length>0,T=Object.keys(c??{}).length>0,z=Object.keys(s??{}).length>0;return E&&(M.value["path-parameters"]=u),T&&(M.value["query-parameters"]=c),z&&(M.value.headers=s),(E||T||z)&&(M.value.name=n??a),i.contentType!=null&&(M.value["content-type"]=i.contentType),i.description!=null&&(M.value.docs=i.description),M}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(Bw_(e.method)&&A.readonly)).map(A=>{let M=Xg({schema:A.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:1}),E=A.nameOverride??A.key,T=PR(A.availability);if(!o.has(E)&&A.audiences.length<=0)return o.add(E),A.nameOverride!=null?[A.key,{type:sq(M),docs:IJn(M),name:A.nameOverride,availability:T}]:[A.key,T?{...typeof M=="string"?{type:M}:M,availability:T}:M];let z={type:sq(M),docs:IJn(M)};return o.has(E)&&(z.name=A.generatedName),A.audiences.length>0&&(z.audiences=A.audiences),T!=null&&(z.availability=T),o.add(E),[A.key,z]})),m=g.allOf.map(A=>{let M=Xg({schema:Ov.reference(A),fileContainingReference:t,context:r,namespace:l,declarationDepth:0});return sq(M)}).filter(A=>A!=="unknown"),P={properties:O};m.length>0&&(P.extends=m),i.additionalProperties&&(P["extra-properties"]=!0);let D={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":c,headers:s,body:P};return i.contentType!=null&&(D["content-type"]=i.contentType),i.description!=null&&(D.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:D}}else if(i.type==="octetStream"){let b={body:"bytes","content-type":i.contentType??Iq.APPLICATION_OCTET_STREAM,"query-parameters":c};return c!=null&&(b.name=n??a),i.description!=null&&(b.docs=i.description),{schemaIdsToExclude:[],value:b}}else if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let P=g.contentType.split(",")[0];m["content-type"]=P}return[g.key,m]}return[g.key,O]}else{let O=Xg({schema:g.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(g.contentType||g.exploded||g.encoding){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.encoding==="json"?m.style="json":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":c,headers:s,body:{properties:b},"content-type":Iq.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Ao(i)}function sIE({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Ao(t)}}function cIE({location:e,namespaceOverride:t}){return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function lIE(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:wy.of(`${R_(r)}.yml`),endpointId:e.summary!=null?R_(e.summary):R_(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:wy.of(SS),endpointId:R_(e.summary)}:{file:wy.of(SS),endpointId:R_(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:wy.of(SS),endpointId:i};let n=n5a(r),a=n5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=pIE({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let c=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])c.push(s);else{let o=R_(r);return{file:wy.of(`${o}.yml`),endpointId:i,tag:r}}}if(c.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:wy.of(R_(c.join("_"))+".yml"),endpointId:R_(a.slice(c.length).join("_")),tag:r}}function a5a(e){let t=e.tags[0];if(e.sdkName!=null){let r=RSc({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:wy.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return cIE({namespaceOverride:e.namespace,location:lIE(e)})}function n5a(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=j3e(t),t}var fIE=new RegExp("[^a-zA-Z0-9{}]+"),dIE=new RegExp("[{}]","g");function pIE({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(fIE).join("_").replaceAll(dIE,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:wy.of(R_(t)+".yml"),endpointId:R_(e.slice(0,-1*a.length)),tag:t}}function xw_(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:c,tag:d}=a5a(a),s=c.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,P=g[m];if(P==null)break;if(P.summary!=null||P.description!=null){o=g[m];break}}}let l=d==null?void 0:i.tagsById[d];e.setInState(v5.Endpoint),e.setEndpointMethod(a.method);let b=Iw_({context:e,endpoint:a,declarationFile:c});e.unsetEndpointMethod(),e.unsetInState(v5.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(c,{name:u,schema:b.value,source:a.source!=null?Emi(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(c,{"display-name":o?.summary??l?.id,docs:o?.description??l?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function Rw_(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?Mmi(r.groupName):void 0,n=Xg({schema:Ov.primitive(r),context:e,fileContainingReference:wy.of(SS),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:sq(n),docs:r.description??void 0}})}}function Nw_(e){for(let t of e.ir.webhooks){let r=yIE({webhook:t,context:e});if(r==null)continue;let i=iau(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=tor({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:n,payload:Xg({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:IK(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function _IE({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function hIE({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:wy.of(SS),endpointId:i};let n=n5a(r),a=n5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=[];for(let c=0;c<n.length;++c){let d=n[c];if(d!=null&&d===a[c])u.push(d);else{let s=R_(r);return{file:wy.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:wy.of(R_(u.join("_"))+".yml"),endpointId:R_(a.slice(u.length).join("_")),tag:r}}function yIE({webhook:e,context:t}){return e.sdkName!=null?{file:cw_({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:_IE({namespaceOverride:e.namespace,location:hIE({webhook:e,context:t})})}var vIE=wy.of(SS);function Lw_(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return Fw_({namespace:e.namespace,groupName:e.groupName});case"oneOf":return Fw_({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return vIE;default:Ao(e)}}function Fw_({namespace:e,groupName:t}){return e!=null&&t!=null?_3i([{type:"namespace",name:e},...t]):e!=null?_3i([{type:"namespace",name:e}]):_3i(t)}var kSc="external",zw_=wy.of(SS);function Uw_({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=Lw_(a),c=_w_({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(kIi(c.schema)){let d=sq(c.schema);if(d===(c.name??n)||d===`optional<${c.name??n}>`||d===`optional<nullable<${c.name??n}>>`)continue}i.builder.addType(u,{name:c.name??n,schema:c.schema})}}function Vw_(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),ww_(e),Sw_(e),Dw_(e),gw_(e),Rw_(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(kSc);let t=xw_(e),r=t.sdkGroups;e.setInState(v5.Webhook),Nw_(e),e.unsetInState(v5.Webhook),e.setInState(v5.Channel);for(let n of Object.values(e.ir.channels)){let a=_3i(n.groupName);jw_({channel:n,context:e,declarationFile:a})}e.unsetInState(v5.Channel);let i=bIE({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});Uw_({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))Uw_({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function bIE({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}var o5a=class{context;constructor(t){this.context=t}};var aau=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,c]of Object.entries(i.files)){let d=n!=null?wy.of(`${n}${"/"}${u}`):wy.of(u);t[d]=c}let a=Object.keys(i.directories).sort();for(let u of a){let c=n!=null?`${n}${"/"}${u}`:u,d=i.directories[u];r(d,c)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[wy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var vnn=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new aau,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return sir(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))Ww_(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(Ww_(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??R_((x3e(r)+"/"+WZi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===wy.of(n6))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=iBo(x3e(J8n.of(`/${t}`)),J8n.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=iBo(x3e(J8n.of(`/${t}`)),J8n.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===wy.of(n6))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(c=>W8(c,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=GN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:GN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:GN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===SS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function Ww_(e){return e?.header!=null}var oau=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.useBytesForBinaryResponse=i?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=i?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new vnn(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let c={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let l=parseInt(s),b=c[l];b==null&&o.schema!=null?c[l]=o.schema:b!=null&&o.schema!=null&&Bue(b,o.schema)||this.unknownSchema.add(l)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(v5.Channel,v5.Endpoint,v5.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ao(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Ao(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function eDc(e){let t=new oau(e);return Vw_(t)}var uau=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=eDc({taskContext:t,ir:r,options:Y8a({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:i?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums}}),authOverrides:i?.auth!=null?{auth:i.auth}:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:xd.dump(a.rootApiFile)},namedDefinitionFiles:{...Sd(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(u),contents:u})),[wy.of(SS)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var u5a=class extends DQt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;inlineAllOfSchemas;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.inlineAllOfSchemas=t.inlineAllOfSchemas,this.converter=new uau(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new Eqe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};var m$={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var zJn={of(e){return e}};var Hw_={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},tDc={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:Hw_,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},ad={SOURCE:zJn.of("source"),SDK_NAMESPACE:zJn.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:zJn.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:zJn.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:zJn.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport",IS_DISCRIMINATED:"x-fern-discriminated"};var _7={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json",useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,additionalPropertiesDefaultsTo:!1,typeDatesAsStrings:!0,preserveSingleSchemaOneOf:!1,inlineAllOfSchemas:!1};function qQt({options:e,overrides:t}){return{disableExamples:t?.disableExamples??_7.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??_7.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??_7.useTitlesAsName,audiences:t?.audiences??e?.audiences??_7.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??_7.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??_7.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??_7.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??_7.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??_7.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??_7.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??_7.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??_7.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??_7.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??_7.objectQueryParameters,filter:t?.filter??e?.filter??_7.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??_7.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??_7.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??_7.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??_7.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??_7.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??_7.preserveSingleSchemaOneOf,inlineAllOfSchemas:t?.inlineAllOfSchemas??e?.inlineAllOfSchemas??_7.inlineAllOfSchemas}}var $w_={naming:"v1"};function hf(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function s5a(e,t,r,i,n=[]){try{let a=hf(e,t);if(a!=null)return r.parse(a)}catch{let u=j3e(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function bnn(e){let t=hf(e,"examples");if(t!=null){if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null)return Object.values(t).map(r=>typeof r=="object"&&r!==null&&"value"in r?r.value:r)}return[]}function Gw_({schema:e,logger:t}){return hf(e,ad.ENCODING)??void 0}function Qw_(e){return hf(e,ad.FERN_ENUM)}function Jw_({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=hf(i,ad.SDK_NAMESPACE),c=hf(i,ad.SDK_GROUP_NAME),d=hf(i,ad.TYPE_DEFINITION);if(d!=null)return c5a({fernType:d,nameOverride:e,generatedName:t,title:r,description:n,availability:a,namespace:u,groupName:typeof c=="string"?[c]:c})}function c5a({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c}){return b6({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>{switch(d.v1){case"BASE_64":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.base64({example:void 0})});case"BOOLEAN":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.boolean({default:void 0,example:void 0})});case"DATE":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.date({example:void 0})});case"DATE_TIME":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.datetime({example:void 0})});case"FLOAT":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.float({example:void 0})});case"DOUBLE":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint({default:void 0,example:void 0})});case"INTEGER":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint64({default:void 0,example:void 0})});case"LONG":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Nl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Ao(d.v1)}},unknown:()=>Nl.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,namespace:u,groupName:c}),map:({keyType:d,valueType:s})=>d?.type==="primitive"&&s!=null?Nl.map({nameOverride:t,generatedName:r,title:i,key:d,value:s,description:n,availability:a,namespace:u,groupName:c,encoding:void 0,example:void 0,inline:void 0}):void 0,list:d=>d!=null?Nl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,optional:d=>d!=null?Nl.optional({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,nullable:d=>d!=null?Nl.nullable({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,set:d=>d!=null?Nl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,literal:d=>Nl.literal({nameOverride:t,generatedName:r,title:i,value:d._visit({string:s=>_x.string(s),boolean:s=>_x.boolean(s),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,namespace:u,groupName:c}),named:d=>Nl.reference({schema:d,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,source:TK.openapi({file:"<memory>"})})}})}function Kw_(e){let t=hf(e,ad.SOURCE);if(t!=null)return t.endsWith(".proto")?TK.protobuf({file:t}):TK.openapi({file:t})}function gnn(e){if(e!=null&&typeof e=="boolean")return e}function ep(e){return e?.$ref!=null}function Yw_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,encoding:b,source:g}){return n===void 0&&(n=d.options.additionalPropertiesDefaultsTo),typeof n=="boolean"||xJn(n,d.options)?sau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Nl.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}),namespace:s,groupName:o,example:l,encoding:b}):sau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Xw_(n0(n,d.options.optionalAdditionalProperties?c:!1,d,[...i,"Value"],g,s,void 0,void 0,void 0)),namespace:s,groupName:o,example:l,encoding:b})}function Xw_(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=Xw_(e.value);break;case"oneOf":e.value.inline=!0;break;default:Ao(e)}return e}function sau({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:c,namespace:d,groupName:s,example:o,encoding:l}){return a?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0}),description:u,availability:c,namespace:d,groupName:s,inline:void 0}):Nl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:c,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0})}function xJn(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!ep(e)&&Object.keys(e).length===0}function Zw_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,source:b}){let g=n==null?Nl.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:o}):n0(n,!1,d,[...i,"Item"],b,s);return gIE({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:o,itemSchema:g,wrapAsNullable:c,description:a,availability:u,example:l})}function gIE({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,example:s}){return n?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):Nl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0})}function zK(e){switch(hf(e,ad.AVAILABILITY)){case"deprecated":return b$.Deprecated;case"beta":return b$.Beta;case"generally-available":return b$.GenerallyAvailable;default:break}if(!ep(e)&&e.deprecated)return b$.Deprecated}function rDc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminator:s,context:o,namespace:l,groupName:b,encoding:g,source:O}){let m=s.propertyName,P=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,M])=>{let E=qmi({$ref:M},!1,o,[M],g,O,l);return o.markReferencedByDiscriminatedUnion({$ref:M},m,1),[A,E]})),D=Object.entries(n).filter(([A])=>A!==m).map(([A,M])=>{let E=c!=null&&c.includes(A),T=n0(M,!E,o,[...i,A],O,l);return{key:A,schema:T}});return kw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:m,subtypes:P,namespace:l,groupName:b,source:O})}function iDc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminant:s,variants:o,context:l,namespace:b,groupName:g,encoding:O,source:m}){let P=Object.fromEntries(Object.entries(o).map(([A,M])=>{if(ep(M)){let E=qmi(M,!1,l,[M.$ref],O,m,b);return l.markReferencedByDiscriminatedUnion(M,s,1),[A,E]}else{let E=RJn(M,!1,l,[...i,A],O,m,b,new Set([s]));return[A,E]}})),D=Object.entries(n).filter(([A])=>A!==s).map(([A,M])=>{let E=c!=null&&c.includes(A),T=n0(M,!E,l,[...i,A],m,b);return{key:A,schema:T}});return kw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:s,subtypes:P,namespace:b,groupName:g,source:m})}function kw_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:c,subtypes:d,namespace:s,groupName:o,source:l}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.oneOf(Cee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0})),namespace:s,groupName:o,description:a,availability:u,inline:void 0}):Nl.oneOf(Cee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0}))}function e1_(e){if(e.proto!=null)return iJn.protobuf({typeName:e.proto.type})}function v3i({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:c,availability:d,wrapAsNullable:s,namespace:o,groupName:l,context:b,source:g,inline:O}){let m=mIE(n??[]),P=new Set(a),D=Array.from(P).map((M,E)=>{let T=i?.[M],z=m[E],G=TJn.test(M),I=T?.name??z,R=G?M:CJn(M);return I!=null&&!TJn.test(I)&&(b?.logger.warn(`Enum name override ${I} is not a valid name. Falling back on ${R}.`),I=void 0),{nameOverride:I,generatedName:R,value:M,description:T?.description,availability:d,casing:{snake:T?.casing?.snake??void 0,pascal:T?.casing?.pascal??void 0,screamingSnake:T?.casing?.screamingSnake??void 0,camel:T?.casing?.camel??void 0}}}),A=u!=null?D.find(M=>M.value===u):void 0;return OIE({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:D,_default:A,description:c,availability:d,namespace:o,groupName:l,source:g,inline:O})}function OIE({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:c,namespace:d,groupName:s,source:o,inline:l}){return e?Nl.nullable({nameOverride:t,generatedName:r,title:i,value:Nl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:c,example:void 0,namespace:d,groupName:s,source:o,inline:l}),description:u,availability:c,namespace:d,groupName:s,inline:l}):Nl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:c,default:a,example:void 0,namespace:d,groupName:s,source:o,inline:l})}function mIE(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function t1_({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m})}function r1_(e){return typeof e=="string"?_x.string(e):typeof e=="boolean"?_x.boolean(e):_x.string(`${e}`)}function i1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,namespace:c,groupName:d}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.literal({nameOverride:e,generatedName:t,title:r,value:r1_(n),description:a,availability:u,namespace:c,groupName:d}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):Nl.literal({nameOverride:e,generatedName:t,title:r,value:r1_(n),description:a,availability:u,namespace:c,groupName:d})}function nDc({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==null||i==="double"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.double({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="float"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="int32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):i==="time-delta"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:b,description:o,availability:l,namespace:O,groupName:m})}var PIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},jIE={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}}},wIE={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}}},SIE={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},DIE={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},EIE={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},MIE={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},AIE={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function cau(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[PIE,jIE,wIE,SIE,DIE,EIE,MIE,AIE],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:c}=a.applyStrategy(t);t=u,r=[...r,...c]}}while(t.join("")!==n.join(""));return r}function g5(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:QB(R_(n))).join("");return/^\d/.test(i)?t5a(i)??i:i}function aDc(e){let t=e.join("_");return R_(t)}function bA(e){switch(e.type){case"object":return Ov.object({allOf:e.allOf,properties:e.properties.map(t=>TIE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return Ov.array({description:e.description,availability:e.availability,value:bA(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return Ov.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return Ov.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"nullable":return Ov.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return Ov.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return Ov.primitive({description:e.description,availability:e.availability,schema:n1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Ov.map({description:e.description,availability:e.availability,key:Ov.primitive({description:e.key.description,availability:e.key.availability,schema:n1_(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:bA(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return Ov.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Ov.oneOf(qIE(e.value));case"unknown":return Ov.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Ao(e)}}function qIE(e){switch(e.type){case"discriminated":return Dmi.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:bA(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,bA(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return Dmi.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>bA(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Ao(e)}}function n1_(e){switch(e.type){case"string":return xw.string(e);case"base64":return xw.base64();case"boolean":return xw.boolean(e);case"date":return xw.date();case"datetime":return xw.datetime();case"double":return xw.double(e);case"float":return xw.float();case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();default:Ao(e)}}function TIE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:bA(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function lau(e,t){return Bue(bA(e),bA(t))}function a1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:c,allOf:d,context:s,propertiesToExclude:o,namespace:l,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:P}){let D=[...u??[]],A={...n},M=[],E=[];for(let R of d)if(!s.options.inlineAllOfSchemas&&ep(R)){let U=s.resolveSchemaReference(R);if(U.discriminator!=null&&U.discriminator.mapping!=null)continue;if(U.oneOf!=null||U.anyOf!=null){let J=U.oneOf??U.anyOf;if(J!=null){for(let X of J){let ae=ep(X)?s.resolveSchemaReference(X):X,pe=n0(ae,!1,s.DUMMY,i,P,l);pe.type==="object"&&M.push(...pe.properties.map(de=>de.schema.type!=="optional"&&de.schema.type!=="nullable"?{...de,schema:Nl.optional({nameOverride:void 0,generatedName:"",title:void 0,value:de.schema,description:void 0,availability:de.availability,namespace:void 0,groupName:void 0,inline:void 0})}:de))}continue}}let Y=b3i(R);if(Y==null)continue;E.push({schemaId:Y,convertedSchema:oDc(R,[Y],P,s.options.preserveSchemaIds),properties:o1_({schema:R,context:s,breadcrumbs:i,source:P,namespace:l})}),s.markSchemaAsReferencedByNonRequest(Y)}else if(ep(R)){let U=s.resolveSchemaReference(R),Y=n0(U,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}else{let U=R.required??[];M=M.map(J=>(J.schema.type==="optional"||J.schema.type==="nullable")&&U.includes(J.key)?{...J,schema:J.schema.value}:J);let Y=n0(R,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}let T={};for(let R of E)for(let[U,Y]of Object.entries(R.properties)){let J=T[U];J!=null?(J.schemaIds.push(R.schemaId),J.schemas.some(ae=>lau(ae,Y))||J.schemas.push(Y)):T[U]={schemaIds:[R.schemaId],schemas:[Y]}}let z=[];for(let[R,U]of Object.entries(T))U.schemaIds.length>1&&z.push({propertyKey:R,allOfSchemaIds:U.schemaIds,conflictingTypeSignatures:U.schemas.length>1});let G=Object.fromEntries(Object.entries(A).filter(([R,U])=>!(!ep(U)&&U.type==="null"))),I=Object.entries(G).map(([R,U])=>{let Y=hf(U,ad.AUDIENCES)??[],J=zK(U),X=ep(U)?!1:U.readOnly,ae=ep(U)?!1:U.writeOnly,pe=D.includes(R)&&!X,de=hf(U,ad.FERN_PROPERTY_NAME),me=[...i,R],Le=aDc(me),yt=pe?n0(U,!1,s,me,P,l):Nl.optional({nameOverride:e,generatedName:Le,title:r,description:void 0,availability:J,value:n0(U,!1,s,me,P,l),namespace:l,groupName:b,inline:void 0}),De={};for(let Ae of E){let Ct=Ae.properties[R];Ct!=null&&!lau(yt,Ct)?De[Ae.schemaId]={differentSchema:!0}:Ct!=null&&(De[Ae.schemaId]={differentSchema:!1})}return{key:R,schema:yt,nameOverride:de,audiences:Y,conflict:De,generatedName:aDc([...i,R]),availability:J,readonly:X,writeonly:ae}});return I.push(...M.map(R=>{let U=R.conflict;for(let Y of E){let J=Y.properties[R.key];J!=null&&!lau(R.schema,J)?U[Y.schemaId]={differentSchema:!0}:J!=null&&(U[Y.schemaId]={differentSchema:!1})}return{...R,conflict:U}})),CIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,properties:I.filter(R=>!o.has(R.key)),description:a,allOf:E.map(R=>R.convertedSchema),allOfPropertyConflicts:z,namespace:l,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:P,context:s})}function CIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:l,availability:b,source:g,context:O}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:xJn(l,O.options),availability:void 0,source:g,inline:void 0}),description:a,availability:b,namespace:d,groupName:s,inline:void 0}):Nl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:xJn(l,O.options),availability:b,source:g,inline:void 0})}function o1_({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,c]=ep(e)?[t.resolveSchemaReference(e),cau(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...o1_({schema:d,context:t,breadcrumbs:c,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=n0(s,!1,t,[...c,d],i,n);a[d]=o}return a}function g3i({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:c,subtypes:d,namespace:s,groupName:o,encoding:l,source:b,subtypePrefixOverrides:g}){let O=zIE({schemas:d}),m=d.flatMap((D,A)=>{if(!ep(D)&&D.enum!=null&&c.options.coerceEnumsToLiterals&&D.type==="string")return D.enum.map(E=>Nl.literal({nameOverride:void 0,generatedName:g5([t,E],c.options.preserveSchemaIds),title:void 0,value:_x.string(String(E)),namespace:s,groupName:void 0,description:void 0,availability:E.availability}));let M=O[A];if(g!=null){let E=g[A];E!=null&&"name"in E&&(M=E.name)}return[n0(D,!1,c,[...i,M??`${A}`],b,s)]}),P=BIE(m);return IIE({uniqueSubtypes:P,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,namespace:s,groupName:o,context:c,encoding:l,source:b})}function BIE(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&Bue(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function IIE({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,context:s,encoding:o,source:l}){if(Object.entries(e).every(([g,O])=>O.type==="literal")){let g={},O=[];return Object.entries(e).forEach(([m,P])=>{P.type==="literal"&&P.value.type==="string"&&(O.push(P.value.value),P.description!=null&&(g[P.value.value]={description:P.description}))}),v3i({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:g,enumVarNames:void 0,enumValues:O,_default:void 0,namespace:c,groupName:d,context:s,source:l,inline:void 0})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:u1_({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,namespace:c,groupName:d,encoding:o,source:l})}function uDc({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,namespace:c,groupName:d,discriminator:s,encoding:o,source:l}){let b=Object.entries(s.mapping??{}).map(([m,P],D)=>{let A={$ref:P},M=qmi(A,!1,u,[P],o,l,c);return u.markSchemaWithDiscriminantValue(A,s.propertyName,m),M.type==="object"&&(M.properties={[s.propertyName]:Nl.literal({nameOverride:void 0,generatedName:g5([t,m],u.options.preserveSchemaIds),title:void 0,value:_x.string(m),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...M.properties.filter(E=>E.key!==s.propertyName)}),M}),g=[];for(let m=0;m<b.length;++m){let P=b[m],D=!1;for(let A=m+1;A<b.length;++A){let M=b[A];if(P!=null&&M!=null&&Bue(P,M)){D=!0;break}}P!=null&&!D&&g.push(P)}if(Object.entries(g).every(([m,P])=>P.type==="literal")){let m={},P=[];return Object.entries(g).forEach(([D,A])=>{A.type==="literal"&&A.value.type==="string"&&(P.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),v3i({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:P,_default:void 0,namespace:c,groupName:d,context:u,source:l,inline:void 0})}return g.length===1&&g[0]!=null&&!u.options.preserveSingleSchemaOneOf?g[0]:u1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,namespace:c,groupName:d,encoding:o,source:l})}function zIE({schemas:e}){let t={},r=0;for(let a of e){if(!ep(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),c={},d=u;for(let[s,o]of Object.entries(t)){let l=oAo(o,u);d=oAo(d,o),c[s]=l}c[r]=d,t=c}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let c=u.sort();if(c[0]!=null){i.push(c[0]),++n;continue}}ep(a)?i.push(p3i(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(p3i(n)??`${n}`),++n}return i}function u1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,namespace:c,groupName:d,encoding:s,source:o}){return i?Nl.nullable({nameOverride:e,generatedName:t,title:r,value:Nl.oneOf(Cee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0})),description:n,availability:a,namespace:c,groupName:d,inline:void 0}):Nl.oneOf(Cee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0}))}function NJn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function fau({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=bnn(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function s1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=bnn(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function ror({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=bnn(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function c1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=bnn(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var Onn="#/components/schemas/";function n0(e,t,r,i,n,a,u=!1,c=new Set,d){let s=Kw_(e)??n,o=WIE({schema:e,logger:r.logger});if(ep(e)){let l=b3i(e);return l!=null?(u?r.markSchemaAsReferencedByRequest(l):r.markSchemaAsReferencedByNonRequest(l),qmi(e,t,r,i,o,s,a)):RJn(r.resolveSchemaReference(e),t,r,cau(e.$ref),o,s,a,c,u,d)}return RJn(e,t,r,i,o,s,a,c,u,d)}function qmi(e,t,r,i,n,a,u){let c=e.$ref.includes("properties")?RJn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Nl.reference(oDc(e,i,a,r.options.preserveSchemaIds));return t?Nl.nullable({title:void 0,nameOverride:void 0,generatedName:g5(i,r.options.preserveSchemaIds),value:c,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0}):c}function xIE(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function RJn(e,t,r,i,n,a,u,c=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=hf(e,ad.TYPE_NAME)??(r.options.useTitlesAsName?xIE(e.title):void 0),l=hf(e,ad.SDK_GROUP_NAME)??hf(e,m$.TAGS)?.[0],b=(typeof l=="string"?[l]:l)??[];b=r.resolveGroupName(b);let g=g5(i,r.options.preserveSchemaIds),O=e.title,m=e.description,P=zK(e),D=[];e.example!=null&&D.push({name:void 0,value:e.example,description:void 0});let A=hf(e,m$.EXAMPLES);A!=null&&Object.keys(A).length>0&&D.push(...Object.entries(A).map(([z,G])=>({name:G?.summary??z,value:G.value,description:G.description})));let M=bnn(e);M!=null&&Object.keys(M).length>0&&D.push(...M.map(z=>({name:void 0,value:z,description:void 0})));let E=Jw_({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:P});if(E!=null)return E;if(Array.isArray(e.type)){let z=e.type.indexOf("null"),G=z!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&G)e.type.splice(z,1),e.type=e.type[0],e.nullable=!0;else if(G&&(e.type.splice(z,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let I=new Set([...e.oneOf,...e.type]);e.oneOf=[...I]}}if(!t&&e.nullable===!0)return RJn(e,!0,r,i,n,a,u,c,d,s);if("const"in e&&(e.enum=[e.const]),e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(!_au(e.enum))return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:NJn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:P});let z=Qw_(e);return e.enum.length===1&&e.enum[0]!=null&&z==null?i1_({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:P,namespace:u,groupName:b}):v3i({nameOverride:o,generatedName:g,title:O,fernEnum:z,enumVarNames:hf(e,[m$.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0})}if(_au(e.type)&&e.type.length>1){let z=e.type.includes("null"),G=e.type.filter(I=>I!=="null").map(I=>({type:I,nullable:z}));return g3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:G,namespace:u,groupName:b,encoding:n,source:a})}if(e.type==="boolean"){let z=hf(e,ad.BOOLEAN_LITERAL);return z!=null?l1_({nameOverride:o,generatedName:g,title:O,literal:_x.boolean(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.boolean({default:RIE(e.default),example:s1_({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b})}if(e.type==="number")return nDc({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:gnn(e.exclusiveMinimum),exclusiveMaximum:gnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="integer")return t1_({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:gnn(e.exclusiveMinimum),exclusiveMaximum:gnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="float")return nDc({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:gnn(e.exclusiveMinimum),exclusiveMaximum:gnn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="string"){if(e.format==="date-time")return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.datetime({example:ror({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b});if(e.format==="date"&&r.options.typeDatesAsStrings===!1)return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.date({example:ror({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b});if(e.format==="json-string")return Nl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:b,example:void 0});let z=p1_(e,"const");return z!=null?l1_({nameOverride:o,generatedName:g,title:O,literal:_x.string(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:b}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:NJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:P})}if(e.type==="array")return Zw_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,example:c1_({schema:e,logger:r.logger,fallback:s}),source:a});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&dau(e))return Yw_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,example:e.example,source:a});if(e.oneOf!=null&&e.oneOf.length>0&&hf(e,ad.IS_DISCRIMINATED)===!1)return g3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf,namespace:u,groupName:b,encoding:n,source:a});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?uDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):rDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf!=null&&e.oneOf.length>0){let z=hf(e,ad.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||z?uDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):rDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(r.options.preserveSingleSchemaOneOf)return g3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:b,source:a});let G=n0(e.oneOf[0],t,r,i,a,u,d);return FJn(G,m,u,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let U=e.oneOf[0],Y=e.oneOf[1];if(!ep(U)&&U.type==="null")return n0(Y,!0,r,i,a,u);if(!ep(Y)&&Y.type==="null")return n0(U,!0,r,i,a,u)}let G=LIE({schemas:e.oneOf});if(G!=null)return v3i({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:G,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0});let I=f1_({schemas:e.oneOf,context:r});if(I!=null&&!r.options.discriminatedUnionV2&&!z)return iDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:I.discriminant,variants:I.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let R=e.oneOf.filter(U=>!ep(U)&&U.type==="null").length>0;return g3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||R,context:r,subtypes:e.oneOf.filter(U=>ep(U)||U.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let I=n0(e.anyOf[0],t,r,i,a,u,d);return FJn(I,m,u,b)}if(e.anyOf.length===2){let[I,R]=e.anyOf;if(I!=null&&R!=null){if(!ep(I)&&I.type==="null"){let U=n0(R,!0,r,i,a,u);return FJn(U,m,u,b)}else if(!ep(R)&&R.type==="null"){let U=n0(I,!0,r,i,a,u);return FJn(U,m,u,b)}}}let z=f1_({schemas:e.anyOf,context:r});if(z!=null&&!r.options.discriminatedUnionV2)return iDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:z.discriminant,variants:z.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let G=e.anyOf.filter(I=>!ep(I)&&I.type==="null").length>0;return g3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||G,context:r,subtypes:e.anyOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}if(e.allOf!=null||e.properties!=null){let z=[];for(let I of e.allOf??[])(ep(I)||Object.keys(I).length>0)&&z.push(I);if((e.properties==null||dau(e))&&z.length===1&&z[0]!=null){let I=n0(z[0],t,r,i,a,u,d);return FJn(I,m,u,b)}let G=z.filter(I=>{let R=pau(I);return R||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(I)}`),R});if((e.properties==null||dau(e))&&G.length===1&&G[0]!=null){let I=n0(G[0],t,r,i,a,u,d);return FJn(I,m,u,b)}return a1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:G,context:r,propertiesToExclude:c,namespace:u,groupName:b,fullExamples:D,additionalProperties:e.additionalProperties,availability:P,encoding:n,source:a})}if(e.type==="object"&&NIE(e)&&FIE(e)&&dau(e))return sau({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:NJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:ror({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b},valueSchema:Nl.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:u,groupName:b}),namespace:u,groupName:b,encoding:n,example:e.example});e.type!=null&&r.logger.warn(`Failed to parse an OpenAPI schema at the following location: ${i.join("->")}. Coercing to unknown.`);let T=e.example??e.default;return Nl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:b,example:T})}function RIE(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function b3i(e){if(e.$ref.startsWith(Onn))return e.$ref.replace(Onn,"")}function oDc(e,t,r,i){let n=hf(e,ad.TYPE_NAME),a=g5(t,i),u=e.description,c=zK(e),d=b3i(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return Ov.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:c,namespace:void 0,groupName:void 0,source:r})}function NIE(e){return e.oneOf==null||e.oneOf.length===0}function FIE(e){return e.allOf==null||e.allOf.length===0}function dau(e){return e.properties==null||zq(e.properties)===0}function _au(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function FJn(e,t,r,i){return e.type==="reference"?Nl.reference({...e,description:t,availability:e.availability,namespace:r,groupName:i}):e.type==="optional"?Nl.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e.type==="nullable"?Nl.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e}function pau(e){return ep(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>pau(t)):e.oneOf!=null?e.oneOf.every(t=>pau(t)):e.anyOf!=null?e.anyOf.every(t=>pau(t)):!1}function l1_({literal:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,nameOverride:u,generatedName:c,title:d}){return t?Nl.nullable({nameOverride:u,generatedName:c,title:d,value:Nl.literal({nameOverride:u,generatedName:c,title:d,value:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Nl.literal({nameOverride:u,generatedName:c,title:d,value:e,namespace:r,groupName:i,description:n,availability:a})}function b5({primitive:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,generatedName:u,nameOverride:c,title:d}){return i=typeof i=="string"?[i]:i,t?Nl.nullable({nameOverride:c,generatedName:u,title:d,value:Nl.primitive({nameOverride:c,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Nl.primitive({nameOverride:c,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i})}function LIE({schemas:e}){let t=new Set;for(let r of e){if(ep(r))return;if(r.enum!=null&&_au(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function f1_({schemas:e,context:t}){let r={};for(let i of e){let n=d1_({schema:i,context:t});for(let[a,u]of Object.entries(n)){let c=r[a];c!=null?c[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function d1_({schema:e,context:t}){let r=ep(e)?t.resolveSchemaReference(e):e;return UIE({schema:r,context:t})}function UIE({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=d1_({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=ep(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&_au(a.enum)&&VIE(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=p1_(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function VIE(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function p1_(e,t){let r=e[t];if(r!=null)return r}function WIE({schema:e,logger:t}){let r=Gw_({schema:e,logger:t});if(r!=null)return e1_(r)}var LJn=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(Onn))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(Onn.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,c]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(ep(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&c!=null){let s=d.properties?.[c];if(s==null)throw new Error(`Property "${c}" not found on "${a}". Full ref: ${t.$ref}`);ep(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var hau=class extends LJn{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",i=this.document.components;if(i==null||i.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let n=t.$ref.substring(r.length),a=i.messages[n];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function UJn(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let i={};for(let[n,a]of Object.entries(t))switch(a.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(a.namespace==null){r[n]=a;continue}let u=a.namespace;i[u]??={},i[u][n]=a;continue}case"oneOf":case"unknown":r[n]=a;continue;default:Ao(a)}return{rootSchemas:r,namespacedSchemas:i}}function O3i(e){if(typeof e=="string")return Yg.primitive(D_.string(e));if(typeof e=="number")return Number.isInteger(e)?Yg.primitive(D_.int(e)):Yg.primitive(D_.double(e));if(typeof e=="boolean")return Yg.primitive(D_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>O3i(r));return t.length===0?void 0:Yg.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=O3i(i);n!=null&&t.push({key:D_.string(r),value:n})}return Yg.map(t)}}function l5a(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function _1_(e){if(e!=null&&Array.isArray(e))return e}var m3i=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:c}){switch(i.type){case"enum":return typeof r=="string"&&h1_({schema:i,value:r})?Yg.enum(r):i.values[0]!=null?Yg.enum(i.values[0]?.value):void 0;case"literal":return Yg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:c});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:c});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return Yg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?c:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},l=l5a(r),b=l?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,l);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let P of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=Yg.primitive(D_.string(b));break}else{let D=this.buildExampleHelper({exampleId:t,schema:P[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:c});if(D!=null){this.mergeExampleWith(D,d),d[i.value.discriminantProperty]=Yg.primitive(D_.string(P[0]));break}}for(let P of i.value.commonProperties){s[P.key]={schema:P.schema,readonly:!1};let D=this.getResolvedSchema(P.schema);D.type!=="optional"&&D.type!=="nullable"&&(o[P.key]=P.schema)}for(let[P,D]of Object.entries(s)){let A=P in o;if(A&&l?.[P]!=null){let M=this.buildExampleHelper({schema:D.schema,exampleId:t,example:l[P],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});if(M!=null)d[P]=M;else return}else{let M=this.buildExampleHelper({exampleId:t,schema:D.schema,example:l?.[P],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});if(M!=null)d[P]=M;else if(A)return}}return Yg.oneOf(n3i.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:c});break}}return;case"unknown":if(r!=null){let d=O3i(r);if(d!=null)return Yg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?Yg.primitive(D_.string(u.name??"string")):Yg.map([{key:D_.string("key"),value:Yg.primitive(D_.string("value"))}]);case"array":{let d=_1_(r),s=[];if(d!=null&&d.length>0)for(let o of d){let l=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});l!=null&&s.push(l)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let l=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});l!=null&&s.push(l)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:c});o!=null&&s.push(o)}return Yg.array(s)}case"map":{let d=l5a(r??i.example);if(d!=null&&Object.entries(d).length>0){let l=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:c});m!=null&&l.push({key:O,value:m})}return Yg.map(l)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return Yg.map([{key:D_.string("key"),value:Yg.unknown(Yg.primitive(D_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:c});return o!=null?Yg.map([{key:s,value:o}]):Yg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=l5a(r)??(s!=null?l5a(s.value):{})??{},l=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(l)){if(c&&O.readonly||O.schema._visit({optional:A=>typeof A.availability=="string"&&A.availability==="Deprecated",primitive:()=>!1,object:()=>!1,array:()=>!1,map:()=>!1,enum:()=>!1,reference:()=>!1,literal:()=>!1,oneOf:()=>!1,nullable:()=>!1,unknown:()=>!1,_other:()=>!1}))continue;let m=g in b,P=Object.keys(o).includes(g),D=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:c});if(m&&D!=null)d[g]=D;else{if(m)return;(P&&D!=null||!u.ignoreOptionals&&D!=null)&&(d[g]=D)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Nl.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:c});m!=null&&(d[g]=m)}}return Yg.object({properties:d})}default:Ao(i)}}mergeExampleWith(t,r){t._visit({array:Ko,enum:Ko,literal:Ko,map:i=>{for(let n of i){let a=n.key;a.type==="string"&&(r[a.value]=n.value)}},object:i=>{for(let[n,a]of Object.entries(i.properties))r[n]=a},oneOf:i=>{if(i.type==="discriminated")for(let[n,a]of Object.entries(i.value))r[n]=a;else this.mergeExampleWith(i.value,r)},primitive:Ko,unknown:Ko,_other:Ko})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return h1_({schema:t,value:r})?5:0;case"object":{if(!Tw(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!Tw(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?D_.string(t):r.example!=null?D_.string(r.example):D_.string(i.name??Hh.STRING);case"base64":return t!=null&&typeof t=="string"?D_.base64(t):r.example!=null?D_.base64(r.example):D_.base64(Hh.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?D_.boolean(t):r.example!=null?D_.boolean(r.example):D_.boolean(Hh.BOOLEAN);case"date":return t!=null&&typeof t=="string"?D_.date(t):r.example!=null?D_.date(r.example):D_.date(Hh.DATE);case"datetime":return t!=null&&typeof t=="string"?D_.datetime(t):r.example!=null?D_.datetime(r.example):D_.datetime(Hh.DATE_TIME);case"double":return t!=null&&typeof t=="number"?D_.double(t):r.example!=null?D_.double(r.example):D_.double(Hh.DOUBLE);case"float":return t!=null&&typeof t=="number"?D_.float(t):r.example!=null?D_.float(r.example):D_.float(Hh.FLOAT);case"int":return t!=null&&typeof t=="number"?D_.int(t):r.example!=null?D_.int(r.example):D_.int(Hh.INT);case"int64":return t!=null&&typeof t=="number"?D_.int64(t):r.example!=null?D_.int64(r.example):D_.int64(Hh.INT64);case"uint":return t!=null&&typeof t=="number"?D_.uint(t):r.example!=null?D_.uint(r.example):D_.uint(Hh.UINT);case"uint64":return t!=null&&typeof t=="number"?D_.uint64(t):r.example!=null?D_.uint64(r.example):D_.uint64(Hh.UINT64);default:Ao(r)}}};function h1_({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function TQt(e){switch(e.type){case"object":return Nl.object({allOf:e.allOf,properties:e.properties.map(t=>$IE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return Nl.array({description:e.description,availability:e.availability,value:TQt(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Nl.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Nl.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName});case"nullable":return Nl.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:TQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Nl.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:TQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Nl.primitive({description:e.description,availability:e.availability,schema:y1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Nl.map({description:e.description,availability:e.availability,key:Nl.primitive({description:e.key.description,availability:e.key.availability,schema:y1_(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:TQt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return Nl.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Nl.oneOf(HIE(e.value));case"unknown":return Nl.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,namespace:void 0,groupName:void 0,description:void 0,availability:void 0});default:Ao(e)}}function HIE(e){switch(e.type){case"discriminated":return Cee.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:TQt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,TQt(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return Cee.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>TQt(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Ao(e)}}function y1_(e){switch(e.type){case"string":return vp.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return vp.base64({example:void 0});case"boolean":return vp.boolean({default:e.default,example:void 0});case"date":return vp.date({example:void 0});case"datetime":return vp.datetime({example:void 0});case"double":return vp.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return vp.float({example:void 0});case"int":return vp.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return vp.int64({default:e.default,example:void 0});case"uint":return vp.uint({default:void 0,example:void 0});case"uint64":return vp.uint64({default:void 0,example:void 0});default:Ao(e)}}function $IE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:TQt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function yau(e){return e.type!=="optional"&&e.type!=="nullable"}function sDc(e){return e==="POST"||e==="PUT"||e==="PATCH"}function f5a(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var vau=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,i){this.schemas=t,this.context=r,this.globalHeaders=i,this.schemas=t,this.exampleTypeFactory=new m3i(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=QIE(t.request),i=JIE(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:sDc(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:sDc(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(l&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let l=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,MQt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,MQt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,MQt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,MQt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let l of t.pathParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:g})}let c=[];for(let l of t.queryParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&c.push({name:l.name,value:g})}let d=[];for(let l of t.headers){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:l.name,value:g})}for(let l of this.globalHeaders){let b=l.schema!=null?TQt(l.schema):Nl.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:vp.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),g=this.exampleTypeFactory.buildExample({schema:b,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!CQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),g==null)return[];g!=null&&d.push({name:l.header,value:g})}let s=[];t.request!=null&&t.response!=null?s=GIE(n,a):t.request!=null?s=n.map(([l,b])=>({id:l,request:b,response:void 0})):t.response!=null&&(s=a.map(([l,b])=>({id:l,request:void 0,response:b})));let o=t.examples.filter(l=>f5a(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let b=l.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return l.codeSamples}).filter(l=>yy(l));return s.length===0?[EQt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:c,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:l,request:b,response:g})=>EQt.full({name:l,description:void 0,pathParameters:u,queryParameters:c,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?wmi.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):wmi.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?g$.Csharp:r.sdk,code:r.code})).filter(yy)}isSchemaRequired(t){return yau(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function GIE(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,c]of t)r.push({id:u??n,request:a,response:c});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,c]of e)r.push({id:u??n,request:c,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let c=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),c=!0)}!c&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],c=e.find(([d])=>d==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:u})}return r}function QIE(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:KIE(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function JIE(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function CQt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return CQt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return CQt(e.value.value);default:return!1}default:Ao(e)}}function KIE(e){return Nl.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:TQt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(yy),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var VJn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new m3i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let u=[];for(let c of r){let d=[];for(let l of i.queryParameters){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!CQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&d.push({name:l.name,value:g})}let s=[];for(let l of i.headers){let b=this.isSchemaRequired(l.schema),g=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!CQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&s.push({name:l.name,value:g})}let o=[];for(let l of c.messages){let b=t.getExampleMessageReference(l),g=t.resolveMessageReference({$ref:b}),O=ep(g.payload)?t.resolveSchemaReference(g.payload):g.payload,m=this.exampleTypeFactory.buildExample({schema:n0(O,!1,t,[l.messageId],n,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&o.push({messageType:l.type,payload:m,description:void 0})}u.push({name:c.summary,queryParameters:d,headers:s,description:c.description,messages:o})}return u}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let u of t.queryParameters){let c=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!CQt(d)&&(d=void 0),c&&d==null)return;d!=null&&n.push({name:u.name,value:d})}let a=[];for(let u of t.headers){let c=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!CQt(d)&&(d=void 0),c&&d==null)return;d!=null&&a.push({name:u.name,value:d})}for(let u of r){let c=this.exampleTypeFactory.buildExample({schema:u.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&i.messages.push({messageType:u.type,payload:c,description:void 0})}return i}isSchemaRequired(t){return yau(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var zee={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function bau(e){return hf(e,zee.FERN_EXAMPLES)??[]}function gau(e,t){return t.includes("://")?t:`${e}://${t}`}function Oau(e){return e.startsWith("/")?e:"/"+e}function g1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let l=n0(o,!1,e,[s],r,e.namespace);a[s]=l}let c=new VJn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:gau(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let l=hf(o,zee.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[D,A]of Object.entries(o.parameters??{}))b.push({name:D,description:A.description,parameterNameOverride:void 0,schema:A.schema!=null?n0(A.schema,!1,e,t,r,e.namespace):Nl.primitive({schema:vp.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:zK(A),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let D=o.bindings.ws.headers.required??[];for(let[A,M]of Object.entries(o.bindings.ws.headers.properties??{})){if(ep(M)){let E=e.resolveSchemaReference(M);g.push({name:A,schema:qmi(M,!1,e,t,void 0,r,e.namespace),description:E.description,parameterNameOverride:void 0,env:void 0,availability:zK(E),source:r});continue}g.push({name:A,schema:n0(M,!D.includes(A),e,[...t,A],r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:zK(M),source:r})}}if(o.bindings.ws.query!=null){let D=o.bindings.ws.query.required??[];for(let[A,M]of Object.entries(o.bindings.ws.query.properties??{})){if(ep(M)){let E=e.resolveSchemaReference(M);O.push({name:A,schema:qmi(M,!1,e,t,void 0,r,e.namespace),description:E.description,parameterNameOverride:void 0,availability:zK(E),source:r});continue}O.push({name:A,schema:n0(M,!D.includes(A),e,[...t,A],r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:zK(M),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=v1_({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=b1_({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let P;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?P=v1_({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):P=b1_({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||P!=null){let D=bau(o),A=[];if(D.length>0)A=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:D,handshake:{headers:g,queryParameters:O},source:r,namespace:e.namespace});else{let z=[];m!=null&&z.push({type:"publish",payload:m}),P!=null&&z.push({type:"subscribe",payload:P});let G=c.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},messages:z});G!=null&&A.push(G)}let M=hf(o,zee.FERN_CHANNEL_ADDRESS),E=M??Oau(s),T=[];m!=null&&T.push({origin:"client",name:"publish",body:bA(m)}),P!=null&&T.push({origin:"server",name:"subscribe",body:bA(P)}),u[s]={audiences:hf(o,ad.AUDIENCES)??[],handshake:{headers:g.map(z=>({...z,schema:bA(z.schema),env:z.env})),queryParameters:O.map(z=>({...z,schema:bA(z.schema)})),pathParameters:b.map(z=>({...z,parameterNameOverride:void 0,schema:bA(z.schema)}))},groupName:e.resolveGroupName([hf(o,zee.FERN_SDK_GROUP_NAME)??s]),messages:T,servers:(o.servers?.map(z=>d[z])??Object.values(d)).filter(z=>z!=null),summary:hf(o,zee.FERN_DISPLAY_NAME),path:E,description:o.description,examples:A,source:r}}}return{groupedSchemas:UJn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:hf(n,zee.BASE_PATH)}}function v1_({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],d=[];for(let s of t.message.oneOf){let o,l={type:"notFound"};if(ep(s)){let b=r.resolveMessageReference(s);!ep(b.payload)&&u.naming==="v2"?(l=b.name?{type:"name",name:b.name}:l,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(l),c.push(o)}return g3i({description:t.description??t.message.description,availability:zK(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function b1_({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return ep(r.payload)&&(a=i.resolveSchemaReference(r.payload)),n0(a,!1,i,[t,e],n,i.namespace)}}var mau=class extends LJn{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(r.length),n=this.document.components.parameters[i];if(n==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in n?this.resolveParameterReference(n):n}resolveMessageReference(t){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let c=t.$ref.split("/"),d=c[2],s=c[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let l=this.document.channels[d].messages?.[s];if(l==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in l?this.resolveMessageReference(l):{name:s,...l}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var O1_="#/channels/",m1_="#/servers/",cDc="$message.";function j1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},c={},d=[],s={};for(let[O,m]of Object.entries(n.components?.schemas??{}))a[O]=n0(m,!1,e,[O],r,e.namespace);for(let[O,m]of Object.entries(n.channels??{}))if(u[O]||(u[O]={}),m.messages){for(let[P,D]of Object.entries(m.messages))if(e.isReferenceObject(D)||e.isMessageWithPayload(D))if(c[P]||(c[P]=[]),e.isReferenceObject(D)){let A=e.resolveMessageReference(D);c[P].push({channelId:O,payload:A.payload})}else c[P].push({channelId:O,payload:D.payload})}for(let[O,m]of Object.entries(c))if(m.length===1){let P=m[0],D=P.channelId;u[D]=u[D]||{},u[D][O]=n0(P.payload,!1,e,[O],r,e.namespace)}else{d.push(O);for(let{channelId:P,payload:D}of m){let A=`${P}_${O}`;u[P]||(u[P]={}),u[P][A]=n0(D,!1,e,[A],r,e.namespace)}}let o=Object.values(u).reduce((O,m)=>({...O,...m}),{}),l=new VJn(o,e),b={};for(let[O,m]of Object.entries(n.servers??{}))b[O]={name:O,url:gau(m.protocol,m.host)};let g={};for(let[O,m]of Object.entries(n.operations??{})){if(hf(m,zee.IGNORE))continue;let P=YIE(m);if(g[P]||(g[P]={subscribe:[],publish:[],__parsedMessages:[]}),m.action==="receive")g[P].subscribe.push(...m.messages);else if(m.action==="send")g[P].publish.push(...m.messages);else throw new Error(`Operation ${O} has an invalid action: ${m.action}`)}for(let[O,m]of Object.entries(g)){let P=[];P.push(...P1_({messages:m.subscribe,channelPath:O,origin:"server",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),P.push(...P1_({messages:m.publish,channelPath:O,origin:"client",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),g[O]!=null&&(g[O].__parsedMessages=P)}for(let[O,m]of Object.entries(n.channels??{})){if(hf(m,zee.IGNORE))continue;let P=[],D=[],A=[];if(m.parameters!=null)for(let[M,E]of Object.entries(m.parameters)){let T=e.isReferenceObject(E)?e.resolveParameterReference(E):E,{type:z,parameterKey:G}=T.location!=null?XIE(T.location):{type:m.address?.includes(`={${M}}`)?"query":"path",parameterKey:M},I=hf(T,zee.FERN_PARAMETER_OPTIONAL),R=QB(R_(O))+QB(R_(M)),U={...T,type:"string",title:R,example:T.examples?.[0],default:T.default,enum:T.enum,required:void 0},Y=n0(U,!1,e,[G],r,e.namespace);I&&(Y=Nl.optional({value:Y,description:void 0,availability:void 0,generatedName:"",title:R,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let J={name:G,description:T.description,parameterNameOverride:void 0,schema:Y,variableReference:void 0,availability:zK(E),source:r};z==="header"?P.push({...J,env:void 0}):z==="path"?D.push(J):(z==="payload"||z==="query")&&A.push(J)}if(P.length>0||A.length>0||g[O]!=null&&(g[O].publish!=null||g[O].subscribe!=null)){let M=bau(m),E=g[O]?.__parsedMessages??[],T=[];if(M.length>0)T=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:M,handshake:{headers:P,queryParameters:A},source:r,namespace:e.namespace});else{let z=[],{examplePublishMessage:G,exampleSubscribeMessage:I}=kIE({messages:E,messageSchemas:u[O]??{}});G!=null&&z.push(G),I!=null&&z.push(I);let R=l.buildWebsocketSessionExample({handshake:{headers:P,queryParameters:A},messages:z});R!=null&&T.push(R)}s[O]={audiences:hf(m,ad.AUDIENCES)??[],handshake:{headers:P.map(z=>({...z,schema:bA(z.schema),env:z.env})),queryParameters:A.map(z=>({...z,schema:bA(z.schema)})),pathParameters:D.map(z=>({...z,parameterNameOverride:void 0,schema:bA(z.schema)}))},groupName:e.resolveGroupName([hf(m,zee.FERN_SDK_GROUP_NAME)??O]),messages:E,summary:hf(m,zee.FERN_DISPLAY_NAME),servers:m.servers?.map(z=>ZIE(b,z))??Object.values(b),path:m.address?.split("?")[0]??Oau(O),description:m.description,examples:T,source:r}}}return{groupedSchemas:UJn(e.namespace,a),channels:s,servers:Object.values(b),basePath:hf(n,zee.BASE_PATH)}}function YIE(e){if(!e.channel.$ref.startsWith(O1_))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(O1_.length)}function XIE(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(cDc))throw new Error(`Invalid location format: ${e}; expected ${cDc} prefix`);let i=t.substring(cDc.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function ZIE(e,t){if(!t.$ref.startsWith(m1_))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(m1_.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function P1_({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let u=[];return e.forEach((c,d)=>{let o=a.resolveMessageReference(c).name;n.includes(o)&&(o=`${t}_${o}`);let l=i[o];l!=null&&u.push({origin:r,name:o??`${r}Message${d+1}`,body:bA(l)})}),u}function kIE({messages:e,messageSchemas:t}){let r=e.find(u=>u.origin==="client")?.name,i=e.find(u=>u.origin==="server")?.name,n=r!=null?t[r]:void 0,a=i!=null?t[i]:void 0;return{examplePublishMessage:n!=null&&r!=null?{type:r,payload:n}:void 0,exampleSubscribeMessage:a!=null&&i!=null?{type:i,payload:a}:void 0}}function w1_({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?u.push(c.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new hau({document:c,taskContext:t,options:r,namespace:a});return g1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:c})}else{let c=e,d=new mau({document:c,taskContext:t,options:r,namespace:a});return j1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:c})}}function S1_(e){return hf(e,ad.ASYNC_CONFIG)}var D1_="$request.";function E1_(e){let t=hf(e,ad.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:ezE(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function ezE(e){return e.startsWith(D1_)?e.slice(D1_.length):e}function M1_(e){let t=e;if(t.cursor!=null)return O6e.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return O6e.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return O6e.custom({results:r.results})}throw new Error("Invalid pagination extension")}function A1_(e,t){let r=hf(t,ad.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=hf(e,ad.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:M1_(i)}return M1_(r)}}function q1_(e){let t=tzE(e),r={};return lDc({obj:t,occurrences:r,breadcrumbs:[]}),r}function lDc({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)lDc({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)lDc({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function tzE(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?d5a(r.get):void 0,put:r?.put!=null?d5a(r.put):void 0,post:r?.post!=null?d5a(r.post):void 0,patch:r?.patch!=null?d5a(r.patch):void 0,delete:r?.delete!=null?d5a(r.delete):void 0}]))}}function d5a(e){return{...e,requestBody:e.requestBody!=null?ep(e.requestBody)?e.requestBody:rzE(e.requestBody):void 0}}function rzE(e){let t,r;for(let i in e.content){let n=Iq.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[Iq.MULTIPART_FORM_DATA]:r}}:e}var Pau=class{endpoints;parser=new sen;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var T1_="#/components/parameters/",C1_="#/components/responses/",B1_="#/components/examples/",I1_="#/components/requestBodies/",WJn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=q1_(t),this.options=n,this.source=a,this.filter=new Pau({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};if(Array.isArray(i)){let a=parseInt(n,10);if(isNaN(a)||a<0||a>=i.length)return{"x-fern-type":"unknown"};i=i[a]}else i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(ep(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(T1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(T1_.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(I1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(I1_.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(C1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(C1_.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(B1_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(B1_.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return ep(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var mnn=class extends WJn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var izE=Yo.object({lang:Yo.string(),label:Yo.optional(Yo.string()),source:Yo.string()}),fDc=Yo.array(izE);var z1_={README_EXT:"x-readme"};function nzE(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Tw(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function x1_(e){let t=hf(e,z1_.README_EXT);if(!Tw(t))return[];let r=t["code-samples"];if(!nzE(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function R1_(e,t,r){let n=(hf(t,ad.EXAMPLES)??[]).filter(s=>{let o=ZN.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=s5a(t,m$.REDOCLY_CODE_SAMPLES_KEBAB,fDc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...s5a(t,m$.REDOCLY_CODE_SAMPLES_CAMEL,fDc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&n.push({"code-samples":c.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=x1_(t);return d.length>0&&n.push({"code-samples":d}),n.map(EQt.unknown)}function N1_(e){let t=hf(e,ad.AVAILABILITY);if(t==="ga"||t==="generally-available")return b$.GenerallyAvailable;if(t==="beta"||t==="pre-release")return b$.Beta;if(t==="deprecated")return b$.Deprecated;if(e.deprecated)return b$.Deprecated}function jau(e){return{url:azE({url:e.url,variables:e.variables??{}}),description:e.description,name:ozE(e),audiences:hf(e,ad.AUDIENCES)}}function azE({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,encodeURIComponent(n));return e}function ozE(e){let t=hf(e,[ad.SERVER_NAME_V1,ad.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function F1_(e){return hf(e,ad.PARAMETER_NAME)}function L1_(e){return hf(e,ad.SDK_VARIABLE)}function wau({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let d=hf(c,ad.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=ep(c)?i.resolveParameterReference(c):c,o=s.required??!1,l=zK(s),b=[...n,s.name],g=g5(b,i.options.preserveSchemaIds),O=s.schema!=null?n0(s.schema,!o,i,b,a,i.namespace,!1,new Set,ror({schema:s,logger:i.logger})):o?Nl.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:ror({schema:s,logger:i.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):Nl.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Nl.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:ror({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:l,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!ep(s.schema)&&s.schema.default!=null){let P=s.schema.default;typeof P=="string"&&P.length>0&&(O=Nl.literal({nameOverride:void 0,generatedName:g,title:void 0,value:_x.string(P),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:F1_(s),availability:l,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:L1_(s)}):s.in==="header"?!uzE.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var uzE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function U1_(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:p5a(i,t)}}}function szE(e){return e.includes("json")||e==="*/*"}function dDc({content:e,context:t}){for(let[r,i]of Object.entries(e))if(Sau({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function Sau({mediaType:e,mediaTypeObject:t,context:r}){if(!szE(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:p5a(t,r)}}function Dau({content:e,context:t}){let r=dDc({content:e,context:t});if(!r)return;let[i,n]=r;return Sau({mediaType:i,mediaTypeObject:n,context:t})}function V1_(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:p5a(i,t)}}}function p5a(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=hf(e,m$.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=ep(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function czE({content:e,context:t}){for(let[r,i]of Object.entries(e))if(H1_({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function H1_({mediaType:e,mediaTypeObject:t,context:r}){if(Iq.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:p5a(t,r)}}function lzE({content:e}){for(let[t,r]of Object.entries(e))if($1_({mediaType:t,mediaTypeObject:r}))return[t,r]}function $1_({mediaType:e,mediaTypeObject:t}){if(Iq.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function G1_({mediaType:e}){return Iq.parse(e)?.isBinary()??!1}function fzE({content:e}){for(let[t,r]of Object.entries(e))if(G1_({mediaType:t}))return[t,r]}function dzE(e,t){let r=ep(e)?pDc(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!ep(n)&&n.type==="string"&&n.format==="binary")!=null}function Mau({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}){let c=fzE({content:e});if(c){let[b,g]=c;return ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}let d=lzE({content:e}),s=dDc({content:e,context:i}),o=pzE({json:s,multipart:d,document:r,visitor:{json:([b,g])=>ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),multipart:([b,g])=>ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),neither:()=>{}}});if(o)return o;let l=czE({content:e,context:i});if(l){let[b,g]=l;return ior({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}}function pzE({json:e,multipart:t,document:r,visitor:i}){if(!e&&!t)return i.neither();let[,n]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!n?.schema&&!a?.schema?i.neither():n?.schema&&a?.schema?n.schema&&dzE(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function ior({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:u,namespace:c}){let d=_zE({mediaTypeObject:t});if(G1_({mediaType:e}))return Tee.octetStream({description:r,source:u,sdkMethodName:d,contentType:e});let s=$1_({mediaType:e,mediaTypeObject:t}),o=s?.schema,l=s?.encoding;if(o){let O=ep(o)?pDc(o,i):{id:void 0,schema:o},m=n0(O.schema,!1,n,a,u,c,!1),P=[];if(m.type==="object")for(let D of m.properties){let{isFile:A,isOptional:M,isArray:E,description:T}=Eau({schema:D.schema});if(A){let z=W1_(D.key,l);P.push({key:D.key,schema:Smi.file({isOptional:M,isArray:E,description:T}),description:T,contentType:z,exploded:!1,encoding:z==null?n.options.defaultFormParameterEncoding:void 0})}else{let z=W1_(D.key,l);P.push({key:D.key,schema:Smi.json(D.schema),description:void 0,contentType:z,exploded:l?.[D.key]?.explode,encoding:z==null?n.options.defaultFormParameterEncoding:yzE(z)})}}return Tee.multipart({name:ep(o)&&n.getNumberOfOccurrencesForRef(o)===1?O.id:void 0,description:O.schema.description,properties:P,source:u,sdkMethodName:d})}let b=Sau({mediaType:e,mediaTypeObject:t,context:n});if(b){let O=n0(b.schema,!1,n,a,u,c,!0);return Tee.json({description:void 0,schema:O,contentType:b.contentType,fullExamples:b.examples,additionalProperties:!ep(b.schema)&&xJn(b.schema.additionalProperties,n.options),source:u,sdkMethodName:d})}let g=H1_({mediaType:e,mediaTypeObject:t,context:n});if(g!=null&&g.schema!=null){let O=n0(g.schema,!1,n,a,u,c,!1);return Tee.formUrlEncoded({schema:O,description:r,contentType:g.contentType,source:u,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:d})}}function _zE({mediaTypeObject:e}){return hf(e,ad.SDK_METHOD_NAME)}var hzE={"application/json":"json"};function yzE(e){return e?hzE[e]:void 0}function pDc(e,t){if(!e.$ref.startsWith(Onn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=b3i(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return ep(i)?pDc(i,t):{id:r,schema:i}}function Eau({schema:e,isOptional:t,isArray:r,description:i}){return bzE(e)?Eau({schema:e.value,isOptional:!0,isArray:r,description:e.description}):gzE(e)?Eau({schema:e.value,isOptional:t,isArray:r,description:e.description}):OzE(e)?Eau({schema:e.value,isOptional:t,isArray:!0,description:e.description}):vzE(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:i??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function vzE(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function bzE(e){return e.type==="optional"}function gzE(e){return e.type==="nullable"}function OzE(e){return e.type==="array"}function W1_(e,t){return t?.[e]?.contentType}var _Dc={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"},Q1_=new Set(Object.values(_Dc));var mzE=["200","201","202","204"];function K1_({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let c=PzE({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:mzE){let l=t[o];l!=null&&(d=!0,s==null&&(s=J1_({operationContext:e,response:l,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=J1_({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:c};case"streamingJson":case"streamingSse":return{value:s,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:c};default:Ao(s)}return{value:void 0,errors:c}}function J1_({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:c}){let d=ep(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=ep(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?OB.bytes({description:d.description,source:a,statusCode:c}):OB.file({description:d.description,source:a,statusCode:c});let s=U1_(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return OB.streamingJson({statusCode:c,description:d.description,responseProperty:hf(e.operation,ad.RESPONSE_PROPERTY),fullExamples:s.examples,schema:n0(s.schema,!1,i,n,a,u),source:a});case"sse":return OB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:n0(s.schema,!1,i,n,a,u),source:a,statusCode:c})}let o=Dau({context:i,content:d.content??{}});if(o){if(t!=null)switch(t){case"json":return OB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:n0(o.schema,!1,i,n,a,u),source:a,statusCode:c});case"sse":return OB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:n0(o.schema,!1,i,n,a,u),source:a,statusCode:c})}return OB.json({description:d.description,schema:n0(o.schema,!1,i,n,a,u),responseProperty:hf(e.operation,ad.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:c})}for(let[l,b]of Object.entries(d.content??{})){let g=Iq.parse(l);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo()||g.isMultiPartMixed())return OB.file({description:d.description,source:a,statusCode:c});if(g.isPlainText()){let O=b.schema;if(O==null)return OB.text({description:d.description,source:a,statusCode:c});let m=ep(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?OB.file({description:d.description,source:a,statusCode:c}):OB.text({description:d.description,source:a,statusCode:c})}}}}function PzE({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let d=ep(u)?t.resolveResponseReference(u):u,s=V1_(d.content??{},t),o=_Dc[c];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[c]={statusCode:c,nameOverride:void 0,generatedName:o,description:d.description,schema:n0(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function Tmi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:c,path:d,method:s,baseBreadcrumbs:o}=e,l=hf(c,ad.IDEMPOTENT),b=hf(c,[ad.REQUEST_NAME_V1,ad.REQUEST_NAME_V2]),g=[...o,"Request"],O=wau({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:d,httpMethod:s,source:a}),m=/{([^}]+)}/g,D=[...d.matchAll(m)].map(R=>R[1]).filter(R=>!O.pathParameters.some(U=>U.name===R));if(D.length>0)for(let R of D)O.pathParameters.push({name:R??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Nl.primitive({schema:vp.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0});let A=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let R=ep(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,U=Object.values(R.content).every(J=>wzE({mediaTypeObject:J})!=null),Y=[];if(U)return Y.push(...Object.entries(R.content).map(([J,X])=>{let ae=ior({mediaType:J,mediaTypeObject:X,description:R.description,document:u,context:new mnn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return Y1_({context:t,convertedParameters:O})&&ae!=null&&(ae.type==="json"||ae.type==="formUrlEncoded")&&ae.schema.type!=="object"&&c.requestBody!=null?ae=ior({mediaType:J,mediaTypeObject:X,description:R.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(ae=ior({mediaType:J,mediaTypeObject:X,description:R.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),ae}).filter(J=>J!=null)),Y.length===0?[void 0]:Y;{let J=Mau({content:R.content,description:R.description,document:u,context:new mnn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return Y1_({context:t,convertedParameters:O})&&J!=null&&(J.type==="json"||J.type==="formUrlEncoded")&&J.schema.type!=="object"&&c.requestBody!=null?J=Mau({content:R.content,description:R.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(J=Mau({content:R.content,description:R.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),[J]}})(),M=A.length>1,E=[...o,"Response"],T=K1_({operationContext:e,streamFormat:n,responses:c.responses,context:t,responseBreadcrumbs:E,responseStatusCode:r,source:a}),z=N1_(c),G=R1_(e,c,t),I=hf(c,ad.SERVER_NAME_V2);return A.map(R=>({summary:c.summary,internal:hf(c,m$.INTERNAL),idempotent:l,audiences:hf(c,ad.AUDIENCES)??[],operationId:c.operationId!=null&&i!=null?c.operationId+"_"+i:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:SzE({operationContext:e,request:R}),pathParameters:O.pathParameters,queryParameters:O.queryParameters,headers:O.headers,requestNameOverride:b??void 0,generatedRequestName:g5(M?jzE({breadcrumbs:g,request:R}):g,t.options.preserveSchemaIds),request:R,response:T.value,errors:T.errors,servers:I!=null?[{name:I,url:void 0,audiences:void 0}]:(c.servers??[]).map(U=>jau(U)),description:c.description,authed:DzE(c,u),availability:z,method:s,path:d,examples:G,pagination:e.pagination,source:a}))}function jzE({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function wzE({mediaTypeObject:e}){return hf(e,ad.SDK_METHOD_NAME)}function SzE({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function DzE(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function Y1_({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function Z1_({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,c=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=X1_({context:t,headerToIgnore:c,parameters:a}),l=X1_({context:t,headerToIgnore:c,parameters:u}),b=Tmi({operationContext:{...e,pathItemParameters:o,operationParameters:l,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=Tmi({operationContext:{...e,pathItemParameters:o,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.forEach(O=>{O.headers.push({name:c,schema:Nl.literal({nameOverride:void 0,generatedName:g5([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:_x.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:b,async:g}}function X1_({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=ep(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var hDc="stream";function rS_({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:Tmi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=k1_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=b3i(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=eS_({operation:e.operation,response:r.responseStream}),a=Tmi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+hDc}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,hDc]},context:t,streamFormat:r.format,suffix:hDc,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(o=>tS_(o,t)!==!1)});let u=k1_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=eS_({operation:e.operation,response:r.response}),d=Tmi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:c}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(o=>tS_(o,t)!==!0)}),{streaming:a,nonStreaming:d}}default:Ao(r)}}function k1_({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=ep(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Dau({content:n.content,context:e});if(a==null)return;let u=ep(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let c=u.properties?.[r.streamConditionProperty];c!=null&&ep(c)&&(c=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...c??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[Iq.APPLICATION_JSON]:{schema:d}}},schemaReference:ep(a.schema)?a.schema:void 0}}function eS_({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[Iq.APPLICATION_JSON]:{schema:t}}}}}function tS_(e,t){return e._visit({unknown:r=>{let i=ZN.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function iS_({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:c,sdkMethodName:d}=t,s=[...c,"Payload"],o=wau({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`),[];let l=n.operationId;if(l==null)return e.logger.error(`Skipping webhook ${a} because no operation id present`),[];if(u!=="POST"&&u!=="GET")return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`),[];let b=ep(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(b.content).map(([g,O])=>ior({mediaType:g,mediaTypeObject:O,description:b.description,document:i,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:n.summary,audiences:hf(n,ad.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:u,operationId:l,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:g5(s,e.options.preserveSchemaIds),payload:g.schema,description:n.description,examples:EzE(g.fullExamples),source:r}}).filter(g=>g!=null)}function EzE(e){if(e==null)return[];let t=[];for(let r of e){let i=O3i(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function yDc({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=hf(r,ad.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=MzE(r,e),u=A1_(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:AzE({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i)return{type:"webhook",value:iS_({context:e,operationContext:c,source:e.source})};let d=E1_(r);if(d!=null){let l=rS_({context:e,operationContext:c,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let s=S1_(r);if(s!=null){let l=Z1_({context:e,operationContext:c,asyncExtension:s,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:Tmi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function MzE(e,t){let r=hf(e,ad.SDK_METHOD_NAME),i=hf(e,ad.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function AzE({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(R_(`${r}_${i.split("/").join("_")}`));return a}function nS_(e,t,r,i){let n=[],a=oS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=qzE({operation:c.operation}),s=yDc({context:i,pathItemContext:{...u,method:c.method},operation:c.operation,convertToWebhook:d});s&&n.push(s)}return n}function aS_(e,t,r,i){let n=[],a=oS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=yDc({context:i,pathItemContext:{...u,method:c.method},operation:c.operation,convertToWebhook:!0});d&&n.push(d)}return n}function oS_(e){let t=[];return e.get!=null&&t.push({method:O$.Get,operation:e.get}),e.post!=null&&t.push({method:O$.Post,operation:e.post}),e.put!=null&&t.push({method:O$.Put,operation:e.put}),e.delete!=null&&t.push({method:O$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:O$.Patch,operation:e.patch}),e.head!=null&&t.push({method:O$.Head,operation:e.head}),t}function qzE({operation:e}){return hf(e,[ad.WEBHOOK])??!1}function uS_(e){let t=hf(e,ad.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=hf(e,ad.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function sS_(e){return hf(e,ad.FERN_BASIC_AUTH)}function vDc(e,t){if(ep(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return TzE(e,t)}function TzE(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=hf(e,m$.BEARER_FORMAT),i=hf(e,ad.FERN_HEADER_AUTH);return jU.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??hf(e,ad.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let r=hf(e,ad.FERN_BEARER_TOKEN);return jU.bearer({tokenVariableName:r?.name??hf(e,ad.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let r=sS_(e),i=uS_(e);return jU.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return jU.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return jU.oauth({scopesEnum:CzE(e,t)})}}function CzE(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=v3i({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=bA(i);if(n.type==="enum")return n}}function cS_(e){return hf(e,ad.BASE_PATH)}var BzE=Yo.record(Yo.string(),Yo.object({summary:Yo.string().optional(),description:Yo.string().optional()}));function lS_({document:e,context:t}){return s5a(e,ad.GROUPS,BzE,t.logger)}function fS_({context:e,document:t}){return hf(t,ad.FERN_VERSION)??void 0}function dS_(e){let t=hf(e,ad.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?c5a({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function pS_(e){let t=hf(e,ad.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?c5a({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function _S_(e,t){let r=hf(e,ad.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:g5([i],t),title:n.title,schema:xw.string({default:NJn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var IzE="webhooks";function hS_(e){return hf(e,IzE)??{}}var Aau=class extends WJn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new mnn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function yS_(e){return hf(e,ad.RESOLUTIONS)}function vS_({openapi:e}){let t=yS_(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=zzE({openapi:e,schemaReference:a,schemaName:i.name}),e=bS_({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function zzE({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function bS_({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return bS_({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let c=a[a.length-1];return c==null||(u[c]={$ref:r}),e}function OS_({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=vS_({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,R])=>vDc(R,i)==null?[]:[I,vDc(R,i)])),u=new Set(...Object.entries(a).map(([I,R])=>R.type==="basic"||R.type==="bearer"?"Authorization":R.type==="header"?R.headerName:null)),c=_S_(e,r.preserveSchemaIds),d=dS_(e),s=pS_(e),o=r.audiences??[],l=[],b=[],g=new Aau({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,R])=>{if(R==null)return;t.logger.debug(`Converting path ${I}`);let U=nS_(I,R,e,g);for(let Y of U){let J=gS_({operation:Y});if(!(o.length>0&&!o.some(X=>J.includes(X))))switch(Y.type){case"async":l.push(...Y.sync),l.push(...Y.async);break;case"http":l.push(...Y.value);break;case"streaming":l.push(...Y.streaming),Y.nonStreaming&&l.push(...Y.nonStreaming);break;case"webhook":b.push(...Y.value);break;default:Ao(Y)}}}),Object.entries(hS_(e)).forEach(([I,R])=>{if(R==null)return;t.logger.debug(`Converting path ${I}`);let U=aS_(I,R,e,g);for(let Y of U){let J=gS_({operation:Y});o.length>0&&!o.some(X=>J.includes(X))||b.push(...Y.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,R])=>{let U=hf(R,ad.SDK_NAMESPACE);if(!ep(R)){let Y=hf(R,ad.IGNORE);if(Y!=null&&Y)return[];if(Q1_.has(I))return[I,n0({...R,"x-fern-type-name":`${I}Body`},!1,g,[I],i,U??n)]}return[I,n0(R,!1,g,[I],i,U??n)]}).filter(I=>I.length>0)),m=xzE(O,g,i),P=RzE(m,g),D={};for(let[I,R]of Object.entries(P)){let U=bA(R);g.isSchemaExcluded(I)||(D[I]=U,t.logger.debug(`Converted schema ${I}`))}let A=new m3i(P,g.nonRequestReferencedSchemas,g),M=b.map(I=>{let U=I.examples;if(!r.disableExamples&&U.length===0){let Y=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Y!=null&&(U=[{name:void 0,description:void 0,payload:Y}])}return{...I,payload:bA(I.payload),examples:U}}),E=new vau(P,g,d),T=l.map(I=>{let R=I.examples,U=R;if(!r.disableExamples&&(R.length===0||R.every(f5a))){let X=E.buildEndpointExample(I);X.length>0&&(U=[...X,...R.filter(ae=>!f5a(ae))])}let Y=I.request,J=I.response;return{...I,request:Y?.type==="json"||Y?.type==="formUrlEncoded"?{...Y,schema:bA(Y.schema)}:Y,response:J?.type==="json"?{...J,schema:bA(J.schema)}:J,queryParameters:I.queryParameters.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,availability:X.availability,source:X.source})),pathParameters:I.pathParameters.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,variableReference:X.variableReference,availability:X.availability,source:X.source})),headers:I.headers.map(X=>({description:X.description,name:X.name,schema:bA(X.schema),parameterNameOverride:X.parameterNameOverride,env:X.env,availability:X.availability,source:X.source})),examples:U,errors:Sd(I.errors,X=>{let ae=X.fullExamples?.map(pe=>{let de=O3i(pe.value);if(de!=null)return{name:pe.name,description:pe.description,example:de}}).filter(yy);if(ae?.length===0){let pe=A.buildExample({schema:X.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});pe!=null&&ae.push({name:void 0,description:void 0,example:pe})}return{generatedName:X.generatedName,nameOverride:X.nameOverride,schema:bA(X.schema),description:X.description,source:X.source,examples:ae}})}}),z=lS_({document:e,context:g});return{apiVersion:fS_({context:g,document:e}),basePath:cS_(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(z??{}).map(([I,R])=>[I,{summary:R.summary??void 0,description:R.description??void 0}])),servers:(e.servers??[]).map(I=>jau(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:T,webhooks:M,channels:{},groupedSchemas:UJn(n,D),securitySchemes:a,hasEndpointsMarkedInternal:T.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:c,globalHeaders:d,idempotencyHeaders:s}}function xzE(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},c=t.getReferencesFromDiscriminatedUnion(u);if(c==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!c.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!c.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=mS_({schema:a,schemas:e});for(let o of[...new Set(s)]){let l=i[o]??e[o];l==null||l.type!=="object"||(i[o]={...l,type:"object",properties:l.properties.filter(b=>!c.discriminants.has(b.key)),allOfPropertyConflicts:l.allOfPropertyConflicts.filter(b=>!c.discriminants.has(b.propertyKey))})}}return i}function RzE(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let c=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&c.push({...s,schema:Nl.literal({nameOverride:void 0,generatedName:g5([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:_x.string(o),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else c.push(s);let d={...n,type:"object",properties:c};r[i]=d}return r}function mS_({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...mS_({schema:n,schemas:t}))}return r}function qau(e){return[...new Set(e)]}function gS_({operation:e}){let t=[];switch(e.type){case"async":t=qau(e.async.flatMap(r=>r.audiences));break;case"http":t=qau(e.value.flatMap(r=>r.audiences));break;case"streaming":t=qau(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=qau(e.value.flatMap(r=>r.audiences));break;default:Ao(e)}return t}function Pnn({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:TK.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=OS_({taskContext:e,openApi:n.value,options:qQt({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=FzE(i,u);break}case"asyncapi":{let u=w1_({document:n.value,taskContext:e,options:qQt({options:n.settings,overrides:r}),source:a,asyncApiOptions:NzE({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(c=>({...c,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=PS_(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Ao(n)}}return i}function NzE({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??$w_.naming}}function FzE(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:PS_(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function PS_(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var QI_=ui(Dcu(),1),Ecu={config:new QI_.Config({apis:{},styleguide:{plugins:[tDc],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function LKn(e){if(e.settings==null&&e.raw?.api?.auth==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.raw?.api?.auth!=null&&(t.auth=e.raw?.api?.auth),t}function b9a(e){return e.swagger!=null}function qTc(e){return e.openapi!=null}function g9a({options:e,overrides:t}={}){return{...qQt({options:e,overrides:t}),...Y8a({options:e,overrides:t})}}function K3i(e,t={}){return{...Object.fromEntries(r6(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...r6(e.importedDefinitions).reduce((r,[i,n])=>({...r,...HIa(K3i(n.definition,{defaultURL:n.url}),(a,u)=>GN(i,wy.of(u)))}),{})}}function O9a(e,t={}){return{...Object.fromEntries(r6(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...r6(e.importedDefinitions).reduce((r,[i,n])=>({...r,...HIa(O9a(n.definition,{defaultURL:n.url}),(a,u)=>GN(i,wy.of(u)))}),{})}}function Kmi(e){return{...O9a(e),...K3i(e)}}function Uue(e,t){return Kmi(e.definition)[t]?.contents}function V6(e,t){for(let[r,i]of r6(Kmi(e.definition)))t(r,i.contents,{isPackageMarker:WZi(r)===SS,defaultUrl:i.defaultUrl})}function Jnn(e,t){for(let[r,i]of r6(O9a(e.definition)))t(r,i.contents)}function C6e({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Bs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Bs.dim(r)),i.join(`